IT Share you

실행중인 프로세스를 확인하는 Bash 스크립트

shareyou 2021. 1. 9. 10:55
반응형

실행중인 프로세스를 확인하는 Bash 스크립트


프로세스가 실행 중인지 확인하기 위해 bash 스크립트를 작성했습니다. ps 명령은 항상 종료 코드 1을 반환하므로 작동하지 않습니다. 명령 줄에서 ps 명령을 실행하면 $? 올바르게 설정되어 있지만 스크립트 내에서는 항상 1입니다.

#!/bin/bash
SERVICE=$1

ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
    echo "`date`: $SERVICE service running, everything is fine"
else
    echo "`date`: $SERVICE is not running"
fi

Bash 버전 : GNU bash, 버전 3.2.25 (1) -release (x86_64-redhat-linux-gnu)


몇 가지 매우 간단한 방법이 있습니다.

pgrep procname && echo Running 
pgrep procname || echo Not running 
killall -q -0 procname && echo Running 
pidof procname && echo Running

BASH 버전 3.2.29에서 버전을 사용해 보았지만 정상적으로 작동했습니다. 그러나 위에서 제안한 것과 같은 작업을 수행 할 수 있습니다. 예를 들면 다음과 같습니다.

#!/bin/sh

SERVICE="$1"
RESULT=`ps -a | sed -n /${SERVICE}/p`

if [ "${RESULT:-null}" = null ]; then
    echo "not running"
else
    echo "running"
fi

이 트릭은 저에게 효과적입니다. 이것이 당신을 도울 수 있기를 바랍니다. 다음을 checkRunningProcess.sh로 저장합시다.

#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "Running"
else
    echo "Not Running"
fi

checkRunningProcess.sh를 실행 가능하게 만든 다음 사용하십시오.
사용할 예.

20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

나는 이것을 사용하여 10 초마다 프로세스가 실행 중인지 확인하고 그렇지 않은 경우 시작하고 여러 인수를 허용합니다.

#!/bin/sh

PROCESS="$1"
PROCANDARGS=$*

while :
do
    RESULT=`pgrep ${PROCESS}`

    if [ "${RESULT:-null}" = null ]; then
            echo "${PROCESS} not running, starting "$PROCANDARGS
            $PROCANDARGS &
    else
            echo "running"
    fi
    sleep 10
done    

스크립트 이름에 $ SERVICE가 포함되어 있지 않은지 확인하십시오. 그렇다면 ps 결과에 표시되므로 스크립트는 항상 서비스가 실행 중이라고 생각합니다. 다음과 같이 현재 파일 이름에 대해 grep 할 수 있습니다.

#!/bin/sh
SERVICE=$1
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
    echo "$SERVICE service running, everything is fine"
else
    echo "$SERVICE is not running"
fi

일하는 것.

! / bin / bash
수표 = $ 0
서비스 = $ 1
DATE =`날짜`
OUTPUT = $ (ps aux | grep -v grep | grep -v $ CHECK | grep $ 1)
에코 $ OUTPUT
if [ "$ {# OUTPUT}"-gt 0];
then echo "$ DATE : $ SERVICE 서비스 실행 중, 모든 것이 정상입니다"
else echo "$ DATE : $ SERVICE가 실행되고 있지 않습니다."
fi

bash에서 / dev / null 접근 방식으로 약간의 성공에도 불구하고. 솔루션을 cron에 푸시했을 때 실패했습니다. 반환 된 명령의 크기를 확인하는 것은 완벽하게 작동했습니다. ampersrand는 bash가 종료되도록합니다.

#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if  ${#result}> 0 
then
        echo " Working!"
else
        echo "Not Working.....Restarting"
        /usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi

#! / bin / bash
ps axho comm | grep $ 1> / dev / null
결과 = $?
echo "종료 코드 : $ {result}"
if [ "$ {result}"-eq "0"]; 그때
echo "`date` : $ SERVICE 서비스 실행 중, 모든 것이 정상입니다."
그밖에
echo "`date` : $ SERVICE가 실행되고 있지 않습니다."
/etc/init.d/$1 재시작
fi

이 같은


도움이되는 힌트입니다. 스크립트를 시작할 때 서비스가 실행 중인지 확인해야했기 때문에 서비스를 떠났을 때와 같은 상태로 둘 수있었습니다. 나는 이것을 사용하여 결국 :

   HTTPDSERVICE=$(ps -A | grep httpd | head -1)

   [ -z "$HTTPDSERVICE" ] &&  echo "No apache service running." 

나는 문제를 발견했다. ps -ae 대신 ps -a가 작동합니다.

I guess it has to do with my rights in the shared hosting environment. There's apparently a difference between executing "ps -a" from the command line and executing it from within a bash-script.


A simple script version of one of Andor's above suggestions:

!/bin/bash

pgrep $1 && echo Running

If the above script is called test.sh then, in order to test, type: test.sh NameOfProcessToCheck

e.g. test.sh php


I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process "firefox" and it tires things more nicely first, then moves on to kill.

# -- NICE: try to use killall to stop process(s)
killall ${1} > /dev/null 2>&1 ;sleep 10

# -- if we do not see the process, just end the function
pgrep ${1} > /dev/null 2>&1 || return

# -- UGLY: Step trough every pid and use kill -9 on them individually
for PID in $(pidof ${1}) ;do

    echo "Terminating Process: [${1}], PID [${PID}]" 
    kill -9 ${PID} ;sleep 10

    # -- NASTY: If kill -9 fails, try SIGTERM on PID
    if ps -p ${PID} > /dev/null ;then
        echo "${PID} is still running, forcefully terminating with SIGTERM"
        kill -SIGTERM ${PID}  ;sleep 10
    fi

done

# -- If after all that, we still see the process, report that to the screen.
pgrep ${1} > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [${1}]" || echo "Terminate process [${1}] : SUCCESSFUL"

I need to do this from time to time and end up hacking the command line until it works.

For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":

ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'

Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:

#!/bin/bash

VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`

if [ ! -z "$VNC_STRING" ]; then
    echo "The VNC STRING is not empty, therefore your process is running."
fi

The "sed" part trims the path to the exact token and might not be necessary for your needs.

Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.

I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).

It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.

It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.

#!/bin/bash

SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`

if  [ $SSH_COUNT = "2" ]; then
    echo "There are already 2 SSH tunnels."
elif  [ $SSH_COUNT = "1" ]; then
    echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
    echo "connecting 2 SSH tunnels."
    ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
    ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi

if  [ $VNC_COUNT = "2" ]; then
    echo "There are already 2 VNC sessions."
elif  [ $VNC_COUNT = "1" ]; then
    echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
    echo "launching 2 vnc sessions."
    vncviewer.exe localhost:1 &
    vncviewer.exe localhost:4 &
fi

This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.


A solution with service and awk that takes in a comma-delimited list of service names.

First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.

#!/usr/bin/env bash

# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1

ALL_SERVICES_STARTED=true

if [ $EUID -ne 0 ]; then
  if [ "$(id -u)" != "0" ]; then
    echo "root privileges are required" 1>&2
    exit 1
  fi
  exit 1
fi

for service in ${SERVICES//,/ }
do
    STATUS=$(service ${service} status | awk '{print $2}')

    if [ "${STATUS}" != "started" ]; then
        echo "${service} not started"
        ALL_SERVICES_STARTED=false
    fi
done

if ${ALL_SERVICES_STARTED} ; then
    echo "All services started"
    exit 0
else
    echo "Check Failed"
    exit 1
fi

The most simple check by process name :

 bash -c 'checkproc ssh.exe ; while  [ $? -eq 0  ] ; do  echo "proc running";sleep 10; checkproc ssh.exe; done'

ReferenceURL : https://stackoverflow.com/questions/2903354/bash-script-to-check-running-process

반응형