A Python script that allows you to check the status of the server from your browser

Description

Monitor the status of the server from your browser. I made it with a little improvement, referring to the introductory book on Python. It's not a big deal, but I made it so much so I'll keep it.

screen

When executed on the server, it listens on port 8000. A menu is displayed when opened in a browser.

無題.png

Click the command to see the result on your browser.

無題2.png

Source code

# coding: UTF-8

import BaseHTTPServer, shutil, os
from cStringIO import StringIO

class  MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

HTTP path and command line command of the service to be provided

    cmds = { '/free': 'free',
            '/cpuinfo' : 'cat /proc/cpuinfo',
            '/netstat' : 'netstat -anp',
            '/netstat-nlt' : 'netstat -nlt',
            '/uptime' : 'uptime',
            '/vmstat' : 'vmstat',
            '/df' : 'df -h',
            '/sar' : 'sar',
            '/hostname' : 'hostname',
            '/date' : 'date',
            '/ps' : 'ps aux',
            '/iostat' : 'iostat',
            '/pstree' : 'pstree',
            '/ifconfig' : 'ifconfig',
            '/who' : 'who'}

    def do_GET(self):

#Service to GET request

Call the head method to specify the response and content type.

        f = self.send_head()

#If the file object is returned, the response check passes and 200 is OK, so create the body.

This time it is GET, so do not use f above and overwrite it as follows.

        if f:
            f = StringIO()

Get the machine name

            machine = os.popen("hostname").readlines()[0]

/ Then just create an index and return

            if self.path == "/":
                heading = "Select a command to run on %s" % (machine)
                body = self.getMenu()

When # command is specified, the command is actually executed and returned. else: heading = "Execution of ``%s'' on %s" % ( self.cmds[self.path], machine ) cmd = self.cmds[self.path] body = 'Main Menu

%s
\n' % os.popen(cmd).read()

            f.write("<html><head><title>%s</title></head>\n" % (heading) )
            f.write("<body><h1>%s</h1>\n" % (heading))
            f.write(body)
            f.write("</body></html>\n")
            f.seek(0)
            self.copyfile(f, self.wfile)
            f.close()
        return f

    def do_HEAD(self):

HEAD Service to request

        f = self.send_head()
        if f:
            f.close()

    def send_head(self):
        path = self.path
        if not path in ["/"] + self.cmds.keys():
            head = 'Command "%s" not found. Try one of these:<ul>' % path
            msg = head + self.getMenu()
            self.send_error(404, msg)
            return None
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=UTF-8")
        self.end_headers()
        f = StringIO()
        f.write("A test %s\n" % self.path)
        f.seek(0)
        return f

    def getMenu(self):
        keys = self.cmds.keys()
        keys.sort()
        msg = []
        for k in keys:
            msg.append('<li><a href="%s">%s => %s</a></li>' % (k,k, self.cmds[k]))

        msg.append("</ul>")
        return "\n".join(msg)

    def copyfile(self, source, outputfile):
        shutil.copyfileobj(source, outputfile)

def main(HandlerClass = MyHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    main()

Recommended Posts

A Python script that allows you to check the status of the server from your browser
A Python script that compares the contents of two directories
A learning roadmap that allows you to develop and publish services from scratch with Python
A Python script that goes from Google search to saving the Search results page at once
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
A script that returns 0, 1 attached to the first Python prime number
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A program that rotates the contents of the list to the left
Have Alexa run Python to give you a sense of the future
[Python] A program that calculates the number of socks to be paired
A memo that allows you to change Pineapple's Python environment with pyenv
I made a program to check the size of a file in Python
From a book that makes the programmer's way of thinking interesting (Python)
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
Introduction of "scikit-mobility", a library that allows you to easily analyze human flow data with Python (Part 1)
Send a message from Slack to a Python server
How to open a web browser from python
"Python Kit" that calls a Python script from Swift
Check the status of your data using pandas_profiling
Create a plugin that allows you to search Sublime Text 3 tabs in Python
A python script that draws a band diagram from the VASP output file EIGENVAL
Python script to get a list of input examples for the AtCoder contest
I made a script to record the active window using win32gui of Python
I created a script to check if English is entered in the specified position of the JSON file in Python.
Easy way to check the source of Python modules
The story of launching a Minecraft server from Discord
The wall of changing the Django service from Python 2.7 to Python 3
[Python] A program that counts the number of valleys
Template of python script to read the contents of the file
Get the return code of the Python script from bat
[Python] A program that compares the positions of kangaroos.
Python Note: The mystery of assigning a variable to a variable
A Python script that crawls RSS in Azure Status and posts it to Hipchat
Create a python script to check if the link at the specified URL is valid
[Introduction to Python] Basic usage of the library scipy that you absolutely must know
A script that can perform stress tests according to the number of CPU cores
How to check in Python if one of the elements of a list is in another list
How to find the first element that matches your criteria in a Python list
Introducing the book "Creating a profitable AI with Python" that allows you to learn machine learning in the shortest course
Jedi-vim shortcut command that allows you to refer to the definition source and definition destination in Python
A library that monitors the life and death of other machines by pinging from Python
How to start a simple WEB server that can execute cgi of php and python
A Python script that saves a clipboard (GTK) image to a file.
How to run a Python program from within a shell script
Different from the import type of python. from A import B meaning
Launch a simple WEB server that can check the header
Check the memory status of the server with the Linux free command
I want to start a lot of processes from python
Creating a Python script that supports the e-Stat API (ver.2)
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
I made a function to check the model of DCGAN
Check the operating status of the server with the Linux top command
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to quickly count the frequency of appearance of characters from a character string in Python?
I made a server with Python socket and ssl and tried to access it from a browser
Procedure from environment construction to operation test of testinfra, a server environment test tool made by Python
Build a Python environment and transfer data to the server
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried changing the python script from 2.7.11 to 3.6.0 on windows10