Python telnet 脚本循环

Python telnet script Loop

我有一个 Telnet python 脚本,可以在一个“IP”上正常工作,但是当我添加“for”以在多个 IP 上工作时,它会给我一个错误。

这是我的脚本:

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")

这是我的错误:

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

谁能告诉我我做错了什么? 谢谢,

一个循环遍历多个项目。

您当前的代码已简化以演示该问题:

HOST = "192.168.122.240,192.168.122.241"

for ip in HOST:
    print(ip)

对字符串中的每个字符执行循环:1,然后是 9,然后是 2,等等,因为字符串是一个字符序列。

显然,您需要一个字符串序列,例如列表:

HOST = ["192.168.122.240", "192.168.122.241"]