Answer a question

I am using python2.7 to check if a service is running or not. I have made my own service and placed it inside /etc/init.d. I have a raspberry on which I am using it.

Now to normally check the status of service, we can do:

service my_service status

But how can I get the status of service from the python code.

Thanks

Answers

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.

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
Logo

更多推荐