我看过几个与此主题相关的问题和答案,但我一直无法掌握方法。
我能做什么:使用 Paramiko 使用 Python 脚本连接到远程计算机并返回信息,例如,ping 交换机:
ssh = pk.SSHClient()
ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx')
标准输入、标准输出、标准错误 = \
ssh.exec_command('ping -n 1 xxx.xxx.x.x ')
print('Ping开关: ', stdout.readlines())
我想做什么但不知道怎么做:连接一次计算机然后再次使用 SSH(paramiko.SSHClient())连接到另一台设备(在本例中为 NAS)和“exec_command”之类的东西喜欢:
ssh = pk.SSHClient()
ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx') # 连接电脑
ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx') #从电脑连接NAS
标准输入、标准输出、标准错误 = \
ssh.exec_command('关机 , y ') # 向 NAS 发送命令
print('Ping开关: ', stdout.readlines())
这可能吗,有谁知道办法吗?
提前谢谢你。
你必须打开一个隧道,检查paramiko演示或使用
sshtunnel
包。
对于后者:
import paramiko as pk
import sshtunnel
with sshtunnel.open_tunnel(
remote_computer_ip,
ssh_username=remote_username,
ssh_password=remote_password,
remote_bind_address=(NAS_IP, 22),
debug_level='DEBUG',
) as tunnel:
ssh = pk.SSHClient()
ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
ssh.connect(NAS_IP,
port=tunnel.local_bind_port, # redirected to port NAS_IP:22
username=NAS_USER,
password=NAS_PASS)
(stdin, stdout, stderr) = ssh.exec_command(...) # your stuff
你可以用更简单的方式问这个问题。如果我没记错的话,你是不是在尝试使用 paramiko 连接到一台机器,然后从那台机器连接到 NAS 机器?
或者你连接到一台机器说 A 然后你想要那台机器的 ssh 句柄并连接到 NAS 机器并生成另一个 ssh 句柄?
如果是后者,我建议您使用一个类并为每个 ssh 连接创建一个对象。 你可以看看这个: