Is it possible to run python SimpleHTTPServer only on localhost?

I have a vpn connection, and when I run python -m SimpleHTTPServer, it runs on 0.0.0.0:8000, which means that it can be accessed through localhost and through my real ip. I don’t want the robots to scan me and wonder if the server will be accessible only through localhost.

Is it possible?

python -m SimpleHTTPServer 127.0.0.1:8000 # doesn't work. 

Any simple HTTP server that can be launched instantly using the command line is also welcome.

+54
python command-line shell
Sep 04 '12 at 17:50
source share
3 answers

If you read the source, you will see that only the port can be redefined on the command line. If you want to change the host on which it is included, you will need to implement the test() SimpleHTTPServer and BaseHTTPServer yourself. But it should be very easy.

Here is how you can do this, quite easily:

 import sys from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer def test(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer): protocol = "HTTP/1.0" host = '' port = 8000 if len(sys.argv) > 1: arg = sys.argv[1] if ':' in arg: host, port = arg.split(':') port = int(port) else: try: port = int(sys.argv[1]) except: host = sys.argv[1] server_address = (host, port) HandlerClass.protocol_version = protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == "__main__": test() 

And use it:

 > python server.py 127.0.0.1 Serving HTTP on 127.0.0.1 port 8000 ... > python server.py 127.0.0.1:9000 Serving HTTP on 127.0.0.1 port 9000 ... > python server.py 8080 Serving HTTP on 0.0.0.0 port 8080 ... 
+43
04 Sep '12 at 17:56
source

As @sberry explained, simply doing this using the nice python -m ... method will not be possible because the IP address is hard-coded in the implementation of the BaseHttpServer.test function.

A way to do this from the command line without writing code to a file would first be

 python -c 'import BaseHTTPServer as bhs, SimpleHTTPServer as shs; bhs.HTTPServer(("127.0.0.1", 8888), shs.SimpleHTTPRequestHandler).serve_forever()' 

If it is still considered one liner, it depends on the width of your terminal ;-) This, of course, is not very easy to remember.

+61
Sep 04 '12 at 18:18
source

In Python version 3.4 and above, the http.server module accepts the bind parameter.

According to the docs:

python -m http.server 8000

By default, the server binds to all interfaces. The -b / - bind option specifies the specific address to which it should bind. For example, the following command forces the server to communicate with localhost only:

python -m http.server 8000 --bind 127.0.0.1

New in version 3.4: the -bind argument was introduced.

+22
Nov 27 '16 at 5:50
source



All Articles