Python 输入两个登录密码的 telnet 脚本?

Python telnet script with two login passwords input?

这是我第一次使用 python 所以请帮忙...:) 如果我知道正确的密码,这个 telnet 脚本对我来说工作正常,但 192.168.1.1 上的路由器有时会使用密码启动:password1,有时使用密码:password2,我需要脚本完全自动化,因此需要直接从脚本中读取密码,因为无论密码是第一个还是第二个,我都想远程登录并登录到路由器。

import telnetlib
import time

router = '192.168.1.1'
password = 'password1'
username = 'admin'

tn = telnetlib.Telnet(router)
tn.read_until(b"Login: ")
tn.write(username.encode("ascii") + b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
print("Successfully connected to %s" % router)
tn.write(b"sh ip int bri\n")
time.sleep(2)
print (type("output"))
output = tn.read_very_eager()
#print(output)
output_formatted = output.decode('utf-8')
print(output_formatted)
print("done")`

我如何修改这段代码,让它在第一个密码不正确的情况下尝试第二个密码,以便在两种情况下都能通过 telnet 成功登录(password1password2)?

写入第一个密码后,tn.write(password...),您需要确定什么输出对应于正确的登录。例如,这可能是以“ok >”结尾的命令提示符。对于错误的密码,您需要检测另一个密码提示对应的输出,例如再次“密码:”,或者从“登录:”重新开始。

然后您可以使用 telnetlib 的 expect() 方法通过将它们放入列表中来同时查找这 2 个输出,例如 ["ok >", "Password: "]。参见 pydoc telnetlib。此方法 returns 一个元组 (列表中的索引,匹配对象,文本读取直到匹配)。唯一感兴趣的是第一个,索引;如果看到“ok >”,它将为 0,如果看到“密码:”,则为 1,如果在给定的超时时间内都没有看到,则为 -1。您只需要测试这个值并适当地进行。

index, match, text = tn.expect([b"ok >", b"Password: "], timeout=10)
if index==-1:
 ... # oops, timeout
elif index==1:
 ... # need to send password2
else:
 ... # ok, logged in

注意,传递给 expect() 的字符串被编译成正则表达式,因此请注意使用特殊字符(参见 pydoc re)。