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

时间:2012-08-12 21:07:57

标签: python paramiko

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

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确实失败了。

1 个答案:

答案 0 :(得分:4)

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

然后一切都会起作用(函数名称可能应该更改......)。