简体   繁体   English

如何在Python的SocketServer中允许或拒绝远程连接?

[英]How to allow or deny remote connections in Python's SocketServer?

I'm creating an extremely simple Vega visualization viewer: it's a one file module that serves a base HTML page containing just the Vega graphic and an HTML5 EventSource of updates. 我正在创建一个非常简单的Vega可视化查看器:这是一个文件模块 ,可提供基本HTML页面,该页面仅包含Vega图形和更新的HTML5 EventSource The user (me) is working in a Python shell through ssh, creates an object representing the viewer, which prints its IP and port for the user to paste into their (my) web browser. 用户(me)通过ssh在Python shell中工作,创建了一个代表查看器的对象,该对象打印其IP和端口供用户粘贴到其(my)Web浏览器中。 This HTTP server doesn't serve files or take input from clients, so I don't see any security concerns. 该HTTP服务器不提供文件或不接收来自客户端的输入,因此我看不到任何安全问题。

The part I'm unsure of is how to set (host, port) such that my web browser can find the HTTP server running in the remote Python. 我不确定的部分是如何设置(host, port) ,以便我的Web浏览器可以找到在远程Python中运行的HTTP服务器。 I've been experimenting all afternoon, and I don't know if I'm misunderstanding what's supposed to happen or if the servers I use have changed their access policies. 我整个下午都在进行实验,不知道是否误解了应该发生的情况,还是我使用的服务器是否更改了访问策略。

Here's a minimal example: 这是一个最小的示例:

import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((host, port), Handler)
print(httpd.server_address)
httpd.serve_forever()

If I'm running this locally and want to ensure that outside viewers cannot access it, do I set host to "127.0.0.1" because that means a client would have to access it as 127.0.0.1, which can only happen locally? 如果我在本地运行此文件并希望确保外部查看者无法访问它,我是否将host设置为"127.0.0.1"因为这意味着客户端必须将其作为 127.0.0.1访问,这只能在本地进行? In this case, port can be 0 to get any open port. 在这种情况下, port可以为0以获取任何打开的端口。

If I'm running this remotely want to to ensure that outside viewers can access it, do I set host to "" or "0.0.0.0" because that means that a client can access it as any address that makes its way to the server? 如果我正在远程运行此服务器,以确保外部查看者可以访问它,请将host设置为""还是"0.0.0.0"因为这意味着客户端可以将其作为访问服务器的任何地址来访问? In this case, I might not be able to set port to 0 because many of those ports might be blocked, or is the OS smarter about this? 在这种情况下,我可能无法将port设置为0因为其中许多端口可能被阻止了,或者操作系统对此是否更聪明?

Basically, how is access control in Python's SocketServer supposed to work? 基本上,Python的SocketServer中的访问控制应该如何工作?

This is basic TCP. 这是基本的TCP。 Nothing to do with Python. 与Python无关。

If you listen at 127.0.0.1, only clients running in the same host can connect. 如果您收听127.0.0.1,则只能在同一主机上运行的客户端可以连接。

If you listen at 0.0.0.0, anybody can connect, firewalls permitting. 如果您收听0.0.0.0,那么在防火墙允许的情况下,任何人都可以连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM