python 脚本的备用主机/IP
我希望我的 Python 脚本通过脚本中指定的 IP 访问 URL,而不是通过域的默认 DNS。基本上,我想要相当于在 /etc/hosts 文件中添加一个条目,但我希望更改仅应用于我的脚本,而不是全局应用于整个服务器。有什么想法吗?
I want my Python script to access a URL through an IP specified in the script instead of through the default DNS for the domain. Basically I want the equivalent of adding an entry to my /etc/hosts file, but I want the change to apply only to my script instead of globally on the whole server. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是否有效将取决于远端站点是否使用 HTTP/1.1 基于命名的虚拟主机。
如果不是,您只需根据 @Greg 的回答,将 URL 的主机名部分替换为它们的 IP 地址。
但是,如果是,您必须确保正确的
Host:
标头作为 HTTP 请求的一部分发送。如果没有这个,虚拟主机网络服务器将不知道要为您提供哪个网站的内容。请参阅您的 HTTP 客户端 API(Curl?)以查看是否可以添加或更改默认请求标头。Whether this works or not will depend on whether the far end site is using HTTP/1.1 named-based virtual hosting or not.
If they're not, you can simply replace the hostname part of the URL with their IP address, per @Greg's answer.
If they are, however, you have to ensure that the correct
Host:
header is sent as part of the HTTP request. Without that, a virtual hosting web server won't know which site's content to give you. Refer to your HTTP client API (Curl?) to see if you can add or change default request headers.您可以使用显式 IP 号码通过将其嵌入到 URL 中来连接到特定计算机:
http://127.0.0.1/index.html
相当于http://localhost/ index.html
也就是说,使用 IP 号码代替 DNS 条目并不是一个好主意。 IP 的变化比 DNS 条目更频繁,这意味着如果您对地址进行硬编码而不是让它正常解析,则您的脚本更有可能被破坏。
You can use an explicit IP number to connect to a specific machine by embedding that into the URL:
http://127.0.0.1/index.html
is equivalent tohttp://localhost/index.html
That said, it isn't a good idea to use IP numbers instead of DNS entries. IPs change a lot more often than DNS entries, meaning your script has a greater chance of breaking if you hard-code the address instead of letting it resolve normally.