简体   繁体   中英

Python script to check server status

I want to check some service status (like MySQL, Apache2) using python. I wrote a simple script.

#!/usr/bin/python
from subprocess import call

command = raw_input('Please enter service name : ')

call(["/etc/init.d/"+command, "status"])

This script will request the user to enter the service and display its results on terminal as follows.

● apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since සි 2016-06-17 09:16:10 IST; 5h 43min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 2313 ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS)
  Process: 1560 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/apache2.service
           ├─1941 /usr/sbin/apache2 -k start
           ├─2332 /usr/sbin/apache2 -k start
           ├─2333 /usr/sbin/apache2 -k start
           ├─2334 /usr/sbin/apache2 -k start
           ├─2335 /usr/sbin/apache2 -k start
           └─2336 /usr/sbin/apache2 -k start

I just want to take this line for each service Active: active (running) and check if that is running and if not I want to ask do you want to start it.

Can some one help me to do this? Thanks in advance

I think what you want is to capture the output. Something along the lines of:

status = subprocess.check_output("YOUR COMMAND", shell=True)
if ("Active: active (running)" in status):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM