Paramiko在异常后没有返回提示符(Python 3)

时间:2014-04-14 20:21:27

标签: python python-3.3 paramiko

RHEL 6上的Python 3.3。

使用下面的代码,如果我第一次获得正确的密码,它会正确打印'authenticated',然后将我返回到我的shell。如果我错误地输入密码3次,它会正确打印“太多尝试,抱歉。”,然后将我返回到我的shell。但是如果我错误地输入了一两次密码,那么就把它弄好,然后打印出'authenticated',然后挂在那里并且不会把我送回我的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')

1 个答案:

答案 0 :(得分:1)

正如特德拉尼所说,你需要添加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()),您可以看到有效线程:

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

当我测试它时,它会在一个错误的密码和正确的密码后打印:

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

我知道这并没有真正解释为什么会这样做,但我希望它有助于解决您的问题,看看发生了什么。