Open In App

Telnet – Python Network programming

Improve
Improve
Like Article
Like
Save
Share
Report

Telnet is a networking protocol that follows a client-server model. It uses TCP as its underlying communication protocol. It is typically used to start and a remote command-line session, typically on a server.  

Some facts about telnet:

  • Uses Transmission Control Protocol for data transmission.
  • Bi-directional 8-bit protocol
  • The protocol standard was initially described in RFC15 and was further extended in RFC854 and RFC855.
  • It was developed in 1969.

In python, telnet communication is facilitated by the telnetlib module. The telnetlib module provides Telnet class that implements telnet protocol described in RFC 854.

The Telnet Class:

Syntax: class telnetlib.Telnet(host=None, port=0[, timeout]) :

Input Parameters:

  • host(optional): it takes the server name or ip-address. Example: 127.0.0.1, “localhost”
  • port(optional): takes the port number if not provided uses the default port number.
  • timeout(optional): an additional parameter can be passed to specify the timeout duration else the global timeout duration is used.

If the Telnet object is created without any parameters, a connection can be established by calling the open() method. Alternatively, the user can pass the host and port details, in which case the object is returned with a connection established.

WARNING: A lot of functions in the Telnet class raise EOFError. Hence, appropriate exception handling must be done.

Important Functions:

  • Telnet.read_until(expected, timeout=None)
  • Telnet.read_all()
  • Telnet.open(host, port=0[, timeout])
  • Telnet.close()
  • Telnet.write(buffer)
  • Telnet.interact()

We have explained the usage of the functions in the following code.

Complexity:

When telnet was developed basic ASCII text was predominant. Present-day terminals usually used Unicode as standard. Additionally, color coding and formatting make the text that is visible on-screen very different from the byte strings that are passed via telnet. This creates confusion while using some functions of the Telnet class. This article aims to help in that respect.

Steps to writing a telnet program:

Step 1: Start a telnet server

Depending on the requirement you may have to start a telnet server or may be provided. If you have a telnet server already running proceed to step 2 else start the server.

For illustration purposes, a telnet server running on “localhost” will be used.

Step 2: Finding the magic sequence

Take a look at the following picture:

$ telnet localhost
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Linux 5.10.0-5mx-amd64 (mx) (2)

mx login: pvtejeswar
Password:
Last login: Sun Sep 26 05:24:30 EDT 2021 from localhost on pts/2
No mail.
pvtejeswar@mx:~     <=========================
$

You might expect the text written at the red triangle to be: “pvtejeswar@mx:~\n$ “ but remember there is a lot of background processing and formatting going on. The text at the red triangle is infact: b”\x1b[1;35mpvtejeswar\x1b[0m@\x1b[1;36mmx\x1b[0m:\x1b[1;32m~\x1b[0m\r\r\n\x1b[1;32m$\x1b[0m “. Now you might be asking: well how do I know what this magic string looks like in my case. The following program will help you with that.

Python3




import telnetlib
import getpass
 
 
HOST = "localhost"
user = input("USERNAME: ")
password = getpass.getpass()
 
tn = telnetlib.Telnet()
tn.open(HOST)
 
tn.read_until(b"login: ")
tn.write(user.encode("ascii")+b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode("ascii")+b"\n")
tn.write(b"exit\n")
print(tn.read_all())
tn.close()


Output:

pvtejeswar@mx:~/Desktop/telnet

$ python3 telnet_base.py 

USERNAME: pvtejeswar

Password: 

b’\r\nLast login: Sun Sep 26 04:56:42 EDT 2021 from localhost on pts/2\r\nNo mail.\r\n\x1b[1;35mpvtejeswar\x1b[0m@\x1b[1;36mmx\x1b[0m:\x1b[1;32m~\x1b[0m\r\r\n\x1b[1;32m$\x1b[0m exit\r\nlogout\r\n’

Just by eyeballing it you may understand the output between “\r\n” and “exit” is string corresponding to  “pvtejeswar@mx:~\n$ “. Now we know that all input prompts will have “pvtejeswar@mx:” which is equivalent to b”\x1b[1;35mpvtejeswar\x1b[0m@\x1b[1;36mmx\x1b[0m:”. Now we are ready to write the actual program.

Step 3: Writing the actual code.

Armed with the knowledge that we gathered from step 2 we will write the code to interact with telnet command by command:

Python3




import telnetlib
import getpass
 
 
HOST = "localhost"
user = input("USERNAME: ")
password = getpass.getpass()
 
# MAGIC is the formatted output information
# that we gathered in step 2.
MAGIC = b"\x1b[1;35mpvtejeswar\x1b[0m@\x1b[1;36mmx\x1b[0m:"
tn = telnetlib.Telnet()
tn.open(HOST)
 
tn.read_until(b"login: ")
tn.write(user.encode("ascii")+b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode("ascii")+b"\n")
 
# reading until we reach the
# MAGIC or reading whatever is
# there and timeout after 5 sec.
tn.read_until(MAGIC, 5)
 
# we write the command to the terminal
tn.write(b"ls -ltr /\n")
print("="*80)
print("output for 'ls -ltr /': ")
 
# output needs to be decoded to human readable
print(tn.read_until(MAGIC).decode('ascii'))
print("="*80)
tn.write(b"exit\n")
 
# read everything there is on the console
print(tn.read_all().decode('ascii'))
tn.close()


Output:

pvtejeswar@mx:~/Desktop/telnet
$ python3 telnet.py
USERNAME: pvtejeswar
Password:
================================================================================
output for 'ls -ltr /':
~
$ ls -ltr /
total 64
lrwxrwxrwx   1 root root     8 Apr  7 23:50 sbin -> usr/sbin
lrwxrwxrwx   1 root root     9 Apr  7 23:50 lib64 -> usr/lib64
lrwxrwxrwx   1 root root     7 Apr  7 23:50 lib -> usr/lib
lrwxrwxrwx   1 root root     7 Apr  7 23:50 bin -> usr/bin
drwxr-xr-x   2 root root  4096 Apr  7 23:50 media
drwxr-xr-x   3 root root  4096 Apr  7 23:56 opt
drwxr-xr-x  14 root root  4096 Apr  7 23:57 usr
drwxr-xr-x  12 root root  4096 Apr  7 23:58 var
drwx------   2 root root 16384 Sep 24 21:34 lost+found
drwxr-xr-x   3 root root  4096 Sep 24 21:38 home
drwxr-xr-x   3 root root  4096 Sep 24 21:39 boot
drwxr-xr-x   2 root root  4096 Sep 24 21:39 mnt
dr-xr-xr-x  13 root root     0 Sep 24 21:39 sys
dr-xr-xr-x 229 root root     0 Sep 24 21:39 proc
drwx------   7 root root  4096 Sep 25 03:24 root
drwxr-xr-x 147 root root 12288 Sep 25 03:27 etc
drwxr-xr-x  15 root root  3360 Sep 26 04:43 dev
drwxr-xr-x  32 root root  1180 Sep 26 04:43 run
drwxrwxrwt   9 root root  4096 Sep 26 05:24 tmp
pvtejeswar@mx:
================================================================================
~
$ exit
logout

Conclusion

Telnet is an old protocol developed in 1970s. It’s not aware of for the recent day formatting and character sets used in modern-day terminals. Hence, when working with telnet we always have to keep that in mind. This guide aims to help in getting command by command interaction using telnet and provide a general overview of the telnetlib library.



Last Updated : 04 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads