【问题标题】:Is there a way to get handle after doing a ssh to linux server in python在 python 中对 linux 服务器执行 ssh 后有没有办法处理
【发布时间】:2022-01-24 17:25:17
【问题描述】:

我是编程新手,我的要求是从我的自动化服务器在两台 linux 机器上运行多个命令(不是按顺序)。我已经阅读了Paramiko 的文档,并尝试使用这个模块对两台 linux 机器进行 ssh。 我能够成功执行 ssh,但看起来 SSHClinet 没有返回任何值。所以我不得不反复执行登录代码来登录机器和来回。不是每次都执行登录代码,有没有办法让我可以随意调用两台机器的句柄?

我写的登录代码是:

    def loginMachines(self, ip, username , password, role, retries = 1):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    for x in range(retries):
        try:
            ssh.connect(ip, username = username , password = password)
            banner(self.log, 'SSH to {0} machine is successful'.format(role))
            return True   >> if this can return a handle i can use the same method to login to both linux machines and manipulate with the handle?
        except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e:
            self.log.info(banner('Exception : {0}'.format(e)))
            return False

【问题讨论】:

  • 什么两台机器?您的代码登录到 one 机器一。
  • 我登录到服务器并运行一个脚本,该脚本将登录到两台 linux 机器,分别启动服务器和客户端并启动它们之间的流量。我可以运行两个脚本,一个在服务器上运行,另一个在客户端上运行,但只是想我是否从一个服务器启动我的脚本,该服务器将在内部登录到两台 linux 机器..
  • 我刚刚发布了登录一台机器的代码。第二台机器只有 IP 会改变。但由于我必须依次在客户端和服务器上执行不同的命令,我认为拥有客户端和服务器机器的句柄会有所帮助。在某种程度上,我可以通过调用 shell 来实现这一点,但不确定这是否正确。
  • 这看起来像 XY problem - 请询问您的实际问题,而不是您想象中的解决方法。
  • 我能够通过返回 ssh 来获得 ssh 句柄。我能够解决这个问题。非常感谢您的帮助

标签: python paramiko


【解决方案1】:

只需返回 ssh 即可解决问题。

    def checkSSH(self, ip, username , password, role, retries = 1):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    for x in range(retries):
        try:
            ssh.connect(ip, username = username , password = password)
            banner(self.log, 'SSH to {0} machine is successful'.format(role))
            return ssh
        except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e:
            self.log.info(banner('Exception : {0}'.format(e)))
            return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多