Kudithipudi.Org

December 28, 2012

HOW TO : Run web servers using one liners

Filed under: HOWTO — Vinay @ 4:56 pm

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

nc -l 8080

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

while :; do nc -l 8080 < SAMPLE_FILE ; done 

Python

You can start a web server in python by running

Python 2.x

 python -m SimpleHTTPServer 8080 

Python 3.x

python -m http.server 8080 

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

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

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.

ruby -rwebrick -e 'server = WEBrick::HTTPServer.new(:Port => 8080) ; server.start' 

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

: DocumentRoot => '/some/shit' 

PHP

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

php -S localhost:8080

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

2 Comments »

  1. Your first netcat command isn’t a web server it is a listener, it doesn’t serve anything.

    I like the PHP one, had never seen that before.

    Comment by Robin — December 29, 2012 @ 6:17 pm

  2. Robin – You are right. The second option provided allows you to serve a single file.

    Comment by Vinay — December 31, 2012 @ 12:15 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress