Telnet Automation / Scripting Using Python
Last Updated :
05 May, 2025
Telnet is the short form of Teletype network, which is a client/server application that works based on the telnet protocol. Telnet service is associated with the well-known port number - 23. As Python supports socket programming, we can implement telnet services as well. In this article, we will learn how to automate telnet login and command execution using a simple Python script.
Telnet Automation/Scripting using Python
The main reason for using Python in Telnet Automation is that Python has a basic syntax when compared to other scripting languages which allow us to focus more on the logic of the program. It has a large community which makes troubleshooting, a piece of cake. Python provides a wide range of libraries that can be imported easily. Each library serves a different purpose. This feature of Python makes it suitable for multiple purposes which includes telnet automation.
Telnetlib Module
The telnetlib module consists of a class called Telnet that can be used to implement the telnet protocol in our python code. The instances of the Telnet class have several methods that can be used to establish a telnet connection.
The methods that we are going to use from this module are explained below:
Telnet()
This method is used to establish a telnet connection with a host, on a specific port. The timeout parameter is set to 'None' by default.
telnetlib.Telnet(host=None, port=0[, timeout])
read_until()
This method is used to read data in a controlled manner by specifying the expected end of the message such as a new line character.
Telnet.read_until(format, string_to_look_for)
write()
In the context of socket programming, the write method is used to send data over a socket to a connected peer.
socket_object.write(binary_data)
decode()
This method does the opposite of encode() method. It converts binary data into human-readable form.
binary_data.decode(decoding_format)
Getpass Module
Hardcoding passwords in a script is not recommended by coding experts. Instead, it has to be given as input to the script in the safest way possible. In our script, we are going to use the getpass module to get the password from the user without displaying the password in the terminal window.
getpass()
This method is used to get sensitive data from the user such as passwords in a private way. It also comes with a default prompt 'password' that can be changed to our wish.
getpass.getpass(prompt='Password: ', stream=None)
Note: The argument 'stream' is ignored for the windows operating system.
Steps to Build and Run the Telnet Script in Python
I'm using a Debian-based Linux operating system here to carry out the demonstration.
Step1:
Ensure that the telnet server is running in the host machine to which you are going to connect using the script. For simplicity, we are going to connect to localhost which is nothing but our own machine. You can check if a telnet server is running on your machine by typing the following command in the terminal:
telnet localhost
This command connects to the telnet server running at localhost. If you can manually connect to the server in this way, then your script will also be able to connect to it.
Step 2:
Create a new python file with any name of your choice with a '.py' extension. The location of this file is also arbitrary. The command to do this is given below:
touch <file_name.py>
Step 3:
Now it's time to insert our script into this file. You can use a text editor of your choice for this purpose. I'm using a mousepad here.
mousepad <file_name>
Code
Python3
#!/bin/python3
import telnetlib
import getpass
# Set the Telnet server address and port number
host = "localhost"
port = 23
# Set the username
username = "gfg_user"
# Get password from the user
print(f"Logging in as '{username}'")
password = getpass.getpass()
# Set the command to execute
command = "ls -l"
# Create a Telnet object
tn = telnetlib.Telnet(host, port)
# Wait for the login prompt
tn.read_until(b"login: ")
# Enter the username and wait for the password prompt
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"Password: ")
# Enter the password and wait for the shell prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"$ ")
# Execute the command and wait for the output
tn.write(command.encode('ascii') + b"\n")
output = tn.read_until(b"$ ")
# Print the output
print(output.decode('ascii'))
# Close the Telnet connection
tn.close()
Note: Make sure to add the line '!#/bin/python3' at the beginning of the file. This will tell your system which interpreter should be used to interpret this script.
Also make sure to replace the value assigned to the variable 'username' with an existing username of your system.
Step 4:
Save the file and exit. It's time to run the script. Now run the script by using the following command.
python3 <file_name.py>
Output:
In the output, you can see for yourself that we have successfully logged into the system as 'gfg_user' by entering the password for the provided user. The Linux command 'ls -l' lists out all the files in the directory along with its permission settings. The list of files in the home directory of user - 'gfg_user' is printed on the terminal.
This example shows a single command in the script. But the actual scope of telnet is limitless. You can build creative scripts by combining various Linux commands and thus perform more powerful automation scripts.
Similar Reads
Python Tutorial - Learn Python Programming Language 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. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 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
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read