0

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.

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,

Linux User
  • 29
  • 4

1 Answers1

0

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.

Clearly, you want a sequence of strings, e.g. a list:

HOST = ["192.168.122.240", "192.168.122.241"]
VPfB
  • 14,927
  • 6
  • 41
  • 75