2014-04-14 26 views
1

的Python 3.3 RHEL 6的paramiko沒有返回異常後及時

與下面的代碼,如果我得到了密碼,在第一時間,它正確打印「認證」(Python 3中),然後返回我到我貝殼。如果我錯誤地輸入3次密碼,它會正確輸出'嘗試次數過多,抱歉',然後將我退回到我的shell。但是,如果我的密碼錯誤一次或兩次,然後正確,它會打印「已驗證」,但只會掛在那裏,並不會將我發回到我的外殼。我必須按CTRL-C才能脫離腳本。

任何想法?

import paramiko 
import getpass 
authenticated, tries = False, 1 
while authenticated == False and tries <= 3: 
    try: 
     password = getpass.getpass('Password: ') 
     ssh = paramiko.SSHClient() 
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     ssh.connect(myhost, username=myusername, password=password) 
     authenticated = True 
    except paramiko.AuthenticationException: 
     authenticated = False 
     tries += 1 
if authenticated == False: 
    print('Too many tries, sorry.') 
else: 
    print('Authenticated') 
+0

適用於python 2.x linux上的我。可能不相關,但嘗試關閉腳本末尾的ssh連接,即使連接失敗 - paramiko運行後臺線程,也許這與它有關。 – tdelaney

回答

1

正如tdelaney所說,您需要添加ssh.close()。使用Python 3.3進行了測試:

import paramiko 
import getpass 
authenticated, tries = False, 1 
myhost  = 'myserver.mydomain.org' 
myusername = 'myuser' 
while authenticated == False and tries <= 3: 
    try: 
     password = getpass.getpass('Password: ') 
     ssh = paramiko.SSHClient() 
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     ssh.connect(myhost, username=myusername, password=password) 
     authenticated = True 
    except paramiko.AuthenticationException: 
     authenticated = False 
     tries += 1 
if authenticated == False: 
    print('Too many tries, sorry.') 
else: 
    print('Authenticated') 
ssh.close() 

沒有ssh.close()腳本掛起,當我輸入一個錯誤的密碼,然後將正確的密碼。它不會掛起,否則(2錯誤的密碼,然後正確的密碼是好的,它不會掛起)。

你可以看到活動線程,如果你import threading,並在最後一行print('Threads:', threading.enumerate())

Threads: [<_MainThread(MainThread, started 140298690832128)>, <paramiko.Transport at 0x14e3a90 (cipher aes128-ctr, 128 bits) (connected; awaiting auth)>, <paramiko.Transport at 0x147a910 (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>] 

import paramiko 
import getpass 
import threading 

authenticated, tries = False, 1 
myhost  = 'myserver.mydomain.org' 
myusername = 'myuser' 
while authenticated == False and tries <= 3: 
    try: 
     password = getpass.getpass('Password: ') 
     ssh = paramiko.SSHClient() 
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     ssh.connect(myhost, username=myusername, password=password) 
     authenticated = True 
    except paramiko.AuthenticationException: 
     authenticated = False 
     tries += 1 
if authenticated == False: 
    print('Too many tries, sorry.') 
else: 
    print('Authenticated') 
#ssh.close() 
print('Threads:', threading.enumerate()) 

當我測試了它,它經過一個錯誤的密碼,正確的密碼打印我知道這並不能解釋它爲什麼會這樣做,但我希望它有助於解決您的問題並查看發生了什麼。