Python - Telnet

Rohit Mohite

9 months ago

Telnet in Python | Insideaiml
Telnet in Python | Insideaiml
Telnet is a type of network protocol that allows a user in one computer to log on to another computer which also belongs to the same network. The telnet command is used along with the hostname and then the user credentials are entered. Upon successful login, the remote user can access the applications and data in a way similar to the regular user of the system. Of course, some privileges can be controlled by the administrator of the system who sets up and maintains the system.
In Python telnet is implemented by the module telnetlib which has the Telnet class which has the required methods to establish the connection. In the below example we also use the getpass module to handle the password prompt as part of the login process. Also, we assume the connection is made to a unix host. The various methods from telnetlib.Telnet the class used in the program is explained below.
  • Telnet.read_until - Read until a given string, expected, is encountered or until timeout seconds have passed.
  • Telnet.write - Write a string to the socket, doubling any IAC characters. This can block if the connection is blocked. May raise socket.error if the connection is closed.
  • Telnet.read_all() - Read all data until EOF; block until connection closed.


import getpass
import telnetlib

HOST = "http://localhost:8000/"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")


When we run the above program, we get the following output

- lrwxrwxrwx    1 0        0            1 Nov 13  2012 ftp -> .
- lrwxrwxrwx    1 0        0            3 Nov 13  2012 mirror -> pub
- drwxr-xr-x   23 0        0            4096 Nov 27  2017 pub
- drwxr-sr-x   88 0        450          4096 May 04 19:30 site
- drwxr-xr-x    9 0        0            4096 Jan 23  2014 vol
Please note that this output is specific to the remote computer whose details are submitted when the program is run.
I hope you enjoyed reading this article and finally, you came to know about Python - Telnet.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review