Day 27 - Getting Hands-On with Python & Network

This commit is contained in:
Michael Cade
2022-01-27 15:22:36 +00:00
parent 1677511e6e
commit 8ca6594031
28 changed files with 1293 additions and 6 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1,197 @@
**************************************************************************
* IOSv is strictly limited to use for evaluation, demonstration and IOS *
* education. IOSv is provided as-is and is not supported by Cisco's *
* Technical Advisory Center. Any use or disclosure, in whole or in part, *
* of the IOSv Software or Documentation to any third party for any *
* purposes is expressly prohibited except as otherwise authorized by *
* Cisco in writing. *
**************************************************************************
R1>enable
Password:
R1#term len 0
R1#sh run
Building configuration...
Current configuration : 3846 bytes
!
! Last configuration change at 09:18:04 UTC Thu Jan 27 2022
!
version 15.6
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname R1
!
boot-start-marker
boot-end-marker
!
!
enable password access123
!
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local none
!
!
!
!
!
aaa session-id unique
ethernet lmi ce
!
!
!
mmi polling-interval 60
no mmi auto-configure
no mmi pvc
mmi snmp-timeout 180
!
!
!
!
!
!
!
!
!
!
!
no ip domain lookup
ip domain name 90DaysOfDevOps.net
ip cef
no ipv6 cef
!
multilink bundle-name authenticated
!
!
!
!
username admin password 0 access123
!
redundancy
!
lldp run
!
!
!
!
!
!
!
!
!
!
!
!
!
!
interface GigabitEthernet0/0
ip address 10.10.88.110 255.255.255.0
duplex auto
speed auto
media-type rj45
!
interface GigabitEthernet0/1

View File

@ -0,0 +1,193 @@
**************************************************************************
* IOSv is strictly limited to use for evaluation, demonstration and IOS *
* education. IOSv is provided as-is and is not supported by Cisco's *
* Technical Advisory Center. Any use or disclosure, in whole or in part, *
* of the IOSv Software or Documentation to any third party for any *
* purposes is expressly prohibited except as otherwise authorized by *
* Cisco in writing. *
**************************************************************************
SW3>enable
Password:
SW3#term len 0
SW3#sh run
Building configuration...
Current configuration : 3939 bytes
!
! Last configuration change at 09:22:10 UTC Thu Jan 27 2022
!
version 15.2
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
service compress-config
!
hostname SW3
!
boot-start-marker
boot-end-marker
!
!
enable password access123
!
username admin password 0 access123
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local none
!
!
!
!
!
!
aaa session-id unique
!
!
!
!
!
vtp mode transparent
!
!
!
no ip domain-lookup
ip domain-name 90DaysOfDevOps.net
ip cef
no ipv6 cef
!
!
!
spanning-tree mode rapid-pvst
spanning-tree extend system-id
!
vlan internal allocation policy ascending
lldp run
!
!
!
!
!
!
!
!
!
!
!
!
!
!
interface GigabitEthernet0/1
media-type rj45
negotiation auto
!
interface GigabitEthernet0/2
media-type rj45
negotiation auto
!
interface GigabitEthernet0/3
media-type rj45
negotiation auto
!
interface GigabitEthernet0/0
no switchport
ip address dhcp

View File

@ -0,0 +1,194 @@
**************************************************************************
* IOSv is strictly limited to use for evaluation, demonstration and IOS *
* education. IOSv is provided as-is and is not supported by Cisco's *
* Technical Advisory Center. Any use or disclosure, in whole or in part, *
* of the IOSv Software or Documentation to any third party for any *
* purposes is expressly prohibited except as otherwise authorized by *
* Cisco in writing. *
**************************************************************************
SW1>enable
Password:
SW1#term len 0
SW1#sh run
Building configuration...
Current configuration : 3976 bytes
!
! Last configuration change at 14:04:42 UTC Thu Jan 27 2022
!
version 15.2
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
service compress-config
!
hostname SW1
!
boot-start-marker
boot-end-marker
!
!
enable password access123
!
username admin password 0 access123
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local none
!
!
!
!
!
!
aaa session-id unique
!
!
!
!
!
vtp mode transparent
!
!
!
no ip domain-lookup
ip domain-name 90DaysOfDevOps.net
ip cef
no ipv6 cef
!
!
!
spanning-tree mode rapid-pvst
spanning-tree extend system-id
!
vlan internal allocation policy ascending
lldp run
!
!
!
!
!
!
!
!
!
!
!
!
!
!
interface GigabitEthernet0/1
media-type rj45
negotiation auto
!
interface GigabitEthernet0/2
media-type rj45
negotiation auto
!
interface GigabitEthernet0/3
media-type rj45
negotiation auto
!
interface GigabitEthernet0/0
no switchport
ip address dhcp

View File

@ -0,0 +1,199 @@
**************************************************************************
* IOSv is strictly limited to use for evaluation, demonstration and IOS *
* education. IOSv is provided as-is and is not supported by Cisco's *
* Technical Advisory Center. Any use or disclosure, in whole or in part, *
* of the IOSv Software or Documentation to any third party for any *
* purposes is expressly prohibited except as otherwise authorized by *
* Cisco in writing. *
**************************************************************************
SW2>enable
Password:
SW2#term len 0
SW2#sh run
Building configuration...
Current configuration : 4140 bytes
!
! Last configuration change at 14:17:13 UTC Thu Jan 27 2022 by admin
!
version 15.2
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
service compress-config
!
hostname SW2
!
boot-start-marker
boot-end-marker
!
!
enable password access123
!
username admin password 0 access123
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local none
!
!
!
!
!
!
aaa session-id unique
!
!
!
!
!
vtp mode transparent
!
!
!
no ip domain-lookup
ip domain-name 90DaysOfDevOps.net
ip cef
no ipv6 cef
!
!
!
spanning-tree mode rapid-pvst
spanning-tree extend system-id
!
vlan internal allocation policy ascending
lldp run
!
!
!
!
!
!
!
!
!
!
!
!
!
!
interface GigabitEthernet0/1
switchport trunk allowed vlan 1,2
switchport trunk encapsulation dot1q
switchport mode trunk
media-type rj45
negotiation auto
!
interface GigabitEthernet0/2
switchport trunk allowed vlan 1,2
switchport trunk encapsulation dot1q
switchport mode trunk
media-type rj45
negotiation auto
!
interface GigabitEthernet0/3
media-type rj45
negotiation auto
!

View File

@ -0,0 +1,195 @@
**************************************************************************
* IOSv is strictly limited to use for evaluation, demonstration and IOS *
* education. IOSv is provided as-is and is not supported by Cisco's *
* Technical Advisory Center. Any use or disclosure, in whole or in part, *
* of the IOSv Software or Documentation to any third party for any *
* purposes is expressly prohibited except as otherwise authorized by *
* Cisco in writing. *
**************************************************************************
SW4>enable
Password:
SW4#term len 0
SW4#sh run
Building configuration...
Current configuration : 3982 bytes
!
! Last configuration change at 09:22:39 UTC Thu Jan 27 2022
!
version 15.2
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
service compress-config
!
hostname SW4
!
boot-start-marker
boot-end-marker
!
!
enable password access123
!
username admin password 0 access123
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local none
!
!
!
!
!
!
aaa session-id unique
!
!
!
!
!
vtp mode transparent
!
!
!
no ip domain-lookup
ip domain-name 90DaysOfDevOps.net
ip cef
no ipv6 cef
!
!
!
spanning-tree mode rapid-pvst
spanning-tree extend system-id
!
vlan internal allocation policy ascending
!
vlan 10,20,30,40,50,60,70,80,90,100,200
lldp run
!
!
!
!
!
!
!
!
!
!
!
!
!
!
interface GigabitEthernet0/1
media-type rj45
negotiation auto
!
interface GigabitEthernet0/2
media-type rj45
negotiation auto
!
interface GigabitEthernet0/3
media-type rj45
negotiation auto
!
interface GigabitEthernet0/0
no switchport

View File

@ -17,7 +17,7 @@ no ip domain-lookup
lldp run lldp run
ip domain-name PythonTraining.net ip domain-name 90DaysOfDevOps.net
ip ssh version 2 ip ssh version 2
ip scp server enable ip scp server enable
crypto key generate rsa general-keys modulus 1024 crypto key generate rsa general-keys modulus 1024

View File

@ -20,7 +20,7 @@ enable password access123
username admin password access123 username admin password access123
no ip domain-lookup no ip domain-lookup
ip domain-name PythonTraining.net ip domain-name 90DaysOfDevOps.net
ip ssh version 2 ip ssh version 2
ip scp server enable ip scp server enable
crypto key generate rsa general-keys modulus 1024 crypto key generate rsa general-keys modulus 1024

View File

@ -20,7 +20,7 @@ enable password access123
username admin password access123 username admin password access123
no ip domain-lookup no ip domain-lookup
ip domain-name PythonTraining.net ip domain-name 90DaysOfDevOps.net
ip ssh version 2 ip ssh version 2
ip scp server enable ip scp server enable
crypto key generate rsa general-keys modulus 1024 crypto key generate rsa general-keys modulus 1024

View File

@ -20,7 +20,7 @@ enable password access123
username admin password access123 username admin password access123
no ip domain-lookup no ip domain-lookup
ip domain-name PythonTraining.net ip domain-name 90DaysOfDevOps.net
ip ssh version 2 ip ssh version 2
ip scp server enable ip scp server enable
crypto key generate rsa general-keys modulus 1024 crypto key generate rsa general-keys modulus 1024

View File

@ -21,7 +21,7 @@ enable password access123
username admin password access123 username admin password access123
no ip domain-lookup no ip domain-lookup
ip domain-name PythonTraining.net ip domain-name 90DaysOfDevOps.net
ip ssh version 2 ip ssh version 2
ip scp server enable ip scp server enable
crypto key generate rsa general-keys modulus 1024 crypto key generate rsa general-keys modulus 1024

49
Days/Networking/backup.py Normal file
View File

@ -0,0 +1,49 @@
import sys
import time
import paramiko
import os
import cmd
import datetime
now = datetime.datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("Your backup has started at", dt_string)
tic = time.perf_counter()
#user = input("Enter username:")
#password = input("Enter Paswd:")
#enable_password = input("Enter enable pswd:")
user = "admin"
password = "access123"
enable_password = "access123"
port=22
f0 = open('backup.txt')
for ip in f0.readlines():
ip = ip.strip()
filename_prefix ='/Users/shambhu/Documents' + ip
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port, user, password, look_for_keys=False)
chan = ssh.invoke_shell()
time.sleep(2)
chan.send('enable\n')
chan.send(enable_password +'\n')
time.sleep(1)
chan.send('term len 0\n')
time.sleep(1)
chan.send('sh run\n')
time.sleep(20)
output = chan.recv(999999)
filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip,now.year,now.month,now.day,now.hour,now.minute,now.second)
f1 = open(filename, 'a')
f1.write(output.decode("utf-8") )
f1.close()
ssh.close()
f0.close()
toc = time.perf_counter()
print("Congratulations You Have Backed Up Your 90DaysOfDevOps Lab")
print(f"Your backup duration was {toc - tic:0.4f} seconds")
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("Your backup completed at", dt_string)

View File

@ -0,0 +1,5 @@
192.168.169.115
192.168.169.178
192.168.169.193
192.168.169.125
192.168.169.197

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
#password = getpass()
R1 = {
"device_type": "cisco_ios",
"host": "192.168.169.115",
"username": "admin",
"password": "access123",
}
SW1 = {
"device_type": "cisco_ios",
"host": "192.168.169.178",
"username": "admin",
"password": "access123",
}
SW2 = {
"device_type": "cisco_ios",
"host": "192.168.169.193",
"username": "admin",
"password": "access123",
}
SW3 = {
"device_type": "cisco_ios",
"host": "192.168.169.125",
"username": "admin",
"password": "access123",
}
SW4 = {
"device_type": "cisco_ios",
"host": "192.168.169.197",
"username": "admin",
"password": "access123",
}
command = "show ip int brief"
for device in (R1, SW1, SW2, SW3, SW4):
net_connect = ConnectHandler(**device)
print(net_connect.find_prompt())
print(net_connect.send_command(command))
net_connect.disconnect()

View File

@ -0,0 +1,39 @@
#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
#password = getpass()
SW1 = {
"device_type": "cisco_ios",
"host": "192.168.169.178",
"username": "admin",
"password": "access123",
}
SW2 = {
"device_type": "cisco_ios",
"host": "192.168.169.193",
"username": "admin",
"password": "access123",
}
SW3 = {
"device_type": "cisco_ios",
"host": "192.168.169.125",
"username": "admin",
"password": "access123",
}
SW4 = {
"device_type": "cisco_ios",
"host": "192.168.169.197",
"username": "admin",
"password": "access123",
}
command = "show int trunk"
for device in (SW1, SW2, SW3, SW4):
net_connect = ConnectHandler(**device)
print(net_connect.find_prompt())
print(net_connect.send_command(command))
net_connect.disconnect()

View File

@ -0,0 +1,19 @@
from netmiko import ConnectHandler
SW2 = {
"device_type": "cisco_ios",
"host": "192.168.169.193",
"username": "admin",
"password": "access123",
"secret": "access123",
}
core_sw_config = ["int range gig0/1 - 2", "switchport trunk encapsulation dot1q",
"switchport mode trunk", "switchport trunk allowed vlan 1,2"]
print("########## Connecting to Device {0} ############".format(SW2))
net_connect = ConnectHandler(**SW2)
net_connect.enable()
print("***** Sending Configuration to Device *****")
net_connect.send_config_set(core_sw_config)

View File

@ -0,0 +1,22 @@
#!/usr/bin/python
import paramiko
import time
Channel = paramiko.SSHClient()
Channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Channel.connect(hostname="192.168.169.115", username='admin', password='access123', look_for_keys=False, allow_agent=False)
shell = Channel.invoke_shell() # This will set interactive shell
shell.send("enable\n")
shell.send("access123\n")
shell.send("terminal length 0\n")
shell.send("show ip int b\n")
shell.send("show arp \n")
time.sleep(2)
print(shell.recv(5000))
# This will receive everything from the buffer, if you need to receive specifc output, the you should execute the command
# and immediately receive the output before executing the 2nd command, Also you should sleep a little
Channel.close()

View File

@ -0,0 +1,129 @@
## Getting Hands-On with Python & Network
In this final section of Networking fundamentals, we are going to cover some automation tasks and tools with our lab environment created on [Day 26](day26.md)
We will be using an SSH tunnel to connect to our devices from our client vs telnet. The SSH tunnel created between client and device is encrypted. We also covered SSH in the Linux section on [Day 18](day18.md)
## Access our virtual emulated environment
For us to interact with our switches we either need a workstation inside the EVE-NG network and you can deploy a Linux box there with Python installed to perform your automation ([Resource for setting up Linux inside EVE-NG](https://www.youtube.com/watch?v=3Qstk3zngrY)) or you can do something like me and define a cloud for access from your workstation.
![](Images/Day27_Networking3.png)
To do this, we have right-clicked on our canvas and we have selected network and then selected "Management(Cloud0)" this will bridge out to our home network.
![](Images/Day27_Networking4.png)
However, we do not have anything inside this network so we need to add connections from the new network to each of our devices. (My networking knowledge needs more attention and I feel that you could just do this next step to the top router and then have connectivity to the rest of the network through this one cable?)
I have then logged on to each of our devices and I have run through the following commands for the interfaces applicable for where the cloud comes in.
```
enable
config t
int gi0/0
ip add dhcp
no sh
exit
exit
sh ip int br
```
The final step gives us the DHCP address from our home network. My device network list is as follows:
| Node | IP Address | Home Network IP |
| ----------- | ----------- | ----------- |
| Router | 10.10.88.110| 192.168.169.115 |
| Switch1 | 10.10.88.111| 192.168.169.178 |
| Switch2 | 10.10.88.112| 192.168.169.193 |
| Switch3 | 10.10.88.113| 192.168.169.125 |
| Switch4 | 10.10.88.114| 192.168.169.197 |
### SSH to a network device
With the above in place, we can now connect to our devices on our home network using our workstation. I am using Putty but also have access to other terminals such as git bash that give me the ability to SSH to our devices.
Below you can see we have an SSH connection to our router device. (R1)
![](Images/Day27_Networking5.png)
### Using Python to gather information from our devices
The first example of how we can leverage Python is to gather information from all of our devices and in particular, I want to be able to connect to each one and run a simple command to provide me with interface configuration and settings. I have stored this script here [netmiko_con_multi.py](Networking/netmiko_con_multi.py)
Now when I run this I can see each port configuration over all of my devices.
![](Images/Day27_Networking6.png)
This could be handy if you have a lot of different devices, create this one script so that you can centrally control and understand quickly all of the configurations in one place.
### Using Python to configure our devices
The above is useful but what about using Python to configure our devices, in our scenario we have a trunked port between `SW1` and `SW2` again imagine if this was to be done across many of the same switches we want to automate that and not have to manually connect to each switch to make the configuration change.
We can use [netmiko_sendchange.py](Networking/netmiko_sendchange.py) to achieve this. This will connect over SSH and perform that change on our `SW1` which will also change to `SW2`.
![](Images/Day27_Networking7.png)
Now for those that look at the code, you will see the message appears and tells us `sending configuration to device` but there is no confirmation that this has happened to we could add additional code to our script to perform that check and validation on our switch or we could modify our script before to show us this. [netmiko_con_multi_vlan.py](Networking/netmiko_con_multi_vlan.py)
![](Images/Day27_Networking8.png)
### backing up your device configurations
Another use case would be to capture our network configurations and make sure we have those backed up, but again we don't want to be connecting to every device we have on our network so we can also automate this using [backup.py](Networking/backup.py). You will also need to populate the [backup.txt](Networking/backup.txt) with the IP addresses you want to backup.
Run your script and you should see something like the below.
![](Images/Day27_Networking9.png)
That could be me just writing a simple print script in python so I should show you the backup files as well.
![](Images/Day27_Networking10.png)
### Paramiko
A widely used Python module for SSH. You can find out more at the official GitHub link [here](https://github.com/paramiko/paramiko)
We can install this module using the `pip install paramiko` command.
![](Images/Day27_Networking1.png)
We can verify the installation by entering the Python shell and importing the paramiko module.
![](Images/Day27_Networking2.png)
### Netmiko
The netmiko module targets network devices specifically whereas paramiko is a broader tool for handling SSH connections overall.
Netmiko which we have used above alongside paramiko can be installed using `pip install netmiko`
Netmiko supports many network vendors and devices, you can find a list of supported devices on the [GitHub Page](https://github.com/ktbyers/netmiko#supports)
### Other modules
It is also worth mentioning a few other modules that we have not had the chance to look at but they give a lot more functionality when it comes to network automation.
`netaddr` is used for working with and manipulating IP addresses, again the installation is simple with `pip install netaddr`
you might find yourself wanting to store a lot of your switch configuration in an excel spreadsheet, the `xlrd` will allow your scripts to read the excel workbook and convert rows and columns into a matrix. `pip install xlrd` to get the module installed.
Some more use cases where network automation can be used that I have not had the chance to look into can be found [here](https://github.com/ktbyers/pynet/tree/master/presentations/dfwcug/examples)
I think this wraps up our Networking section of the #90DaysOfDevOps, Networking is one area that I have not touched for a while really and there is so much more to cover but I am hoping between my notes and the resources shared throughout it is helpful for some.
## Resources
- [Free Course: Introduction to EVE-NG](https://www.youtube.com/watch?v=g6B0f_E0NMg)
- [EVE-NG - Creating your first lab](https://www.youtube.com/watch?v=9dPWARirtK8)
- [3 Necessary Skills for Network Automation](https://www.youtube.com/watch?v=KhiJ7Fu9kKA&list=WL&index=122&t=89s)
- [Computer Networking full course](https://www.youtube.com/watch?v=IPvYjXCsTg8)
- [Practical Networking](http://www.practicalnetworking.net/)
- [Python Network Automation](https://www.youtube.com/watch?v=xKPzLplPECU&list=WL&index=126)
Most of the examples I am using here as I am not a Network Engineer have come from this extensive book which is not free but I am using some of the scenarios to help understand Network Automation.
- [Hands-On Enterprise Automation with Python (Book)](https://www.packtpub.com/product/hands-on-enterprise-automation-with-python/9781788998512)
See you on [Day 28](day28.md) where will start looking into cloud computing and get a good grasp and foundational knowledge of the topic and what is available.

View File

@ -48,7 +48,7 @@ This will not cover all things DevOps but it will cover the areas that I feel wi
- [✔️] 🌐 24 > [Network Automation](Days/day24.md) - [✔️] 🌐 24 > [Network Automation](Days/day24.md)
- [✔️] 🌐 25 > [Python for Network Automation](Days/day25.md) - [✔️] 🌐 25 > [Python for Network Automation](Days/day25.md)
- [✔️] 🌐 26 > [Building our Lab](Days/day26.md) - [✔️] 🌐 26 > [Building our Lab](Days/day26.md)
- [🚧] 🌐 27 > [](Days/day27.md) - [🚧] 🌐 27 > [Getting Hands-On with Python & Network](Days/day27.md)
### Stick to one Cloud Provider ### Stick to one Cloud Provider