使用Python Paramiko嵌套SSH

时间:2016-02-09 23:57:41

标签: python ssh nested paramiko

我有这种情况:

本地主机--------- jump-host ------- target-machine

我正在尝试使用Paramiko在Python中编写代码,首先从本地主机SSH跳转到主机,然后从跳转主机SSH到目标机器。 从目标机器,我想捕获一些输出并将它们作为变量或文件存储在本地(尚未到达那一点)。 我在Stack Overflow中找到了一个例子,他们谈到使用嵌套式SSH和Paramiko,我跟着它但是我被困在这里:

我的代码:

enter code here

#!/usr/bin/python
#
# Paramiko
#
import paramiko
import sys
import subprocess
#
# we instantiate a new object referencing paramiko's SSHClient class
#
vm=paramiko.SSHClient()
vm.set_missing_host_key_policy(paramiko.AutoAddPolicy())
vm.connect('192.168.115.103',username='osmanl',password='xxxxxx')
#
vmtransport = vm.get_transport()
dest_addr = ('192.168.115.103', 22)
local_addr = ('127.0.0.1', 22)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr, local_addr)
#
jhost=paramiko.SSHClient()
jhost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
jhost.load_host_keys('/home/osmanl/.ssh/known_hosts')
jhost.connect('10.103.53.26', username='latiu', password='xxxx', sock=vmchannel)
#
stdin, stdout, stderr = rtr.exec_command("show version | no-more")
#
print stdout.readline()
#
jhost.close()
vm.close()
# End

当我运行上述内容时,我收到此错误:

$ python sshvm.py
Traceback (most recent call last):
  File "sshvm.py", line 28, in <module>
    jhost.load_host_keys('/home/osmanl/.ssh/known_hosts')
  File "/usr/lib/python2.7/site-packages/paramiko-1.15.2-py2.7.egg/paramiko/client.py", line 121, in load_host_keys
    self._host_keys.load(filename)
  File "/usr/lib/python2.7/site-packages/paramiko-1.15.2-py2.7.egg/paramiko/hostkeys.py", line 94, in load
    with open(filename, 'r') as f:
IOError: [Errno 2] No such file or directory: '/home/osmanl/.ssh/known_hosts'

3 个答案:

答案 0 :(得分:9)

尝试以下编辑过的代码,它应该可以工作:

#!/usr/bin/python
#
# Paramiko
#
import paramiko
import sys
import subprocess
#
# we instantiate a new object referencing paramiko's SSHClient class
#
vm = paramiko.SSHClient()
vm.set_missing_host_key_policy(paramiko.AutoAddPolicy())
vm.connect('192.168.115.103', username='osmanl', password='xxxxxx')
#
vmtransport = vm.get_transport()
dest_addr = ('10.103.53.26', 22) #edited#
local_addr = ('192.168.115.103', 22) #edited#
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr, local_addr)
#
jhost = paramiko.SSHClient()
jhost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#jhost.load_host_keys('/home/osmanl/.ssh/known_hosts') #disabled#
jhost.connect('10.103.53.26', username='latiu', password='xxxx', sock=vmchannel)
#
stdin, stdout, stderr = jhost.exec_command("show version | no-more") #edited#
#
print stdout.read() #edited#
#
jhost.close()
vm.close()
# End

答案 1 :(得分:1)

我发现这是通过Jumphost登录到远程服务器的最简单方法。这很了不起!

    link :https://pypi.org/project/jumpssh/
    import jumpssh

答案 2 :(得分:0)

我知道OP特别要求Paramiko,但是我可以很容易地通过fabric来做到这一点。这是我的解决方法

from fabric import Connection

out = Connection('host1').run('host2 uptime')
print(out.stdout.strip())

这对我来说很好,并且我的输出也存储在变量中。