Telnet – Python Network programming
Last Updated :
06 Sep, 2024
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.
Python
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:
Python
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.
Similar Reads
Python Network Programming
Python provides two levels of access to network programming. These are -Â Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.High-Level Access: At the high
6 min read
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python for Kids - Fun Tutorial to Learn Python Programming
Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzle
15+ min read
Python List Add/Append Programs
This article covers a wide range of methods for adding elements to a list, including: Basic addition techniques like append(), extend(), and insert().Appending multiple items, lists, tuples, dictionaries and objects.Performing list modifications such as adding at the beginning, middle or end.Advance
3 min read
Python Program that Sends And Receives Message from Client
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the serv
3 min read
Implementing Checksum using Python
The checksum is a kind of error Detection method in Computer Networks. This method used by the higher layer protocols and makes use of Checksum Generator on the Sender side and Checksum Checker on the Receiver side. In this article, we will be implementing the checksum algorithm in Python. Refer to
3 min read
Small World Model - Using Python Networkx
In this article, we will learn how to create a Small World Network using Networx module in Python. Before proceeding that let's first understand some basics about Small World Phenomenon. What is Small World Phenomenon ? Small World Phenomenon is the study and notion that we are all connected via a s
4 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Menu driven Python program to execute Linux commands
Linux is one of the most popular operating systems and is a common choice for developers. However, it is difficult to remember the vast range of commands that Linux supports, and hence a Python program that can run these commands easily is demonstrated below. In this article, we will deal with a Pyt
3 min read
Python program to find if two IP Address belongs to Same or Different Network
Prerequisites: Classless Inter Domain Routing (CIDR) Given two IP Addresses in CIDR Notation determine whether they belong to Same Network or Different Network. Two IP addresses are said to be in Same Network if the Network ID of both the IP Addresses are same. Examples: Input : IP1 = 192.168.1.0/8,
2 min read