本地调用 open_sftp() 和通过单独的函数调用有什么区别?

2023-12-06

在下面的代码中,第一个测试通过,而第二个测试没有通过,这让我感到困惑。

import paramiko

def test1():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('10.0.0.107', username='test', password='test')
    sftp = client.open_sftp()
    sftp.stat('/tmp')
    sftp.close()

def get_sftp():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('10.0.0.107', username='test', password='test')
    return client.open_sftp()

def test2():
    sftp = get_sftp()
    sftp.stat('/tmp')
    sftp.close()

if __name__ == '__main__':
    test1()
    print 'test1 done'
    test2()
    print 'test2 done'

这是我得到的:

$ ./script.py
test1 done
Traceback (most recent call last):
  File "./play.py", line 25, in <module>
    test2()
  File "./play.py", line 20, in test2
    sftp.stat('/tmp')
  File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 337, in stat
    t, msg = self._request(CMD_STAT, path)
  File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 627, in _request
    num = self._async_request(type(None), t, *arg)
  File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 649, in _async_request
    self._send_packet(t, str(msg))
  File "/usr/lib/pymodules/python2.6/paramiko/sftp.py", line 172, in _send_packet
    self._write_all(out)
  File "/usr/lib/pymodules/python2.6/paramiko/sftp.py", line 138, in _write_all
    raise EOFError()
EOFError

这种情况在 Ubuntu(Python2.6和帕拉米科1.7.6)和 Debian(Python2.7和帕拉米科1.7.7).

如果我跑test2首先,我只得到堆栈跟踪,意思是test2确实失败了。


好的,我已经在 debian/python2.6/paramiko1.7.6 上验证过了。

原因是,client对象超出范围get_sftp(并关闭“通道”)。如果您更改它以便返回客户端:

import paramiko

def get_sftp():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('localhost', username='root', password='B4nan-purr(en)')
    return client

def test2():
    client = get_sftp()
    sftp = client.open_sftp()
    sftp.stat('/tmp')
    sftp.close()


if __name__ == "__main__":
    test2()

那么一切都会正常(函数名称可能应该更改..)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

本地调用 open_sftp() 和通过单独的函数调用有什么区别? 的相关文章

随机推荐