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.
When executed on the server, it listens on port 8000. A menu is displayed when opened in a browser.
Click the command to see the result on your browser.
# coding: UTF-8
import BaseHTTPServer, shutil, os
from cStringIO import StringIO
class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
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
f = self.send_head()
#If the file object is returned, the response check passes and 200 is OK, so create the body.
if f:
f = StringIO()
machine = os.popen("hostname").readlines()[0]
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):
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