Simple Python WebServer: Share/View your Linux Filesystem files over Http Server

A quick tip for Linux lovers.

Python allows you to start a quick http server by a single command.

Suppose you want to share files and directory of current working directory over http. No need to set up a complete web server for that. Python  can do this magic in a Single command.

 [root@clone-1 /]# python -m SimpleHTTPServer

Serving HTTP on port 8000 ...
localhost.localdomain - - [02/Dec/2013 10:15:18] "GET / HTTP/1.1" 200 -
localhost.localdomain - - [02/Dec/2013 10:15:22] "GET /boot/ HTTP/1.1" 200 -
localhost.localdomain - - [02/Dec/2013 10:15:24] "GET /boot/symvers-2.6.18-164.el5.gz HTTP/1.1" 200 -
localhost.localdomain - - [02/Dec/2013 10:15:32] "GET /home/ HTTP/1.1" 200 -
localhost.localdomain - - [02/Dec/2013 10:15:34] "GET /home/yogi/ HTTP/1.1" 200 - - - [02/Dec/2013 10:20:12] "GET / HTTP/1.1" 200 - - - [02/Dec/2013 10:20:12] code 404, message File not found - - [02/Dec/2013 10:20:12] "GET /favicon.ico HTTP/1.1" 404 - - - [02/Dec/2013 10:20:14] "GET /etc/ HTTP/1.1" 200 - - - [02/Dec/2013 10:20:17] "GET /etc/auto.misc HTTP/1.1" 200 - - - [02/Dec/2013 10:20:27] "GET /etc/modprobe.d/ HTTP/1.1" 200 - - - [02/Dec/2013 10:20:29] "GET /etc/modprobe.d/blacklist HTTP/1.1" 200 -

This one-liner starts a web server on port 8000 with the contents of current directory on all the interfaces (address, not just localhost. If you have "index.html" or "index.htm" files, it will serve those, otherwise it will list the contents of the currently working directory.
It works because python comes with a standard module called SimpleHTTPServer. The -m argument makes python to search for a module named in all the possible system locations (listed in sys.path and $PYTHONPATH shell variable). Once found, it executes it as a script. If you look at the source code of this module, you'll find that this module tests if it's run as a script if __name__ == '__main__', and if it is, it runs the test() method that makes it run a web server in the current directory.

If you are not sure that on which specific port this tiny webserver will listen, You can simple ensure it by

[root@clone-1 ~]# netstat -tunlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0      *                   LISTEN      9136/python      
tcp        0      0       *                   LISTEN      3519/portmap    

Here you can see local http server is listening on port 8000.
Remember to configure your linux firewall or "iptables" service to access from remote host.

If you want to try some different port the syntax would be:

$ python -m SimpleHTTPServer 8080

Try it out.

Popular posts from this blog

Grsecurity: Configure RHEL5/6 Kernel for Grsecurity

How to check Perl Module version in Linux

Linux Command line tips and Bash stuff