单IP正常运行的Python Telnet脚本添加多IP循环后报错求助
问题分析与解决:Python Telnet批量操作报错
你的脚本核心问题出在多IP的遍历逻辑上——你把多个IP写成了一个逗号分隔的字符串,然后直接用for ip in HOST遍历,这会把字符串拆成单个字符逐个处理(比如第一次循环ip的值是'1'),用这种无效的"IP"去建立Telnet连接,自然会抛出Invalid argument的错误。
解决步骤
- 正确拆分多IP:把HOST变量改成列表格式,或者对原字符串进行分割,得到独立的IP地址列表。
- 遍历IP列表:循环遍历这个列表,每个元素都是完整的IP地址。
修正后的完整代码
import getpass import telnetlib # 方式1:直接定义为IP列表(推荐) HOSTS = ["192.168.122.240", "192.168.122.241"] # 方式2:如果需要从逗号分隔字符串转换,用下面这行替代上面的HOSTS # HOSTS = "192.168.122.240,192.168.122.241".split(',') user = input("Enter your remote account: ") password = getpass.getpass() for ip in HOSTS: print(f"Processing {ip}...") try: tn = telnetlib.Telnet(ip) tn.read_until(b"Username: ") tn.write(user.encode('ascii') + b"\n") if password: tn.read_until(b"Password: ") tn.write(password.encode('ascii') + b"\n") tn.write(b"enable\n") tn.write(password.encode('ascii') + b"\n") tn.write(b"conf t\n") tn.write(b"vlan 100\n") tn.write(b"name TEST_PY\n") tn.write(b"end\n") tn.write(b"logout\n") # 读取设备返回结果,确认操作状态 output = tn.read_all().decode('ascii') print(f"✅ Successfully configured {ip}\n{output}\n") except Exception as e: print(f"❌ Failed to process {ip}: {str(e)}\n")
额外优化说明
- 加入了
try-except异常捕获:单个IP连接失败不会导致整个脚本终止,还能直观看到错误原因。 - 增加了状态打印:方便跟踪每个IP的处理进度和结果。
- 读取设备输出:可以验证配置是否成功执行,排查潜在问题。
内容的提问来源于stack exchange,提问作者Linux User
相关产品推荐
相关产品推荐

