如何在Python中使用SSH连接从远程主机发送HTTP GET请求? [英] How to send HTTP GET request from remote host using SSH connection in Python?
问题描述
我正在使用与Paramiko的SSH连接.我的代码:
I'm using an SSH connection with Paramiko. My code:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=remote_host, username=remote_user, password=remote_password,
port=remote_port)
如何从连接的远程主机发送HTTP GET
请求(像使用代理一样使用它)?
How to send HTTP GET
request from connected remote host (use it like a proxy)?
我已经根据答案找到了解决方法:
I've found solution according to the answer:
with SSHTunnelForwarder(
ssh_address_or_host=(remote_host, remote_port),
ssh_username=remote_user,
ssh_password=remote_password,
remote_bind_address=("www.python.org", 80),
) as tunnel:
conn = http.client.HTTPConnection("127.0.0.1", port=tunnel.local_bind_port)
conn.request("GET", '/')
推荐答案
有两个选项:
使用SSH服务器上可以发送HTTP请求的任何工具.例如. curl
或 wget
:
Use any tool available on the SSH server that can send the HTTP request. E.g. curl
or wget
:
curl https://www.example.com/
并使用Paramiko执行它: Python Paramiko-运行命令
And execute it using Paramiko: Python Paramiko - Run command
此解决方案更简单,但依赖于命令-因此,它也依赖于平台.
This solution is easier, but has the dependency on the command — So it's also platform dependent.
将本地端口转发到远程HTTP服务器端口80,并使用本地Python代码连接到转发的端口.
Forward a local port to the remote HTTP server port 80 and connect to the forwarded port using your local Python code.
您将找到许多有关如何转发数据库端口的示例.像这样:启用Python通过SSH隧道连接到MySQL
You will find lot of examples how to forward a database port. Like this one: Enable Python to Connect to MySQL via SSH Tunnelling
在这种情况下,您需要执行相同的操作,只是连接HTTP客户端(例如 HTTPConnection
)而不是使用数据库客户端连接到转发的端口.
In your case, you need to do the same, just instead of using a database client to connect to the forwarded port, you connect an HTTP client (like HTTPConnection
).
在大多数情况下,当您想进一步连接时,数据库转发通常在SSH服务器本身( localhost
/ 127.0.0.1
)上结束.
Also in most cases, the database forwarding usually ends on the SSH server itself (localhost
/127.0.0.1
), while you want to connect further.
此解决方案更加复杂,但是没有外部依赖关系-因此它是独立于平台的.另一方面,端口转发是一种特殊特权,可以在服务器上进行限制(但通常不是).在尝试实施之前,您可以使用SSH客户端对其进行测试.
This solution is more complicated, but without external dependencies – So it's platform independent. On the other hand, the port forwarding is a special privilege, that may be restricted on the server (but usually it is not). Before trying to implement it, you can test it with your SSH client.
这篇关于如何在Python中使用SSH连接从远程主机发送HTTP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!