使用 Python Paramiko 嵌套 SSH

2025-02-14 09:49:00
admin
原创
122
摘要:问题描述:我有这种情况:本地主机 --------- 跳转主机 ------- 目标机器我正在尝试使用 Paramiko 在 Python 中编写代码,首先从本地主机通过 SSH 连接到跳转主机,然后从跳转主机通过 SSH 连接到目标计算机。从目标计算机,我想捕获一些输出并将它们存储在本地,作为变量或文件(还...

问题描述:

我有这种情况:

本地主机 --------- 跳转主机 ------- 目标机器

我正在尝试使用 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'

解决方案 1:

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

#!/usr/bin/python
#
# Paramiko
#
import paramiko
#
# 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

解决方案 2:

我知道 OP 明确要求了Paramiko,但我可以很轻松地做到这一点fabric。这是我的解决方案

from fabric import Connection

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

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

解决方案 3:

我发现这是通过 jumphost 登录远程服务器的最简单的途径。效果非常好!

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

解决方案 4:

阅读接受的答案后,对源地址和目标地址https://stackoverflow.com/a/36096801/1303321有点困惑,因此参考https://www.programcreek.com/python/?code=grycap%2Fim%2Fim-master%2FIM%2FSSH.py
,这是我最终得到的解决方案:

def __run_remote_command(self, command: str) -> Tuple[str, str]:
        """
        Private method to run a command in the remote machine via SSH.
        This method establishes the connection; fires the command; collects the output then closes the connection
        :param command: command which needs to be invoked in the remote machine
        :return (stdout, stderr) : Tuple of string containing the standard output and error of the command execution
        """
        stdout, stderr = '', ''
        with paramiko.SSHClient() as jhost:
            jhost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            private_key = paramiko.RSAKey.from_private_key_file(filename=RESOURCES_SERVER_SSH_KEY)
            try:
                jhost.connect(hostname=JUMPHOST_SERVER_URL, username=RESOURCES_SERVER_SSH_USERNAME, pkey=private_key)
                jhost_transport = jhost.get_transport()
                dest_addr = (RESOURCES_SERVER_URL, 22)
                local_addr = (JUMPHOST_SERVER_URL, 22)
                jhost_channel = jhost_transport.open_channel("direct-tcpip", dest_addr, local_addr)

                with paramiko.SSHClient() as target_server:
                    target_server.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                    target_server_private_key = paramiko.RSAKey.from_private_key_file(filename=RESOURCES_SERVER_SSH_KEY)
                    target_server.connect(hostname=RESOURCES_SERVER_URL, username=RESOURCES_SERVER_SSH_USERNAME, pkey=target_server_private_key, sock=jhost_channel)

                    self.logger.info(f"Invoking {command} on remote host {RESOURCES_SERVER_URL} over SSH")
                    _, stdout, stderr = target_server.exec_command(command)
                    stdout = stdout.read().decode('utf-8')
                    stderr = stderr.read().decode('utf-8')
            except SSHException as ssh_ex:
                self.logger.error(f"Failed to connect to {RESOURCES_SERVER_URL} ")
                self.logger.exception(ssh_ex, exc_info=True)
                raise BaseException()
        return (stdout, stderr)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3949  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2735  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   74  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   82  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   68  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用