2017/01/23

Python for network engineers - telnetlib

The typical job of the network engineer is to manage the networks. To manage the network in traditional way, the network engineer connects to the CLI of the device and enters the series of commands. The most simple way to do the job is by using the telnet protocol. Python already includes telnet client in the standard library. The standard telnet library in python is called telnetlib. The goal of this post is to show, how to write a simple script, that connects to the router, executes some command and exits.

The telnetlib consists of python class Telnet. You have two options to initialise the Telnet instance and open the connection to the telnet client.

The first option is to create a instance of the Telnet and then use open() method to establish the connection.

conn = telnetlib.Telnet()
conn.open('192.168.35.121')

The other option is to establish connection during class initialisation.

conn = telnetlib.Telnet('192.168.35.121')

To read the data that is received from the connection, you can use read_until() method. You need to provide the expected string to the method. In this phase, we will assume that router is configured with AAA and "Username: " string is returned from the router. It is a good practice to include some timeout to the method, to prevent the blocking in the code. So our code will be:

conn.read_until('Username: ', 3)

The method will read until the given string is matched or until the timeout is reached. If there is no match the method will return whatever was received.

Now we are ready to send some data via telnet connection. You can use the write() method. The write() method expects the string that should be send to the telnet server. So in our example, we need to send username together with new line symbol (\n).

conn.write('cisco\n')

After you are finished it is advisable to close the connection using close() method.

conn.close()

So lets write a simple program that connects to the router, sends the username and password, close the connection.

import telnetlib

# Establish the connection
conn = telnetlib.Telnet('192.168.35.121')

# Read the output for the username request
output = conn.read_until('Username: ', 3)

# If 'Username: ' is found, send the username
if 'Username: ' in output:
    conn.write('cisco\n')

# Read the output for the password request
output = conn.read_until('Password: ', 3)

# If 'Password: ' is found, send the password
if 'Password: ' in output:
    conn.write('cisco\n')

# Read for hash prompt
output = conn.read_until('#', 3)

# Check for # in output
if '#' in output:
    conn.write('show ip interface brief\n')

# Read the output
output = conn.read_until('#', 3)

# Print the output
print output

# Close the connection
conn.close()