'sending commands in telnetlib.Telnet

I am trying to do the most basic thing, telnet to a device, type password, type a command to reboot it (showing time for testing). Works it I use an actual telnet client but not via python telnetlib Note: I have tested a slightly modified version of below on a switch and works 100% As per below - how do I stop the dont echo / wont echo loop?

import telnetlib
import time
HOST = "1.2.3.4"
password = ("cisco")

tn = telnetlib.Telnet(HOST)

tn.set_debuglevel(1)
tn.read_until(b"Password :")
time.sleep(1)
tn.write(password.encode('ascii') + b"\r\n")
#time.sleep(.5)
tn.read_until(b"> ")
tn.write(b"show time\r\n")
tn.read_until(b"m> ")
tn.write(b"exit\n")
tn.close()
print(tn.read_all().decode('ascii'))
tn.close()

50% of the time it will fail with a loop of telnetlib sending Don't Echo Device responding Won't Echo

Telnet(1.2.3.4,23): recv b'\xff\xfb\x03\xff\xfb\x01'
Telnet(1.2.3.4,23): IAC WILL 3
Telnet(1.2.3.4,23): IAC WILL 1
Telnet(1.2.3.4,23): recv b'\r\n\r\nPassword :'
Telnet(1.2.3.4,23): send b'cisco\r\n'
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
Telnet(1.2.3.4,23): IAC WONT 1
Telnet(1.2.3.4,23): recv b'Password :'
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
Telnet(1.2.3.4,23): IAC WONT 1
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
Telnet(1.2.3.4,23): IAC WONT 1
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
etc

50% of the time it will sort or work (it wont print(tn.read_all().decode('ascii')) - print result to the screen correctly - but probably related to the loop)

Telnet(1.2.3.4,23): recv b'\xff\xfb\x03\xff\xfb\x01'
Telnet(1.2.3.4,23): IAC WILL 3
Telnet(1.2.3.4,23): IAC WILL 1
Telnet(1.2.3.4,23): recv b'\r\n\r\nPassword :'
Telnet(1.2.3.4,23): send b'cisco\r\n'
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
Telnet(1.2.3.4,23): IAC WONT 1
Telnet(1.2.3.4,23): recv b'\r\nCisco Systems, Inc. Copyright 2000-2005\r\nCisco I'
Telnet(1.2.3.4,23): recv b'P phone  MAC: 0011:20c3:7b5f\r\nLoadid:  SW: P0S3-8-'
Telnet(1.2.3.4,23): recv b'12-00  ARM: PAS3ARM1  Boot: PC030301  DSP: 4.0(5.0'
Telnet(1.2.3.4,23): recv b')[A0]\r\n3CXPhoneSystem> '
Telnet(1.2.3.4,23): send b'show time\r\n'
Telnet(1.2.3.4,23): recv b'\xff\xfc\x01'
Telnet(1.2.3.4,23): IAC WONT 1
Telnet(1.2.3.4,23): recv b'\r\n\r\nTimer List - Current Time: 463147 \r\nExpired: 0'
Telnet(1.2.3.4,23): recv b', Canceled: 0, Started: 0, Free List: 60\r\n\r\n3CXPho'
Telnet(1.2.3.4,23): send b'exit\n'
Telnet(1.2.3.4,23): recv b'neSystem> '


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source