Python Network Programming Telnet

Telnet Network Programming in Python

Telnet is a network protocol that allows a user of one computer to log in to another computer that is also part of the same network. The telnet command is used with a host name, followed by user credentials. After a successful login, the remote user can access applications and data in a manner similar to that of a normal user of the system. Of course, some permissions can be controlled by the system administrator who sets up and maintains the system.

In Python, telnet is implemented by the telnetlib module, which contains the Telnet class, which has the methods necessary to establish a connection. In the following example, we also use the getpass module to handle the password prompt as part of the login process. Furthermore, we assume that the connection is being made to a Unix host. The various methods of the telnetlib.Telnet class used in the program are explained below.

  • Telnet.read_until – Reads until a given string is encountered, expected, or until a timeout number of seconds has passed.
  • Telnet.write – Writes a string to the socket, doubling any IAC characters. This may block if the connection is blocked. May raise socket.error if the connection is closed.

  • Telnet.read_all() – Reads all data until EOF; blocks until the connection is closed.

Example

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")

tn.write("lsn")
tn.write("exitn")

print tn.read_all()

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

Note that this output is specific to the remote machine, whose details were submitted when the program was run.

Leave a Reply

Your email address will not be published. Required fields are marked *