You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python Telnet脚本实现双密码自动尝试登录路由器

实现Telnet脚本自动尝试多个密码登录路由器

我是Python初学者,现有一段Telnet脚本,在已知正确密码的情况下可正常登录IP为192.168.1.1的路由器。但该路由器启动时可能使用密码password1,也可能使用密码password2。我需要将脚本修改为全自动运行模式,直接从脚本中读取预设的两个密码,实现无论路由器使用哪一个密码,都能成功通过Telnet登录并执行操作。现有脚本代码如下:

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登录?

这其实很简单,我们可以把密码放进一个列表里循环逐个尝试,每次失败后重新建立Telnet连接(失败后的连接状态已经异常,没法复用),直到找到正确的密码为止。下面是修改后的完整代码:

import telnetlib
import time

router = '192.168.1.1'
username = 'admin'
# 把两个密码放到列表里,按顺序尝试
passwords = ['password1', 'password2']
tn = None
login_success = False

for pwd in passwords:
    try:
        # 每次尝试都新建一个Telnet连接
        tn = telnetlib.Telnet(router)
        # 输入用户名
        tn.read_until(b"Login: ")
        tn.write(username.encode("ascii") + b"\n")
        # 输入当前尝试的密码
        tn.read_until(b"Password: ")
        tn.write(pwd.encode('ascii') + b"\n")
        
        # 这里需要根据你的路由器实际情况调整:
        # 等待读取登录成功后的提示符(比如路由器的命令行提示符,比如b">"或者b"#")
        # 或者如果登录失败,路由器会返回错误提示,比如b"Login incorrect"
        # 设置3秒超时,尝试读取成功提示符
        try:
            # 假设登录成功后会出现">"提示符,你可以根据自己路由器的实际输出修改
            tn.read_until(b">", timeout=3)
            print(f"Successfully connected to {router} using password: {pwd}")
            login_success = True
            break  # 登录成功,跳出循环
        except telnetlib.TelnetTimeoutError:
            # 超时说明密码不对,关闭当前连接,继续尝试下一个密码
            print(f"Failed to login with password: {pwd}, trying next one...")
            tn.close()
            continue
    except Exception as e:
        print(f"Error occurred when trying password {pwd}: {str(e)}")
        if tn:
            tn.close()
        continue

if login_success and tn:
    # 登录成功后执行你的操作
    tn.write(b"sh ip int bri\n")
    time.sleep(2)
    output = tn.read_very_eager()
    output_formatted = output.decode('utf-8')
    print(output_formatted)
    print("done")
    tn.close()
else:
    print("All passwords failed to login, please check your passwords or router status.")

关键改动说明:

  • 密码列表化:把单个密码改成passwords列表,方便循环遍历尝试。
  • 循环尝试机制:逐个遍历密码,每次尝试都新建Telnet连接,避免之前失败的连接状态影响后续尝试。
  • 登录状态判断:通过read_until读取登录成功后的提示符(比如>),如果超时则判定密码错误,继续下一个。你可以根据自己路由器的实际输出,把判断条件改成对应的错误提示(比如b"Password incorrect"),准确性会更高。
  • 异常处理:加入了基本的异常捕获,避免脚本因为连接错误直接崩溃,同时在失败后关闭当前连接。
  • 最终状态校验:循环结束后检查是否登录成功,只有成功才执行后续的命令操作,否则提示所有密码都失败。

内容的提问来源于stack exchange,提问作者BoardID

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:24:05