2012-08-12 25 views
2

在下面的代碼中,第一次測試通過了,第二次沒有通過,我覺得很困惑。本地調用open_sftp()和通過單獨的函數有什麼區別?

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

好吧,我已經在debian/python2.6/paramiko1.7.6上驗證過它。

原因是client對象超出了範圍get_sftp(並關閉「通道」)。如果你cange它,就返回客戶端:

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() 

那麼一切都將正常工作(函數名或許應該改變..)。

+1

這似乎是一個實際的root密碼,請注意:) – 2014-08-13 20:13:04

+0

曾經,但在這篇文章之前已經很久了:-) – thebjorn 2014-08-13 21:43:50

+0

如果當SSHClient超出範圍時,通道是關閉的,這是否意味着創建只需要ip,用戶和密碼的'get_sftp()'函數是不可能的,並且返回一個開放的SFTP連接而不返回'SSHClient'對象? – ewok 2016-05-11 20:26:55

相關問題