形成主要的 Linux 操作系统(已连接,工作)我想运行另一个“.connect”。
这是代码:
import paramiko
hostname = "hostaname"
ip = "1111.111.11.11"
username = "user"
password = "pass"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,username=username, password=password)
现在我想从主目录访问另一个本地主机:
hostname = "localhost"
ip = "222.222.2.2"
username = "root"
password = "root"
ssh.connect(hostname=hostname,username=username, password=password)
我收到以下错误:
NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 222.222.2.2 or ::1
UPD:我在以下问题中找到了答案: 使用 Python Paramiko 的嵌套 SSH
UPD:我在以下问题中找到了答案:Nested SSH using Python Paramiko
这是我的完整代码和解决方案:
import paramiko
ip1_hostname = "host-name-2024"
ip1 = "1111.111.11.11"
ip2 = "222.222.2.2"
ip1_username = "username"
ip1_password = "password"
root_user = "root"
root_password = "root"
ip1_machine = paramiko.SSHClient()
ip1_machine.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ip1_machine.connect(hostname=ip1_hostname,username=ip1_username, password=ip1_password)
std_in, std_out, std_err = ip1_machine.exec_command('ls')
print(f"{std_out.read().decode().split()}")
# based on https://stackoverflow.com/questions/35304525/nested-ssh-using-python-paramiko
ip1_transport = ip1_machine.get_transport()
dest_addr = (ip2, 22) # "222.222.2.2"
local_addr = (ip1, 22) # "1111.111.11.11"
cu_channel = ip1_transport.open_channel("direct-tcpip", dest_addr, local_addr)
cu = paramiko.SSHClient()
cu.set_missing_host_key_policy(paramiko.AutoAddPolicy())
cu.connect(ip2, username=root_user, password=root_password, sock=cu_channel)
std_in, std_out, std_err = cu.exec_command('ls')
print(f"{std_out.read().decode().split()}")