Qwerty
Qwerty

Reputation: 93

Telnet output parsing

I'm now trying to work with telnetlib in Python 3.4. All I want is to try send command to my access point and get some response. My code:

`import telnetlib
 import time

 user='admin'
 password='admin'
 host='192.168.1.1'


 try:
    tn=telnetlib.Telnet("host")
    tn.read_until(b"Login: ")
    tn.write(user.encode() + "\r\n".encode())
    tn.read_until(b"Password: ")
    tn.write(password.encode() + "\r\n".encode())
    print("Connection establised")
 except Exception:
    print("Connection failed")

 cmd="interface AccessPoint\r\n"
 tn.write(cmd.encode())
 cmd2="ssid TEST\r\n"
 tn.write(cmd2.encode())

 output=n.read_eager()
 while output:
    print(output.decode())
    time.sleep(.2)
    output=tn.read_eager()

` For example, this script should change name of the SSID to TEST. Then I'm doing it in Putty, it's fine: enter image description here

But then I'm trying to read response from my script, I see smth like that:

enter image description here

Please, tell me what does all these symbols mean? Is there way to cut them all from my logs?

P.S. Tried all other ways of reading, like read_all. Tried without decode(), tried with decode('utf-8'), but symbols were here always. What else should I do?

Thank you, Mairy.

Upvotes: 1

Views: 3907

Answers (1)

Robᵩ
Robᵩ

Reputation: 168586

Your access point believes it is talking to a terminal emulator. Those symbols are so-called "ANSI Escape Codes," after the now-withdrawn standard ANSI X3.64.

The string Escape-[-K means "erase to end of line." The string Escape - [ - 1 - 6 - D means "move the cursor 16 spaces to the left."

  • You could convince your access point that it isn't talking to a terminal emulator, or that it is talking to a non-ANSI terminal emulator, or

  • You can erase them from your logged strings by using an appropriate regular expression such as msg = re.sub('\x1b\\[\\d*[A-Z]', '', msg)

Reference:

Upvotes: 1

Related Questions