Telnet is a protocol that allows you to connect to a remote computer and execute commands. Python provides a built-in module called “telnetlib” that enables us to use Telnet in our code.
What is Telnet in Python?
Telnet clients let you connect to other Telnet Servers. You cannot connect to your own system and fire remote commands. For that, you need a Telnet Server and unfortunately, there is no native way to enable it in Windows 10. You have to install third-party apps to start serving Telnet on port 23.
Link: https://sourceforge.net/projects/hk-telnet-server/
Use Telnet with IP and Port
To start, make sure you have Python installed on your computer. You can download the latest version from the official Python website. Once you have Python installed, open your preferred code editor and follow the steps below.
Step 1: Import and Establish a Telnet connection
The first line, This line imports the telnetlib library, which provides a way to communicate with Telnet servers next creates a Telnet object and connects to a Telnet server running on localhost (IP address 127.0.0.1) on port 23. If the connection is successful, the Telnet object is assigned to the variable tn.
Python3
import telnetlib tn = telnetlib.Telnet( "127.0.0.1" , 23 ) |
Step 2: Send commands
This line sends the command “echo Hello World” to the Telnet server using the write() method of the Telnet object. Note that the command is sent as a byte string (b”echo Hello World\n”). The “b” before the string indicates that it should be sent as bytes, not as a regular string. Also, make sure to include the newline character (“\n”) at the end of the command, as this is what the server expects.
Python3
tn.write(b "echo Hello World\n" ) |
Step 3: Receive output
This line reads all the output from the Telnet server using the read_all() method of the Telnet object. The output is assigned to the variable output.
Python3
output = tn.read_all() # Print the output print (output) |
Step 4: Close the connection
Finally, we close the Telnet connection by calling the close method on the Telnet object.
Python3
tn.close() |
Complete Code
Python3
import telnetlib # Connect to the Telnet server tn = telnetlib.Telnet( "127.0.0.1" , 23 ) # Send a command to the server tn.write(b "echo Hello World\n" ) # Read the output from the server output = tn.read_all() # Print the output print (output) tn.close() |
Output:
Note: To get the output in the terminal after connecting the server we have to close the server then the output will be printed in the terminal.