无法关闭Paramiko连接

时间:2019-08-11 16:15:22

标签: python ssh paramiko

我正在尝试使用Paramiko在远程服务器上执行一些命令,并重新利用net中的某些代码。从Paramiko文档中,它说您必须关闭连接。但是我这样做时遇到了错误。

class ssh:

    paramiko.util.log_to_file("filename_new.log")

    client = None
    def __init__(self, address, username, password):
        self.client=paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
        self.client.connect(hostname=address, username=username, password=password)

    def sendCommand(self, command):
        if(self.client):
            couldNotConnect = False
            stdin, stdout, stderr = self.client.exec_command(command, get_pty=True)
            stdout = stdout.readlines()
            self.client.close()
        else:
            stdout = "Could Not Connect" 
            couldNotConnect = True       

        return stdout


connection = ssh(serverName, userName, passWord)

dfDetails = connection.sendCommand("df -hT")
upTime = connection.sendCommand("uptime")

我收到以下错误:

  File "/home/amarc/development/djago/venv/lib/python3.6/site-packages/paramiko/client.py", line 508, in exec_command
    chan = self._transport.open_session(timeout=timeout)
AttributeError: 'NoneType' object has no attribute 'open_session'

但是当我删除self.client.close()时,它可以正常工作。但是我担心如果程序多次运行,如果不关闭连接可能会导致问题。

并且正在使用__init__来创建连接的正确方法,因为我可能每次都为函数提供不同的凭据。

2 个答案:

答案 0 :(得分:0)

我建议您选择Fabric(http://www.fabfile.org/)或Ansible,并且不要完全依赖Paramiko,因为您必须重新实现许多细节。这些工具已经在使用它,但在后台。

答案 1 :(得分:0)

SSHClient.close调用必须与SSHClient.connect匹配。

您一次调用SSHClient.connect,但每次调用SSHClient.close

在执行所有命令后,只调用一次SSHClient.close

相关问题