Python SDN 101: Telnet Device Control

We began learning Python in the previous several articles. Why would a network engineer choose to acquire knowledge of this programming language? Our profession is developing and adapting to new technology; so, we must also adapt. Today's network engineer is not the same as he or she was 10 years ago. In 10 years' hence, SDN will undoubtedly disrupt our jobs; we can either surf the wave or perish under it. With this tutorial, we'll begin a Python SDN project to get you started with SDN.

Read More: SSH Tutorial for Python and how to connect to Cisco devices

SDN is coming about Python SDN 101: Telnet Device Control

For those unfamiliar with the term, SDN stands for Software-Defined Networking. With this technology, you get a collection of gadgets that are designed to make network engineers' lives easier. Forget about setting VLANs and ports; the program will take care of everything for you. It is not a basic centralized administration console; it has intelligence. You do not instruct an SDN platform to generate VLANs; you tell it to deploy a new site. It will manage the creation of new VLANs, the addition of routes, and the configuration of ports. As a result, I just came across this phrase on LinkedIn. To the CCIE, Python is going to replace you. While this is not entirely accurate, it demonstrates the potential power of SDN. It may lower the amount of jobs required of a network engineer, hence decreasing the number of network engineers required. If you do not learn how to deal with SDN, you can be certain that SDN will.

Introducing our Python SDN Project

The goal

Our objective with our Python SDN project is to provide tools capable of executing code on network devices. Our application will communicate with them, get information from them, and modify their settings. How you utilize it and what you do with it are entirely up to you. Through this and subsequent articles, we will develop something that is capable of performing the following tasks. Telnet and SSH are used to connect devices. Send configuration instructions and check their execution Execute troubleshooting commands and monitor their results Utilize SNMP to get device status and to make configuration changes. Syslog messages are received These are our system's weaponry. By the time our Python SDN project is complete, it will be able to fire with them. Which direction to go is entirely up to you. However, throughout these articles, we will put you in the proper route.

Everything is on GitHub

GitHub is the leading platform for hosting source code for open-source projects. We have been developing this project step-by-step, and everything is documented on GitHub. Here you can get the code and browse to changes over time. Just follow our sdncore project.

The anatomy of our Python SDN Project

Who starts in the right way is already halfway there. Thus, we need to create a convenient folder structure for our project. We can achieve this structure by adopting the best practices. Here is what the root of our project looks like.
This is how we scaffold the project for Python SDN, before starting to write the Telnet driver
Our project root.
Here is an important tip. Since we are going to work with a lot of files and folders, and even some complex scripts, we simply cannot rely on Notepad or even Notepad++. We need a better solution to write our code, and luckily we have one. You can download for free the community edition of PyCharm, it has everything you need to work with python.

Read More: SSH Tutorial for Python and how to connect to Cisco devices

Connecting to devices in Telnet with Python

SDN entails network management, and what kind of network would exist without network devices? We must first establish contact with them. Today, we're going to look at how Telnet makes this feasible. Telnet is a well-known protocol for non-encrypted terminal emulation. In other words, it enables you to interact with a target device just via text — and without employing any kind of encryption. Even though this is not the optimal solution, some networks may use it. Additionally, it is straightforward to comprehend and apply. It must be included in our project! Our emulation module for terminals We can start by creating a vty module in our sdncore folder. As always, we create an empty __init__.py file, and we start by creating a sub-module called drivers. Here we add a new __init__.py file, a driver.py and a telnet.py. Why all of that? With our vty module, we want to connect to a device regardless of the protocol – Telnet or SSH. Later on in this project, we will create a class that handles that connection. However, we need to implement the drivers to do that with Telnet and SSH. Today, we start by implementing the Telnet driver. The cherry on the cake is the driver.py files, it defines how a driver should be.

The driver

The first thing in our Python SDN project is the driver file. We are going to model our telnet driver according to how a driver should be, thus we need to define it first. The driver will handle the connection to the device, thus it must implement these features:
  • Open the connection to an IP and port, optionally with authentication
  • Send text
  • Receive text
  • Close the connection
Thus, our driver.py file is pretty simple.
class Driver:
def __init__(self, target, port, username, password):
raise NotImplementedError()
def open(self):
raise NotImplementedError()
def send_text(self, text):
raise NotImplementedError()
def read_until(self, text, timeout):
raise NotImplementedError()
def read_eof(self):
raise NotImplementedError()
def expect(self, expr_list, timeout):
raise NotImplementedError
def close(self):
raise NotImplementedError()
Since we are explaining the script step-by-step, we are omitting the docstrings. If you want to read them, please browse our GitHub Python SDN project. However, here is a quick explanation. By instantiating the driver, you prepare it for the connection giving all it needs to connect. With open(), you effectively start the connection. read_until() will read all text until a given string is found, while read_eof() will read as long as there is something to read (until end of file). Instead, expect() sits and wait until a given text (or list of text) appears.

A custom Error class

Our telnet script may rise some errors, while our SSH script may raise some others. We need to standardize this kind of error so that sdncore can handle them. For that, we add the DriverError class in the driver.py file.
class DriverError(Exception):
pass

The Telnet connection

Now it is time to define our telnet.py file. To connect to a device in telnet, we are going to use a standard python library: telnetlib.  Using it, we need to write our own driver. Nothing too complex, the Telnet object from Telnet library has some built-in methods that resemble the ones we just prepared. We are going to require a few modules, then take a look at our constructor.
from telnetlib import Telnet as TelnetClient
from .driver import Driver, DriverError
import socket
class TelnetDriver(Driver):
def __init__(self, target, username='', password='', port=23,
username_finder='username: ', password_finder='password: '):
self.target = target
self.username = username
self.password = password
self.port = port
self.username_finder = username_finder
self.password_finder = password_finder
self._client = TelnetClient()
As you can see, we use the parameters to instantiate our TelentClient. The fancy part is the username and password finders. We are going to use these parameters so that our client knows when it should send username and password. Here is the open() method that uses them.
def open(self):
self._client.open(self.target, self.port)
if self.username != '' or self.password != '':
self.expect(self.username_finder)
self.send_text(self.username)
self.expect(self.password_finder)
self.send_text(self.password

Tuning the other functions

We also need to redefine our other functions to rely on the TelnetClient. While doing so, we also need to convert any error that may arise into a DriverError.
def send_text(self, text):
try:
self._client.write(text.encode('ascii'))
return True
except socket.error:
raise DriverError("Connection closed while sending text")
def read_until(self, text, timeout=2):
try:
return self._client.read_until(text.encode('ascii'), timeout)
except EOFError:
raise DriverError("Connection closed without receiving EOF")
def read_eof(self, timeout=2):
return self._client.read_all()
def expect(self, expr_list, timeout=2):
try:
return self._client.expect(expr_list, timeout)
except EOFError:
raise DriverError("EOF was reached without finding the expected text")
def close(self):
self._client.close()
Here you need to pay attention to the encoding. We are encoding the text in ASCII, as virtual terminals use that.

Testing our first Python SDN component

Now that we have our driver, we can test it. Right now we haven’t developed the vty module, so we need to try the driver itself. To do that, we need a device that will accept Telnet connections. Why not a GNS3 device? If you need help in setting it up, read our GNS3 Guide. If you don’t have the time for that, don’t worry. You can telnet on any website on port 80, like we are doing in this example. Then, we can write a script that looks like this.
from sdncore.vty.drivers.telnet import TelnetDriver
td = TelnetDriver('ictshore.com', port=80)
td.open()
td.send_text('GET /\n')
print(td.read_eof())
td.close()
This will print to screen the HTML code we have on ICTShore.com. Extremely important, never forget about \n. This means hitting enter in the terminal, telling the device that we finished writing a command. Without that, the device will wait for some input but since no more is coming, it will eventually time out. Python SDN 101: Telnet Device Control

Read More: SSH Tutorial for Python and how to connect to Cisco devices

Wrapping it Up

Our telnet connection script is now functional. It may be used to establish a Telnet connection to a device and execute some simple instructions. However, we lack the intelligence necessary to decouple our connection from the underlying protocol - SSH or Telnet. Additionally, we lack a higher degree of intelligence in which the software reads and intelligently comprehends what the gadget is communicating. Not to worry; we will address it. For now, try your new driver and let me know what you think of it. To dive deeper, you can check the official telnetlib documentation and our GitHub sdncore project, or better yet its telnet-driver branch. If Our Method Resolve Your Problem Consider To Share This Post, You can help more People Facing This Problem and also, if you want, you can Subscribe at Our Youtube Channel as Well! So, what do you think of SDN? Do you like the idea of having an automated software making the hard work on your behalf? Let me know what you think in the comments! https://www.techguruhub.net/python-sdn-telnet-device-control/?feed_id=121977&_unique_id=642d9ff149192

Comments

Popular posts from this blog

Need an Hosting for Wordpress? The Best WordPress Hosting Sites Providers in 2022

Need an Hosting for Wordpress? The Best WordPress Hosting Sites Providers in 2022

Getting Started with Open Shortest Path First (OSPF)