user2424160
user2424160

Reputation: 267

How can i make the python program to check linux services

I want to make simple python script , which i can run on cron job. i just want to see if these services are currently running or stopped

Httpd
mysql

How should i check them with python.

Do i need to parse the output of netstat -tlnp

Upvotes: 7

Views: 37893

Answers (6)

Falcon Ryu
Falcon Ryu

Reputation: 485

   import subprocess
    
    
    service = "apache2"
    
    p =  subprocess.Popen(["systemctl", "is-active",  service], stdout=subprocess.PIPE)
    (output, err) = p.communicate()
    output = output.decode('utf-8')
    
    print(output)

The Python program will check if the service is running. If it running, the output will be "active" otherwise the output will be "inactive".

Hope it helps!!

Upvotes: 12

Michele
Michele

Reputation: 29

i used the code of Jossef and I added some features

Thanks so Much Jossef

    import subprocess
    import os
    import subprocess
    import requests

    def is_service_running(name):
        with open(os.devnull, 'wb') as hide_output:
            exit_code = subprocess.Popen(['service', name, 'status'], stdout=hide_output, stderr=hide_output).wait()
            return exit_code == 0

# CLASS SLACK TO SEND NOTIFICATION
    class Slack:
        def __init__(self,report):
            webhook = 'https://hooks.slack.com/services/T92JCJW59/B012Qxxxxxxxxxxxxxxxxxxxxxxx'
            response = requests.post(webhook, json=report, headers={'Content-Type': 'application/json'})
            if response.ok:
                json_data = response.text
                self.result = json_data

    if __name__ == '__main__':
        if not is_service_running('mysqld'):
            print ('mysql is not running')
            os.system("systemctl restart mysqld")
            result_dict = ("*MICHELONE SLACK* \n*MYSQL DOWN IM GOING TO RESTART* ")
            slack_report = {"attachments": [{"fallback": "*MICHELONE SLACK*", "color": "#FF0000", "text": result_dict}]}
            slack_push_log = Slack(slack_report)
        else:
            print("ALL OK")
        if not is_service_running('httpd'):
            print('httpd is not running')
            os.system("systemctl restart httpd")
            result_dict = ("*MICHELONE SLACK* \n*APACHE DOWN IM GOING TO RESTART* ")
            slack_report = {"attachments": [{"fallback": "*MICHELONE SLACK*", "color": "#FF0000", "text": result_dict}]}
            slack_push_log = Slack(slack_report)

        else:
            print("ALL OK")

Upvotes: 1

nic
nic

Reputation: 443

If you use the subprocess module you can do this without spawning a shell, which the command module will do. (You probably don't need a separate shell for this and there might be some security concerns by doing so).

Note that this also gives you possibility to act on errors (see the err variable below), for example you can try to restart services that are down etc.

import subprocess
p = subprocess.Popen(["ps", "-a"], stdout=subprocess.PIPE)
out, err = p.communicate()
if ('Httpd' in str(out)):
    print('Httpd running')
if ('mysql' in str(out)):
    print('mysql running')

http://docs.python.org/2/library/subprocess.html

Upvotes: 4

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34227

If your services are properly registered and support status reporting (init script or upstart job), Use the linux command

service <name> status

If the service is running, command will return exit code 0

import os
import subprocess


def is_service_running(name):
    with open(os.devnull, 'wb') as hide_output:
        exit_code = subprocess.Popen(['service', name, 'status'], stdout=hide_output, stderr=hide_output).wait()
        return exit_code == 0


if not is_service_running('mysql'):
    print 'mysql is not running'
  • the os.devnull is a bonus, to hide the output of the child process.

Upvotes: 2

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 3838

Use psutils class. Its fantastic and cross platform.. Following are the functional usage..

import psutil
>>> psutil.get_pid_list()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
>>>
>>> p = psutil.Process(7055)
>>> p.name
'python'
>>> p.exe
'/usr/bin/python'
>>> p.getcwd()
'/home/giampaolo'
>>> p.cmdline
['/usr/bin/python', 'main.py']
>>>
>>> str(p.status)
'running'
>>> p.username
'giampaolo'
>>> p.create_time
1267551141.5019531
>>> p.terminal
'/dev/pts/0'
>>>
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.gids
group(real=1000, effective=1000, saved=1000)
>>>
>>> p.get_cpu_times()
cputimes(user=1.02, system=0.31)
>>> p.get_cpu_percent(interval=1.0)
12.1
>>> p.get_cpu_affinity()
[0, 1, 2, 3]
>>> p.set_cpu_affinity([0])
>>>
>>> p.get_memory_percent()
0.63423
>>> p.get_memory_info()
meminfo(rss=7471104, vms=68513792)
>>> p.get_ext_memory_info()
meminfo(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0,     
data=5754880,dirty=0)
>>> p.get_memory_maps()
[mmap(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
 mmap(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
 mmap(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245,  
swap=0),
 mmap(path='[heap]', rss=54653, anonymous=8192, swap=0),
 mmap(path='[stack]', rss=1542, anonymous=166, swap=0),
 ...]
>>>
>>> p.get_io_counters()
io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
>>>
>>> p.get_open_files()
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
>>>
>>> p.get_connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
            remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
 connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
            remote_address=('72.14.234.100', 80), status='CLOSING'),
 connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
            remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
 connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
            remote_address=('72.14.234.83', 443), status='SYN_SENT')]
>>>
>>> p.get_num_threads()
4
>>> p.get_num_fds()
8
>>> p.get_num_ctx_switches()
amount(voluntary=78, involuntary=19)
>>>
>>> p.get_threads()
[thread(id=5234, user_time=22.5, system_time=9.2891),
 thread(id=5235, user_time=0.0, system_time=0.0),
 thread(id=5236, user_time=0.0, system_time=0.0),
 thread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.get_nice()
0
>>> p.set_nice(10)
>>>
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.wait(timeout=3)
0
>>>
>>> psutil.test()
USER         PID %CPU %MEM     VSZ     RSS TTY        START    TIME  COMMAND
root           1  0.0  0.0   24584    2240 ?          Jun17   00:00  init
root           2  0.0  0.0       0       0 ?          Jun17   00:00  kthreadd
root           3  0.0  0.0       0       0 ?          Jun17   00:05  ksoftirqd/0
...
giampaolo  31475  0.0  0.0   20760    3024 /dev/pts/0 Jun19   00:00  python2.4
giampaolo  31721  0.0  2.2  773060  181896 ?          00:04   10:30  chrome
root       31763  0.0  0.0       0       0 ?          00:05   00:00  kworker/0:1
>>>

Upvotes: 5

kramer65
kramer65

Reputation: 53943

You could use the commands module to run the ps shell argument:

import commands
output = commands.getoutput('ps -A')
if 'Httpd' in output:
    print("Httpd is up an running!")

[edit] I just read up on the commands module, and although working fine, it seems to be deprecated since Python 2.6 and even removed in Python 3.x. So if you are on Python 3 or want to be ready for future porting to Python 3, you can use the subprocess module:

import subprocess
output = subprocess.check_output(['ps', '-A'])
if 'Httpd' in output:
    print("Httpd is up an running!")

Upvotes: 4

Related Questions