Python read Router IP from file and telnet into
Question: I would like to read a router IP from a text file, then telnet into it:

    
    
    import sys
    import telnetlib
    
    f = open("C:\\MyIP.txt","r")
    line = f.readline()
    
    user = "username"
    password = "password"
    
    for line in f:
    
      tn = telnetlib.Telnet(line)
      tn.read_until("Login: ")
      tn.write(user + "\n")
      if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    f.close()
    

However, in the above code, if I try to read it directly from a file, it's not
working.

Only like this:

    
    
    import getpass
    import sys
    import telnetlib
    hostserver = "192.168.2.1"
    newline = "\n"
    username = "username" + newline
    password = "password" + newline
    telnet = telnetlib.Telnet(hostserver)
    telnet.read_until("Login: ")
    telnet.write(username+ "\n")
    telnet.read_until("Password: ")
    telnet.write(password+ "\n")
    while 1:
        command = raw_input("> ")
        telnet.write(command+ "\n")
        if command == "exit":
            break
        telnet.read_all()
    

Any help is appreciated


Answer: You have the statement

    
    
    line = f.readline()
    

and then later, you have:

    
    
    for line in f:
    

The `for` loop will loop over each line of the file _that has not already been
read_. It doesn't really look like you want to loop at all. Remove the `for`
statement since your `line` variable has already been set above.

