Python code to check if service is running or not.?
I might be a few years late to answer this.. but here is an easy solution I've found
import os # I think it's better to use subprocess for this. but quick code for example
status = os.system('systemctl is-active --quiet service-name')
print(status) # will return 0 for active else inactive.
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
Using subprocess :
import subprocess
stat = subprocess.call(["systemctl", "is-active", "--quiet", "ssh"])
if(stat == 0): # if 0 (active), print "Active"
print("Active")
Also, I found this answer that explains well why use subprocess instead of os.system
Little bit off-topic answer here (for python3).
In python3 you can use pystemd for this purpose. It talks with systemd via it's dbus API, so it's better than just executing systemctl
and parsing it's output.
P.S. It's better to use subprocess module instead of using os.system().