HOW TO : Run web servers using one liners

A collection of one liners using different tools and programming languages to run a full fledged web server on any machine. They can be used to

  1. Serve files located on the server
  2. Act as server listening on a particular port. This is especially helpful if you are trying to setup a load-balancer and/or firewall and need to test access to the end points.

The criteria for the on liners was that you don’t need any additional modules other than the standard modules included with the language distributions.

NC : Netcat

netcat (nc) is pretty powerful network utility. You can start a web server running on port 8080 by simply running

[code]nc -l 8080[/code]

If you want to serve a particular file, you can do so by running

[code]while :; do nc -l 8080 < SAMPLE_FILE ; done [/code]

Python

You can start a web server in python by running

Python 2.x

[code] python -m SimpleHTTPServer 8080 [/code]

Python 3.x

[code]python -m http.server 8080 [/code]

This command will serve up a page with listing of all the files in the directory that the command was executed in. Pretty nifty way to quickly share files

Perl

You can start a web server in perl by running

[code]perl -MIO::All -e ‘io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })’ [/code]

Ruby

You can start a web server using Ruby by running
sudo ruby -rwebrick -e ‘server = WEBrick::HTTPServer.new : Port = >8080
server.start’
I haven’t been able to figure out how to pass an end of line in the command  line. So you need to literally pass the commands in two lines.

Scratch that.. My friend, Ray, showed me the right way to pass a line delimiter in the same command.

[code]ruby -rwebrick -e ‘server = WEBrick::HTTPServer.new(:Port => 8080) ; server.start’ [/code]

He even provided an additional option to define the directory you want to serve files from

[code]: DocumentRoot => ‘/some/shit’ [/code]

PHP

Starting with PHP 5.4 you can initiate a web server by running

[code]php -S localhost:8080[/code]

All of these options should work on any operating system. But I have only tried them on Linux.

Do you know how to do the same thing in other languages? Please share them in the comments section.

Credits: I collected these bits of code from the following sites

Python : http://www.garyrobinson.net/2004/03/one_line_python.html

Perl : http://www.perlmonks.org/?node_id=470397

Ruby : http://phrogz.net/simplest-possible-ruby-web-server

PHP : http://php.net/manual/en/features.commandline.webserver.php