Open In App

Telnet Automation / Scripting Using Python

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads