且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于检查服务是否正在运行的Python代码.

更新时间:2023-12-05 12:07:40

只需使用

Simply by using os.system(). You then get the return code of the execution; 0 means running, 768 stopped

>>> import os
>>> stat = os.system('service sshd status')
Redirecting to /bin/systemctl status  sshd.service
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2017-10-05 09:35:14 IDT; 29s ago
     Docs: man:sshd(8)
           man:sshd_config(5)
  Process: 620 ExecStart=/usr/sbin/sshd $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 634 (sshd)
   CGroup: /system.slice/sshd.service
           └─634 /usr/sbin/sshd
>>> stat
0  <--  means service is running

>>> os.system('service sshd stop')
Redirecting to /bin/systemctl stop  sshd.service
0  <-- command succeeded

>>> os.system('service sshd status')
Redirecting to /bin/systemctl status  sshd.service
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Thu 2017-10-05 09:41:58 IDT; 10s ago
     Docs: man:sshd(8)
...
768 <-- service not running

返回代码是从执行中返回的代码.在 服务 联机帮助页中:>

The return code is the one returned from the execution. From the service manpage:

退出代码 服务会调用初始化脚本并返回其返回的状态.

EXIT CODES service calls the init script and returns the status returned by it.

所以这取决于执行的初始化脚本.您可以放心地说 0以外的任何返回码表示该服务未运行.

So it's up to the init script executed. You can safely say any return code other than 0 means the service is not running.

您可以使用以下方法检查该进程是否正在运行:

You can either check if the process is running instead using:

>>> os.system('ps aux | grep sshd | grep -v grep | wc -l')
2
>>> os.system('ps aux | grep sshd123 | grep -v grep | wc -l')
0