21

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

S Andrew
  • 5,592
  • 27
  • 115
  • 237

7 Answers7

39

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.
Dylan Westra
  • 611
  • 1
  • 5
  • 10
19

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
Chen A.
  • 10,140
  • 3
  • 42
  • 61
14

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().

Roman Kovtuh
  • 561
  • 8
  • 14
9

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

lucrp
  • 582
  • 9
  • 11
-1

You can see my code for reference:

#!/usr/bin/env python
import os

def isActive(daemon):
    command = "systemctl is-active " + daemon + " > tmp"
    os.system(command)
    with open('tmp') as tmp:
        tmp = tmp.read()
        if "active" in tmp:
            os.remove('tmp')
            return 1
    return 0


sshd = "sshd"

print(isActive(sshd))
Huan Phan
  • 11
  • 1
  • 1
    What are the benefits of your proposed approach over the existing answers? – Jeremy Caney May 14 '20 at 02:52
  • Hello @Jeremy Caney: thank you for reminding me. I just give another approach and if someone searching google for solutions they will have another choice. – Huan Phan May 14 '20 at 03:15
-1

use os.popen method to get output of a cmd command and check it by if statement

import os

STATE = os.popen('sc query ServiceName').read()
if STATE.find("RUNNING") != -1:
  print("Service is working")
else:
  print("Service is not working")
Mohammad
  • 21
  • 6
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney May 15 '23 at 01:47
-5

The first thing you need to do is define what you mean by running:

  • systemd gives you a ok status
  • process is running/shows up in PS
  • things actually work, ie can get a web page or ssh into box on local host

Then write something that preforms your test or find a tool that works for you

ms4720
  • 327
  • 1
  • 11