要使用带有密码的Python sshtunnel
而不是密钥文件,你可以使用 sshtunnel
库来实现。以下是一个完整的示例代码,展示了如何使用密码进行SSH隧道连接:
sshtunnel
库首先,确保你已经安装了 sshtunnel
库。如果没有安装,可以使用以下命令进行安装:
pip install sshtunnel
以下是一个使用密码进行SSH隧道连接的示例代码:
from sshtunnel import SSHTunnelForwarder
import requests
# SSH服务器的配置
ssh_host = 'your_ssh_server_host'
ssh_port = 22
ssh_username = 'your_ssh_username'
ssh_password = 'your_ssh_password'
# 本地端口和远程端口的映射
local_port = 8080
remote_host = 'your_remote_host'
remote_port = 80
# 创建SSH隧道
with SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_username,
ssh_password=ssh_password,
remote_bind_address=(remote_host, remote_port)
) as tunnel:
print(f'Tunnel established. Forwarding local port {local_port} to {remote_host}:{remote_port}')
# 使用隧道进行HTTP请求
response = requests.get(f'http://localhost:{local_port}')
print(response.text)
SSHTunnelForwarder
用于创建SSH隧道。requests
用于发送HTTP请求。ssh_host
:SSH服务器的主机地址。ssh_port
:SSH服务器的端口号,默认为22。ssh_username
:SSH用户名。ssh_password
:SSH密码。local_port
:本地端口,用于接收转发过来的数据。remote_host
:远程主机地址。remote_port
:远程主机端口。SSHTunnelForwarder
创建隧道,并指定SSH服务器的配置和端口映射。with
语句确保隧道在使用完毕后自动关闭。requests.get
发送HTTP请求,目标地址为 http://localhost:{local_port}
,这样请求会通过SSH隧道转发到远程主机。通过这种方式,你可以使用密码而不是密钥文件来建立SSH隧道,并进行后续的网络通信。
领取专属 10元无门槛券
手把手带您无忧上云