Simple Python Script To Create A WebServer


In this post, you will learn to create a web server just by executing a simple python script which is below.

##################### START OF SCRIPT #########################
import sys
import getopt
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

def start(argv):
    HandlerClass = SimpleHTTPRequestHandler
    ServerClass = BaseHTTPServer.HTTPServer
    Protocol = "HTTP/1.0"

    if sys.argv[1:]:
        try:
            opts, args = getopt.getopt(argv, "hp:", ["port="])
        except getopt.GetoptError:
            print "Error Try Again"
            sys.exit()

        for opt, arg in opts:
            if opt in ("-p", "--port"):
                port = int(arg)

        server_addr = ("127.0.0.1", port)
        HandlerClass.protocol_version = Protocol
        httpd = ServerClass(server_addr, HandlerClass)

        socket = httpd.socket.getsockname()
        print "HTTP Server running on http://%s:%s/" % (socket[0], socket[1])
        httpd.serve_forever()
    else:
        print "usage:\t$ python http.py -p 8888 \n\t$ python http.py --port 8888"

if __name__ == "__main__":
    start(sys.argv[1:])
##################### END OF SCRIPT ##########################

Python has a built-in Http WebServer. This feature of python can be used to create a small web server within your local network for performing web server related small operations. The Advantage of pythons built-in Http WebServer is that you don't have to install and configure anything. The only thing you need, is to have Python installed. After running the script the terminal will update as the data is loaded from the web server. You can see standard HTTP GET, POST requests, error messages, IP address, date and time and every thing that you would expect from any other web server to display on the terminal as below.

##################### START OF TERMINAL OUTPUT #####################
127.0.0.1 - - [26/Nov/2016 11:03:33] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Nov/2016 11:03:33] "GET /resources/css/all.css HTTP/1.1" 200 -
127.0.0.1 - - [26/Nov/2016 11:03:33] code 404, message File not found
127.0.0.1 - - [26/Nov/2016 11:03:33] "GET /js/debug.js HTTP/1.1" 404 -
127.0.0.1 - - [26/Nov/2016 11:03:33] "GET /add.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Nov/2016 11:03:33] "GET /resources/theme-classic/theme-classic-all.css HTTP/1.1" 200 -
127.0.0.1 - - [26/Nov/2016 11:03:36] code 404, message File not found
127.0.0.1 - - [26/Nov/2016 11:03:36] "GET /fav.ico HTTP/1.1" 404 -
##################### END OF TERMINAL OUTPUT ########################

Reference for this script is here

Comments

Popular posts from this blog

Crack Gmail and LinkedIn Account Using Brute Force Attack With Simple Python Script

WinHex...Data Recovery and Forensics Tool

Download Youtube Playlist And Videos Using Python