I am attempting to use Popen to automate a simple telnet session. In python 2.6.5 the following code works:
openCmd = subprocess.Popen("telnet 192.168.1.1", shell=True, stdout=PIPE, stdin=PIPE)
time.sleep(1)
openCmd.stdin.write("username\r")
time.sleep(1)
openCmd.stdin.write("password\r")
time.sleep(1)
openCmd.stdin.write("some command\r")
openCmd.terminate()
In python 3 it complained of a type error, so I figured I just had to add .encode() to the end of each str object (as shown below). Adding the .encode() did fix the type error, and I don’t get any exceptions, but the command I am trying to run on the remote machine doesn’t get run.
openCmd = subprocess.Popen("telnet 192.168.1.1", shell=True, stdout=PIPE, stdin=PIPE)
time.sleep(1)
openCmd.stdin.write("username\r".encode())
time.sleep(1)
openCmd.stdin.write("password\r".encode())
time.sleep(1)
openCmd.stdin.write("some command\r".encode())
openCmd.terminate()
I also tried .encode(“ascii”) and .encode(“UTF-8”). What am I doing incorrectly? I figure the issue is with the encoding, but I do not know for sure… I am running this program on a machine running Ubuntu 10.04.
Apparently all I needed to do was sleep on this one. It turns out that in Python 2.6.5 every
Had a shorter delay before the buffer was flushed than Python 3 did! Here is the final working program:
In case anyone wondered, I figured out how it worked by running Popen against ‘cat’ and carefully watching the output in Python 2.6.5 and Python 3 ^_^ .