使用Python Paramiko的端口转发和开放SFTP

2024-04-26 18:00:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用ssh在服务器上执行了命令。现在我必须对不同的IP执行另一个ssh,同时保持旧的ssh处于活动状态

这个新的IP是端口转发,然后将用于执行SFTP

我面临的问题是两个ssh连接都在同一个端口上,所以无法执行第二个ssh。 这是失败的SFTP

对这一点的任何支持都会有所帮助

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=username, password=password, port=22)
time.sleep(3)
#Invoke shell to open multiple channel with in one SSH
chan = ssh.invoke_shell()
chan.send(ip1+'\n')
time.sleep(5)
chan.send(pass1+'\n')
time.sleep(10)

chan.send("ssh "+ip2+'\n')

time.sleep(10)
chan.send(pass2+'\n')
time.sleep(5)
#Execute command
chan.send(cmd)

#connect to another ip to do sftp
ssh1 = paramiko.SSHClient()
ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("127.0.0.4", username=usr2, password=pass2, port=22)
sftp=ssh.open_sftp()

Tags: to端口ipsendparamikotimeconnectusername
1条回答
网友
1楼 · 发布于 2024-04-26 18:00:32

看起来像是误会。您的代码不执行任何端口转发

有关正确的代码,请参见Nested SSH using Python Paramiko

如果您需要SFTP,而不是shell,只需执行以下操作:

jhost.open_sftp()

而不是

jhost.exec_command(command)

强制性警告:不要使用AutoAddPolicy–这样做会失去对MITM attacks的保护。有关正确的解决方案,请参见Paramiko "Unknown Server"

相关问题 更多 >