Does paramiko close ssh connection on a non-paramiko exception

心已入冬 提交于 2019-12-04 19:23:16

问题


I'm debugging some code, which is going to result in me constantly logging in / out of some external sftp servers. Does anyone know if paramiko automatically closes a ssh / sftp session on the external server if a non-paramiko exception is raised in the code? I can't find it in the docs and as the connections have to be made fairly early in each iteration I don't want to end up with 20 open connections.


回答1:


No, paramiko will not automatically close the ssh / sftp session. It doesn't matter if the exception was generated by paramiko code or otherwise; there is nothing in the paramiko code that catches any exceptions and automatically closes them, so you have to do it yourself.

You can ensure that it gets closed by wrapping it in a try/finally block like so:

client = None
try:
    client = SSHClient()
    client.load_system_host_keys()
    client.connect('ssh.example.com')
    stdin, stdout, stderr = client.exec_command('ls -l')
finally:
    if client:
        client.close()



回答2:


SSHClient() can be used as a context manager, so you can do

with SSHClient() as ssh:
   ssh.connect(...)
   ssh.exec_command(...)

and not close manually.



来源:https://stackoverflow.com/questions/7159644/does-paramiko-close-ssh-connection-on-a-non-paramiko-exception

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