正如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())
當我測試了它,它經過一個錯誤的密碼,正確的密碼打印我知道這並不能解釋它爲什麼會這樣做,但我希望它有助於解決您的問題並查看發生了什麼。
適用於python 2.x linux上的我。可能不相關,但嘗試關閉腳本末尾的ssh連接,即使連接失敗 - paramiko運行後臺線程,也許這與它有關。 – tdelaney