3

在下面的代码中,第一个测试通过了,而第二个测试没有通过,我觉得这很令人费解。

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(Python 2.6和 paramiko 1.7.6)和 Debian(Python 2.7和 paramiko 1.7.7)上。

如果我test2先运行,我只会得到堆栈跟踪,这意味着test2确实失败了。

4

1 回答 1

5

好的,我已经在 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()

那么一切都会起作用(函数名可能应该改变..)。

于 2012-08-13T14:08:35.250 回答