paramiko: method to open and return an sftp conneciton

和自甴很熟 提交于 2019-12-10 18:09:37

问题


I want to write a method that takes an IP, username, and password, and returns an open SFTP connection to that server. Here's the code I have, using paramiko:

def open_sftp_connection(ip, user, passwd):
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, 22, user, passwd)
    assert ssh.get_transport().is_active(), 'Failed to connect to server'

    sftp = ssh.open_sftp()
    return sftp

If I execute this code directly in a python shell, it works fine:

>>> ssh = SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect(ip, 22, user, passwd)
>>> assert ssh.get_transport().is_active(), 'Failed to connect to server'
>>> sftp = ssh.open_sftp()
>>> print sftp.get_channel().get_transport().is_active()
True

But when I put it in a function and call the function, the sftp connection comes back disconnected:

>>> def open_sftp_connection(ip, user, passwd):
...     ssh = SSHClient()
...     ssh.load_system_host_keys()
...     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
...     ssh.connect(ip, 22, user, passwd)
...     assert ssh.get_transport().is_active(), 'Failed to connect to server'
...     sftp = ssh.open_sftp()
...     return sftp
...
>>> sftp = open_sftp_connection(ip, user, passwd)
>>> print sftp.get_channel().get_transport().is_active()
False

The only thing I can think of is the ssh connection is stored locally in ssh, then when the function returns, ssh is garbage collected, and the connection is terminated, so while the SFTPClient still exists, the underlying connection is now dead.

If that's the case, how can I resolve it? If not, what is actually happening?

EDIT: I modified the function to return sftp, ssh and now the connection stays open. So it is the garbage collector that's the culprit. Can this be resolved without returning two values?


回答1:


You need access to both the ssh and sftp instances.

def open_sftp_connection(ip, user, passwd):
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, 22, user, passwd)
    assert ssh.get_transport().is_active(), 'Failed to connect to server'
    return ssh, ssh.open_sftp()

ssh, sftp = open_sftp_connection(ip, user, passwd)
print sftp.get_channel().get_transport().is_active()


来源:https://stackoverflow.com/questions/37172488/paramiko-method-to-open-and-return-an-sftp-conneciton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!