서비스가 스크립트에서 실행 중인지 테스트하는 “적절한”방법 수동으로 수행하는 방법을

내 문제:

bash 스크립트를 작성 중이며 주어진 서비스가 실행되고 있는지 확인하고 싶습니다.

이 작업을 수동으로 수행하는 방법을 알고 있습니다 $ service [service_name] status.

그러나 (특히 systemd로 이동 한 이후) 구문 분석하기가 약간 까다로운 전체 텍스트를 인쇄합니다. 간단한 출력 또는 확인할 수있는 반환 값을 가진 스크립트에 대한 명령이 있다고 가정했습니다.

그러나 인터넷 검색은 단지 “아, 그냥 ps aux | grep -v grep | grep [service_name]“결과 의 톤을 산출합니다 . 그것은 최선의 방법이 될 수 없습니까? 해당 명령의 다른 인스턴스가 실행 중이지만 SysV init 스크립트에 의해 시작되지 않은 경우 어떻게됩니까?

아니면 그냥 닥치고 작은 pgrep로 손을 더럽혀 야합니까?



답변

systemctl이에 대한 is-active부속 명령이 있습니다.

systemctl is-active --quiet service

service활성화 되면 상태 0으로 종료하고 그렇지 않으면 0이 아니므로 스크립트에 이상적입니다.

systemctl is-active --quiet service && echo Service is running

생략 --quiet하면 현재 상태도 표준 출력으로 출력됩니다.

don_crissti가 지적한 바와 같이 , 서비스를 제공하기 위해 아무것도 실행되고 있지 않더라도 일부 장치는 활성화 될 수 있습니다.“RemainAfterExit”로 표시된 장치는 성공적으로 종료되면 활성화 된 것으로 간주됩니다 (데몬이 필요없는 서비스를 제공한다는 아이디어) ( 예 : 시스템의 일부 측면을 구성합니다). 그러나 데몬과 관련된 장치는 데몬이 여전히 실행중인 경우에만 활성화됩니다.


답변

systemctl스크립팅에 적합한 모드가 있습니다. show대신에 사용 status하고 -p/ --properties--value옵션을 추가하여 원하는 출력 만 얻으십시오.

다음은 Ubuntu 17.04 시스템의 예입니다.

$ systemctl show -p SubState --value NetworkManager
running

달리기 (또는 달리)는입니다 SubState. 서비스가 활성화되어 있는지 확인하려면이 속성을 사용하십시오.ActiveState

$ systemctl show -p ActiveState --value x11-common
inactive
$ systemctl show -p SubState --value x11-common
dead

의 메모 man:

show [PATTERN...|JOB...]
           Show properties of one or more units, jobs, or the manager
           itself. If no argument is specified, properties of the
           manager will be shown. If a unit name is specified, properties
           of the unit are shown, and if a job ID is specified,
           properties of the job are shown. By default, empty properties
           are suppressed. Use --all to show those too. To select specific
           properties to show, use --property=. This command is intended
           to be used whenever computer-parsable output is required. Use
           status if you are looking for formatted human-readable output.

-p, --property=
           When showing unit/job/manager properties with the show command,
           limit display to properties specified in the argument. The
           argument should be a comma-separated list of property names,
           such as "MainPID". Unless specified, all known properties are
           shown. If specified more than once, all properties with the
           specified names are shown. Shell completion is implemented for
           property names.

--value
           When printing properties with show, only print the value, and
           skip the property name and "=".

답변

Zanna의 답변을 보완하기 위해에 대한 --value옵션 이 systemd 버전 230에systemctl show 도입되었습니다 . 따라서 데비안 제시와 같은 특정 배포판에서는 사용할 수 없습니다.

이 경우 sed를 사용하여 옵션을 에뮬레이션 할 수 있습니다.

$ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
active
$ systemctl show -p SubState sshd | sed 's/SubState=//g'
running

답변

나는 이것이 명령 줄 실행이나 스크립트를 만드는 데 유용하다는 것을 알았습니다.

@StephenKitt에서 복사 함

서비스가 다운되었는지 확인하고 서비스를 다시 시작합니다.

systemctl is-active --quiet <service name> || <service name> restart

||systemctl 반환 값은 작성자 바와 같이 활성 상태가 아니라면 비 – 제로 의미가 있는지 검사한다.


답변

나는 그러나 systemctl을 사용하고 활성와 함께 파티에 너무 늦게입니다 &&||않을 경우 모든 시간이 될 스크립트에서이에. 아래는 바람둥이에 사용 된 방법이지만 여러 서비스를 확인해야하지만 여기서 범위를 벗어난 경우 인수를 사용하고 서비스 이름을 인수로 전달하는 방법에서 사용할 수 있습니다.

STATUS=`systemctl is-active tomcat.service`
  if [[ ${STATUS} == 'active' ]]; then
    echo "Execute your tasks ....."
  else
    echo " Service not running.... so exiting "
    exit 1
  fi

이것이 내가 이용하는 방법입니다 .. 단지 내 것을 공유합니다.

간단하고 쉬운 것들을 위해 여기에 설명 된 다른 것들을 따르십시오.

systemctl -q is-active tomcat.service  && echo "Tomcat Runnung" || echo "Service is not running at all "

답변

Oxmel의 답변에서와 같이 sed 명령을 사용하는 대신 cut -d'=' -f 2쿼리되는 모든 종류의 속성 에 사용하면 충분합니다 .

예를 들면 다음과 같습니다.

$ systemctl show -p ActiveState sshd | cut -d'=' -f2
active
$ systemctl show -p SubState sshd | cut -d'=' -f2
running

답변

이 위대한 작은 스크립트를 발견했습니다.

#!/bin/bash
service=replace_me_with_a_valid_service

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
  echo "$service is running!!!"
else
  /etc/init.d/$service start
fi

출처