The module telnetlib implements the telnet protocol. Telnet is a protocol used on the Internet or local area networks, its used for bidirectional interactive text-oriented communication.

Telnet is a low level protocol, in the sense that we can implement application level protocols on top of it like HTTP or FTP.

Related Course: Complete Python Programming Course & Exercises

Telnet example

We use the telnetlib module to do the network logic. All we have to do is connect to the server on the right network port, send the message as bytes (default is unicode in Python3) and wait for reply.

 
import sys
import telnetlib

HOST = "www.python.org"
PORT = "80"

telnetObj=telnetlib.Telnet(HOST,PORT)
message = ("GET /index.html HTTP/1.1\nHost:"+HOST+"\n\n").encode('ascii')
telnetObj.write(message)
output=telnetObj.read_all()
print(output)
telnetObj.close()

In this small example we implement a message of the HTTP protocol, then request the page index.html. we encode the message to ascii using the line:

 
message = ("GET /index.html HTTP/1.1\nHost:"+HOST+"\n\n").encode('ascii')

Telnet essentially is a byte-level connection, we can implement many application level protocols on top of it, HTTP is just one of them.

Download network examples