[英]Python telnet script Loop
I have a Telnet python script that works fine with one "IP" but when i add "for" to works on multiple IP's It gives me an error.我有一个 Telnet python 脚本,它适用于一个“IP”,但是当我添加“for”以适用于多个 IP 时,它给了我一个错误。
This is my script:这是我的脚本:
import getpass
import telnetlib
HOST = "192.168.122.240,192.168.122.241"
user = input("Enter your remote account: ")
password = getpass.getpass()
for ip in HOST:
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")
This Is My Error:这是我的错误:
Traceback (most recent call last):
File "telnet.py", line 9, in <module>
tn = telnetlib.Telnet(ip)
File "/usr/lib/python3.5/telnetlib.py", line 218, in __init__
self.open(host, port, timeout)
File "/usr/lib/python3.5/telnetlib.py", line 234, in open
self.sock = socket.create_connection((host, port), timeout)
File "/usr/lib/python3.5/socket.py", line 711, in create_connection
raise err
File "/usr/lib/python3.5/socket.py", line 702, in create_connection
sock.connect(sa)
OSError: [Errno 22] Invalid argument
Can Anyone please tell me what im doing wrong?谁能告诉我我做错了什么? Thanks,谢谢,
A loop iterates over multiple items.一个循环遍历多个项目。
Your current code simplified to demonstrate the issue:您当前的代码简化以演示该问题:
HOST = "192.168.122.240,192.168.122.241"
for ip in HOST:
print(ip)
executes the loop for each character in the string: 1
, then 9
, then 2
, etc. because a string is a sequence of characters.对字符串中的每个字符执行循环: 1
,然后9
,然后2
等,因为字符串是字符序列。
Clearly, you want a sequence of strings, eg a list:显然,您需要一个字符串序列,例如一个列表:
HOST = ["192.168.122.240", "192.168.122.241"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.