Use Python to check if a process is running or not

# Python2
#!/usr/local/bin/python
import BaseHTTPServer
import subprocess

HOST_NAME = ''  # Use your server ip
PORT_NUMBER = 9000  # Each port, should represent a process

PROCESS_NAME = "nginx"

class ServerHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(s):
        try:
            subprocess.check_output("pgrep -f " + PROCESS_NAME, shell=True)
            responseCode = 200
            responseMessage = 'Your process is up and running!'
        except Exception:
            responseCode = 604
            responseMessage = 'Your process is down!'

        # Respond to a GET request
        s.send_response(responseCode)
        s.send_header("Content-type", "text/html")
        s.end_headers()
        s.wfile.write(responseMessage)


if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), ServerHandler)
    print("Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))

 

# Python3
#!/usr/local/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer
import subprocess

HOST_NAME = ''  # Use your server ip
PORT_NUMBER = 9000  # Each port, should represent a process

PROCESS_NAME = "nginx"

class ServerHandler(BaseHTTPRequestHandler):
    def do_GET(s):
        try:
            subprocess.check_output("pgrep -f " + PROCESS_NAME, shell=True)
            responseCode = 200
            responseMessage = 'Your process is up and running!'
        except Exception:
            responseCode = 604
            responseMessage = 'Your process is down!'

        # Respond to a GET request
        s.send_response(responseCode)
        s.send_header("Content-type", "text/html")
        s.end_headers()
        s.wfile.write(bytes(responseMessage, "utf-8"))


if __name__ == '__main__':
    server_class = HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), ServerHandler)
    print("Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))

 

Top