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

1 投票
1 回答
545 浏览
提问于 2025-04-18 02:43

在RHEL 6上使用Python 3.3。

下面的代码中,如果我第一次输入密码正确,它会正确显示“已认证”,然后让我回到命令行。如果我连续输入错误的密码3次,它会显示“尝试次数太多,抱歉。”然后让我回到命令行。但是,如果我输入错误的密码一次或两次后再输入正确的密码,它会显示“已认证”,但接着就卡在那里,不会让我回到命令行。我必须按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 个回答

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(),当我输入一个错误的密码后再输入正确的密码时,脚本会卡住。其他情况下就不会卡住(比如输入两个错误密码再输入正确的密码是没问题的,不会卡住)。

如果你想查看当前的线程,可以先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))>]

我知道这并没有真正解释为什么会这样,但我希望这能帮助你解决问题,并了解发生了什么。

撰写回答