Telnet Automation / Scripting Using Python
Last Updated :
24 Apr, 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
GUI Automation using Python
In this article, we will explore how we can do GUI automation using Python. There are many modules that can do these things, but in this article, we will use a module named PyAutoGUI to perform GUI and desktop automation using python. We would explore two sections - How to automatically use the mou
12 min read
Google Maps Selenium automation using Python
Prerequisites: Browser Automation using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS, and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can
4 min read
Browser Automation Using Selenium
Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Mastering Selenium will help you automate your day to da
3 min read
Add a User in Linux using Python Script
Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you. Examples: Input : Enter
1 min read
Port Scanner using Python
Prerequisites: Socket Programming in Python This article is just to provide a sample code to generate a Port Scanner. This Port Scanner will work for both the Web Applications as well as remote Host. This tool has been created to provide the basic functionality of a Port Scanner. The general concept
2 min read
Python Script to Automate Software Installation
Software installation can often be a time-consuming and monotonous undertaking, particularly when dealing with multiple applications. Python scripting gives a solution by enabling automation of the entire installation process which leads to more time consuming, enhances productivity, and gets rid of
4 min read
Text Searching in Google using Selenium in Python
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. In this article, we are go
3 min read
How to Run a Python Script using Docker?
Docker helps you to run your Python application very smoothly in different environments without worrying about underlying platforms. Once you build an image using dockerfile you can run that image wherever you want to run. Docker image will help you to package all the dependencies required for the a
8 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Â Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that cust
7 min read
Turing Machine Simulator Using Python
Turing machines and deterministic finite automata (DFAs) are two fundamental concepts in computer science and automata theory. Both these concepts are used to model and analyze computational systems and are essential tools in understanding the limits of computation. A Turing machine is a theoretical
11 min read