是否可以只在本地主机上运行 python SimpleHTTPServer?

我有一个 vpn 连接,当我运行 python-m SimpleHTTPServer 时,它服务于0.0.0.0:8000,这意味着它可以通过本地主机 还有通过我的实际 ip 访问。 我不希望机器人扫描我和感兴趣的服务器将被访问只有通过本地主机。

有可能吗?

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

也欢迎使用命令行即时执行任何其他简单的 http 服务器。

124851 次浏览

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 ...

As @sberry explained, simply doing it by using the nice python -m ... method won't be possible, because the IP address is hardcoded in the implementation of the BaseHttpServer.test function.

A way of doing it from the command line without writing code to a file first would be

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

If that still counts as a one liner depends on your terminal width ;-) It's certainly not very easy to remember.

In Python versions 3.4 and higher, the http.server module accepts a bind parameter.

According to the docs:

python -m http.server 8000

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

python -m http.server 8000 --bind 127.0.0.1

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