Python is a versatile language, and one of its many uses includes creating a Telnet client. Telnet, an integral part of network communication, can be efficiently handled using Python’s telnetlib module. In this guide, we will explore how to build a Telnet client in Python.
Scripting is where Python really pays off. The Python Scripting Essentials Bundle has the kind of small automation projects you would build for work.
Telnet is an old text protocol that sends keystrokes over a network. Python has a
module for it, telnetlib, so you can log into a host from a script and
send it commands.
Understanding Telnet
Telnet is a widely used protocol for text-based communication over the Internet or local area networks. Its strength lies in being a foundation - you can build application-level protocols such as HTTP or FTP atop it.
If you’re new to Python, we have a lot of exercises that can help you dive deeper:
Crafting a Telnet Client in Python
With Python’s telnetlib module, we can manage the network logic with ease. The basic steps involve connecting to the appropriate server port, dispatching our message (in bytes), and then waiting for a response.
Here’s a simple example to illustrate:
import sys |
In the snippet above, we are sending an HTTP request to fetch the index.html page from Python’s official website. Note that we have to encode our message to ascii, given Telnet’s byte-level communication nature.
The essence of this code snippet is to demonstrate that Telnet is flexible. While we used HTTP in this instance, many application-level protocols can be implemented using Telnet as the foundation.
Want more examples? You can download more network examples to further enhance your understanding.
The steps
tn = telnetlib.Telnet('host', port, timeout=10)opens the connection.tn.read_until(b'login: ')waits for a prompt. Always wait for the prompt, otherwise you write before the other side is ready.tn.write(b'user\n')sends a line. The bytes need the \n on them.tn.read_very_eager()reads everything that is waiting.tn.close()hangs up.
Telnet sends your password in plain text, so only use it on a network you trust or on localhost.
For anything real use SSH, with the paramiko package. It encrypts
everything, it is about the same amount of code, and servers that dropped telnet years
ago are the normal case now.
Want more practice on this? Practise this on PyChallenge, there are short browser exercises you can run right after reading.
