You are on page 1of 12

Download PNETLab Platform

PNETLAB Store
PNETLab.com

USE PYTHON CLASS AND FUNCTION TO LOG ON ALL


NETWORK DEVIECS TO GET DATA
Lab Topology:

I. Requirement
You are asked to use :
1. Using Class and Function to write a small python program to Log in Many Devices of
PNETlabs and send commands
The key for this lab are : You know how to process in a file to separate routers/devices into a
List. In addition, you will know how to write a Class ( check theory in google) and cooperate
with Function to complete your problem.
This program can run smoothly , you should use wireshark to capture packets to have a
deeper look.

II. Prerequisite
When you guys load the lab to your PNETlab, it will get all things of this lab except
Ubuntu_server docker. Therefore, you should install by yourself an Ubuntu_server docker and
connect to R2. Now I will show you how to do.

1
Download PNETLab Platform
PNETLAB Store
PNETLab.com

Step 1. Go to Device item of PNETlab site to get Ubuntu_server docker

Step 2. Read the guide to know how to do, or follow my method below.
Step 2.1 After you get Device, then go back to running lab on PNETlab box. Click “Add an
Object” , then Add new Node, then you choose the docker.io. After choosing that box, please
input information follow this picture

2
Download PNETLab Platform
PNETLAB Store
PNETLab.com

Step 2.2 Then you go to Start up configure section. Insert one command line: dhclient eth1
Then save it, enable it. Follow the picture blow.

3
Download PNETLab Platform
PNETLAB Store
PNETLab.com

Step 2.3 Now you have Ubunto_server docker, it is time to connect it to Cloud_NAT

4
Download PNETLab Platform
PNETLAB Store
PNETLab.com

All things related to Ubuntu_server docker are okay. Just click to that device and telnet . Then
just enjoy your Ubuntu in PNETlab now.

Now is the time to check and make Python Environment on Ubuntu. By default, Python3 are
built in your Ubuntu. But to make it work well we should make some check and update or
making the Virtual Environment.
Step 3. Check python version. Make sure it has suitable version. Version 3 is new version of
Python. // Click and telnet to your Ubunto , sodu -i with pass : admin to go to admin level.

admin@Ubuntu_server:~$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

Step 4. Create the virtual environment


sudo apt-get install python3-venv
sudo apt-get install python3-venv
[sudo] password for admin:
Reading package lists... Done
Building dependency tree
Reading state information... Done
// If this command is not Done with this output “E: Unable to fetch some archives, maybe run
apt-get update or try with --fix-missing?”. Please use this command to fix it
apt-get update --fix-missing

Step 5. Create a Directory for Python that it is easy to control python files
mkdir python_on_PNETlab
cd python_on_PNETlab
python3 -m venv env

5
Download PNETLab Platform
PNETLAB Store
PNETLab.com

If problem happen here please use this command again: sudo apt-get install python3-venv
Then execute command again, make sure it is okay now : python3 -m venv env

III. Solution for the lab:


If you don’t familiar with Telnet in Python please practice this lab first : Link Download lab:
https://user.pnetlab.com/store/labs/detail?id=15970569829967

If you already know how to telnet by Python please check the solution for those requirements

1. Create a file name: PNETlabdevices with info as below : (This in information to telnet to
R1, R2, R3 in PNETlab lab. We expect to log in R1 and R2, R3 we make a wrong
configure to test the telnet failure)
R1,ios,10.0.137.85,cisco,cisco
R2,ios-xr,10.0.137.221,cisco,cisco
R3,ios,10.0.137.177,cisco,cisco
base-01,unknown,10.0.137.177,unknown,unknown

2. Nano a python file by any name you want, I choose the name : Class_Function_Python
3. When you run program you should use Wireshark to capture packets on Interface of
Routers too. You can do in R1 to see what the process of telnet and getting data by
python.
4. Coding in that file.
=====
import pexpect

# ---- Class to hold information about a generic network device --------


class NetworkDevice():

def __init__(self, name, ip, user='cisco', pw='cisco'):


6
Download PNETLab Platform
PNETLAB Store
PNETLab.com

self.name = name
self.ip_address = ip
self.username = user
self.password = pw

self.interfaces = ''

def connect(self):
self.session = None

def get_interfaces(self):
self.interfaces = '--- Base Device, does not know how to get interfaces ---'

# ---- Class to hold information about an IOS-XE network device --------


class NetworkDeviceIOS(NetworkDevice):

# ---- Initialize --------------------------------------------------


def __init__(self, name, ip, user='cisco', pw='cisco'):
NetworkDevice.__init__(self, name, ip, user, pw)

# ---- Connect to device -------------------------------------------


def connect(self):

print('--- connecting IOS: telnet ' + self.ip_address)

self.session = pexpect.spawn('telnet ' + self.ip_address, timeout=20)

7
Download PNETLab Platform
PNETLAB Store
PNETLab.com

self.session.sendline('\r\n')
result = self.session.expect(['Username:', pexpect.TIMEOUT])
self.session.sendline(self.username)

# Check for failure


if result != 0:
print('--- Timeout or unexpected reply from device')
return None

result = self.session.expect(['Password:', pexpect.TIMEOUT])


# Check for failure
if result != 0:
print('--- Timeout or unexpected reply from device')
return None

# Successfully got password prompt, logging in with password


self.session.sendline(self.password)
self.session.expect('>')

# ---- Get interfaces from device ----------------------------------


def get_interfaces(self):

self.session.sendline('terminal length 0')


result = self.session.expect('>')
self.session.sendline('show interface')
result = self.session.expect('>')

8
Download PNETLab Platform
PNETLAB Store
PNETLab.com

self.interfaces = self.session.before

# ---- Class to hold information about an IOS-XR network device --------


class NetworkDeviceXR(NetworkDevice):

# ---- Initialize --------------------------------------------------


def __init__(self, name, ip, user='cisco', pw='cisco'):
NetworkDevice.__init__(self, name, ip, user, pw)

# ---- Connect to device -------------------------------------------


def connect(self):
print('--- connecting XR: ssh ' + self.username + '@' + self.ip_address)

# ---- Get interfaces from device ----------------------------------


def get_interfaces(self):
self.interfaces = '--- XR Device interface info ---'

# ======================================================================
def read_devices_info(devices_file):
devices_list = []

file = open(devices_file, 'r')


for line in file:

9
Download PNETLab Platform
PNETLAB Store
PNETLab.com

device_info = line.strip().split(',')

# Create a device object with this data


if device_info[1] == 'ios':

device = NetworkDeviceIOS(device_info[0], device_info[2],


device_info[3], device_info[4])

elif device_info[1] == 'ios-xr':

device = NetworkDeviceXR(device_info[0], device_info[2],


device_info[3], device_info[4])

else:
device = NetworkDevice(device_info[0], device_info[2],
device_info[3], device_info[4])

devices_list.append(device)

return devices_list

# ====================================================================
def print_device_info(device):
print('-------------------------------------------------------')
print(' Device Name: ', device.name)
print(' Device IP: ', device.ip_address)

10
Download PNETLab Platform
PNETLAB Store
PNETLab.com

print(' Device username: ', device.username, end=' ')


print(' Device password: ', device.password)

print('')
print(' Interfaces')
print('')

print(device.interfaces)
print('-------------------------------------------------------\n\n')

# ====================================================================
# Main program: connect to device, show interface, display

devices_list = read_devices_info('PNETlabdevices')

for device in devices_list:


print('==== Device ======================================================')

session = device.connect() # Connect to device

device.get_interfaces() # Get interface info for this device


print_device_info(device) # Print interface info for this device

=====
When you run python3 Function_Python if you meet the fault below, you should install
module pexpect

11
Download PNETLab Platform
PNETLAB Store
PNETLab.com

root@Ubuntu_server:~/python_on_PNETlab# python3 Class_Function_Python


Traceback (most recent call last):
File "Python_Expression", line 1, in <module>
import pexpect
ModuleNotFoundError: No module named 'pexpect'
root@Ubuntu_server:~/python_on_PNETlab# pip3 install pexpect
After that you can run Python again.

12

You might also like