Create Your Own Web App to Execute Linux Command

Let say you need to run a command (which you use frequently) on your headless Linux box, such as, copying files, start/stop services, reboot, etc. However too lazy to go to the physical machine or open a ssh command from another pc.
Would it be nice if we have a web application that can easily be accessed through a web browser (even from a mobile web browser), to execute those commands. All we have to to is type the url (http://my-server-ip-address:myportnumber), and click on a link.
All these could easily be achieved using very simple service using Python.

1. Create a simple Python script. The Python script will be using WSGI to serve HTTP request/response.


2. A sample of the Python script below:

import os
from cgi import parse_qs, escape

def hello_world(environ, start_response):
    parameters = parse_qs(environ.get('QUERY_STRING', ''))
    if 'type' in parameters:
        mycommand = escape(parameters['command'][0])
        mycommand = ''
    start_response('200 OK', [('Content-Type', 'text/html')])

    if mycommand == 'copyfile1':
	#your linux command here. Example below
	os.system('cp myfile1.txt mynewfile.txt')
    elif mycommand == 'copyfile2':
	os.system('cp myfile2.txt mynewfile.txt')

    return ['''Command to execute:  %(mycommand)s 
    <a href='?command=copyfile1'>Copy file 1</a>
    <a href='?command=copyfile2'>Copy file 2</a>
    ''' % {'mycommand': mycommand}]

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    #put your own server ip address and port here
    srv = make_server('',81, hello_world)

3. Make the Python script run on every startup. Create a bash script for this:
vi myserver

4. Here’s the script for the bash file:

#! /bin/sh
# /etc/init.d/myserver

# Carry out specific functions when asked to by the system
case "$1" in
    echo "Starting myserver "
    python /home/username/
    echo "[OK]"
    echo "Stopping myserver "
    kill -9 `pidof python`
    echo "[OK]"
    echo "Usage: /etc/init.d/myserver {start|stop}"
    exit 1

exit 0

5. make the bash script executable.
chmod +x myserver

6. copy myserver script to /etc/init.d
sudo cp /wherever/you/saved/myserver /etc/init.d/myserver

7. update the startup folders to include the new script.
sudo update-rc.d myserver defaults

8. To test your Python web app, open a web browser, and type:

Related Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *