Is it possible to run python SimpleHTTPServer on localhost only?

后端 未结 3 1627
终归单人心
终归单人心 2020-12-02 06:07

I have a vpn connection and when I\'m running python -m SimpleHTTPServer, it serves on 0.0.0.0:8000, which means it can be accessed via localhost and via my

3条回答
  •  醉话见心
    2020-12-02 06:40

    If you read the source you will see that only the port can be overridden on the command line. If you want to change the host it is served on, you will need to implement the test() method of the SimpleHTTPServer and BaseHTTPServer yourself. But that should be really easy.

    Here is how you can do it, pretty 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 to 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 ...
    

提交回复
热议问题