在Python中验证Telnet会话的身份验证

1 投票
2 回答
3421 浏览
提问于 2025-04-16 18:47

我正在尝试通过telnet连接到一个Cisco交换机,并在上面运行几个命令。我可以检查主机是否存在,但不太确定怎么检查用户名或密码是否正确。这是我目前的进展(这是我课程的一部分)

def login(self):
    if self.user_name and self.password: 
        try:
            self.connection=telnetlib.Telnet(self.telnet_host)
            try:
                self.connection.read_until('sername:',1)
                self.connection.write(self.user_name+'\r\n')
                self.connection.read_until('assword:',1)
                self.connection.write(self.password+'\r\n')
                self.connection.read_until(self.prompt,1)
                print "Connected"
                self.loggedON=True
            except EOFError:
                print "Authentication to "+ self.telnet_host+" failed.\n"
                return
        except: 
            print "Can't connect to "+self.telnet_host+"\n"
            return
    else:
        if not self.user_name:
            self.user_name=raw_input("Username: ")
            self.login()
        else:
            self.password=raw_input("Password: ")
            self.login()

即使用户名或密码错误,它仍然会显示已连接。

2 个回答

0

首先,你不应该使用那种笼统的try/except块。捕捉异常时要更具体一些。此外,正如其他人提到的,你可以考虑使用SNMP。

话虽如此,如果你决定继续使用Telnet,那不如直接使用别人的代码。我通过简单的谷歌搜索找到了这个例子。

1

你也可以试试 Exscript

from Exscript.util.start import quickstart

def do_something(conn):
    conn.autoinit()
    conn.execute('show version')

quickstart('telnet://localhost', do_something)

这个 quickstart() 函数会让你输入用户名和密码(如果你不想这样,可以用 start())。如果登录失败或者出现其他错误,它会自动处理这些问题。你可能还想看看 Exscript.util.start

撰写回答