Learning Python with telnetlib. Script seems to stall - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Learning Python with telnetlib. Script seems to stall (/thread-28549.html) |
Learning Python with telnetlib. Script seems to stall - John_Williamson - Jul-23-2020 I'm using pythpn 3.7.7 and working with an interface called Spyder on a Mac My goal is simply to be able to telnet into a device, run some commands, and exit the device. I am using a Cisco switch for this , at this time. I found the basic example of how to use the telnet library, which is as follows: import getpass import telnetlib HOST = "localhost" user = input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until(b"login: ") tn.write(user.encode('ascii') + b"\n") if password: tn.read_until(b"Password: ") tn.write(password.encode('ascii') + b"\n") tn.write(b"ls\n") tn.write(b"exit\n") print(tn.read_all().decode('ascii'))I then made some edits to match the output from the Cisco switch. My code looks like this: import getpass import telnetlib HOST = "10.14.31.68" user = input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) 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"sh ip int br\n") tn.write(b"exit\n") print(tn.read_all().decode('ascii'))I found a video on the learning.oreilly.com web site, where the author uses this exact same example code on a Cisco switch, so I know it should work. The issue is that after prompting for the remote account name, and I type in the name cisco, it never prompts for the password. It seems like it is stuck in a loop. If I control-C out of it, this is the Traceback: One thing I tried was to change the tn.read_until(b"Username: ") line to have the full test that shows up when I manually telnet into the switch, which is: But that didn't change the way the script runs.Interestingly, I just tried the script from my shell on the Mac and I do get prompted for the password. It still gets stuck there. Using just the Telnet command with the IP address in the shell and putting in my login name and password, work fine. No delays at all. RE: Learning Python with telnetlib. Script seems to stall - John_Williamson - Jul-23-2020 Further update: From the shell on my Mac, the script eventually runs. But it takes many minutes. |