What does "\r" do in the following script?

Alinwndrld picture Alinwndrld · Jan 30, 2013 · Viewed 120.4k times · Source

I am using following script to reboot my router using Telnet:

#!/usr/bin/env python

import os
import telnetlib
from time import sleep

host = "192.168.1.1"
user = "USER"
password = "PASSWORD"
cmd = "system restart"

tn = telnetlib.Telnet(host)
sleep(1)

tn.read_until("Login: ")
tn.write(user + "\n\r")
sleep(1)

tn.read_until("Password: ")
tn.write(password + "\n\r")
sleep(1)

tn.write(cmd + "\n\r")

I don't know why but removing "\r" from above code make the script non-working. So what does "\r" do in this script and when to use "\r" in general?

Note: I know about "Carriage Return" but still could not figure out its use in my script. I am running this script in Linux.

Answer

Some programmer dude picture Some programmer dude · Jan 30, 2013

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.