询问ssh远程端口转发命令对应的Paramiko等价实现方式
SSH反向隧道
ssh -R 80:localhost:8080 nokey@localhost.run的Paramiko等价实现 你要实现的是SSH反向端口转发,即把远程服务器的80端口流量转发到本地的8080端口。你当前的代码仅执行普通命令,未配置端口转发逻辑,因此无法达到预期效果。
以下是正确的Paramiko实现代码:
import paramiko import threading # 远程服务器配置 remote_host = "localhost.run" remote_username = "nokey" remote_port = 22 # SSH默认端口,localhost.run使用标准22端口 # 反向转发规则:远程端口80 → 本地localhost:8080 remote_forward_port = 80 local_target_host = "localhost" local_target_port = 8080 # 初始化SSH客户端 client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 连接远程SSH服务器 client.connect(remote_host, port=remote_port, username=remote_username) # 获取传输层对象,用于配置端口转发 transport = client.get_transport() # 请求远程服务器监听80端口,将流量转发至本地 transport.request_port_forward("", remote_forward_port) print(f"反向转发已建立:远程{remote_host}:{remote_forward_port} → 本地{local_target_host}:{local_target_port}") print("按Ctrl+C终止转发...") # 持续监听并处理远程端的连接请求 while True: # 等待1秒接收新连接 channel = transport.accept(1) if channel is None: continue # 建立本地目标服务的通道 local_channel = paramiko.Channel(1) local_channel.connect(local_target_host, local_target_port) # 定义双向数据转发函数 def forward_data(src_channel, dst_channel): while True: data = src_channel.recv(1024) if not data: break dst_channel.send(data) src_channel.close() dst_channel.close() # 启动线程处理双向数据传输 threading.Thread(target=forward_data, args=(channel, local_channel)).start() threading.Thread(target=forward_data, args=(local_channel, channel)).start() except KeyboardInterrupt: print("\n转发已停止") finally: client.close()
关键修正与说明:
- 你之前的代码参数配置错误:将
username设为localhost:9876、host设为nokey@localhost.run不符合SSH连接规范,正确配置应为remote_host为localhost.run,remote_username为nokey,端口使用默认22。 transport.request_port_forward("", remote_forward_port)是实现反向转发的核心,它告知远程服务器监听指定端口,并将传入连接导向本地。- 通过
transport.accept()接收远程连接请求,再建立本地通道并启动线程双向转发数据,才能完成完整的端口转发流程。
内容的提问来源于stack exchange,提问作者T-Dynamos
相关产品推荐
相关产品推荐

