在 python 中对 linux 服务器执行 ssh 后,有没有办法获取句柄

Is there a way to get handle after doing a ssh to linux server in python

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

我写的登录码是:

    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

只需返回 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