Skip to content

Commit

Permalink
Functional update
Browse files Browse the repository at this point in the history
  • Loading branch information
labeveryday committed Mar 6, 2021
1 parent b003b39 commit 0ea026a
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 53 deletions.
69 changes: 45 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# devicebanner

This is a script that leverages the [netmiko library](https://pyneng.readthedocs.io/en/latest/book/18_ssh_telnet/netmiko.html) to update the banner motd on a network device. Then output the results to `results.csv`. Use this script to learn the basics of python.
This is a script that leverages the [netmiko library](https://pyneng.readthedocs.io/en/latest/book/18_ssh_telnet/netmiko.html) to update the banner motd on a network device. Once the device update has been attempted the update status is then output to the `results.csv` file. Use this script to learn the basics of python.

> NOTE: This code will run on Linux, MAC and Windows
## Download the Code

To get started: Download the code and cd the `devicebanner` directory
To get started: Download the code and cd to the `devicebanner` directory

```bash
git clone https://github.com/labeveryday/devicebanner
Expand All @@ -15,9 +15,9 @@ cd device banner

## Python Virtual Environment

When executing python code or installing python applications you should get into the practice of creating and managing python virtual environments.
This will allow you to run different versions of a python library while avoiding version conflicts. My preferred tool for python virtual environments is `venv`
There are many other tools available. Remember to explore and find what works best for you.
When executing python code or installing python packages you should get into the practice of creating and managing python virtual environments.
This will allow you to run different versions of a python library while avoiding software version conflicts. My preferred tool for python virtual environments is [venv](https://docs.python.org/3/library/venv.html)
There are many other tools available. Remember to explore and find the one that works best for you.

**On Linux or Mac**

Expand All @@ -39,53 +39,74 @@ A couple of things to note:

1. Modify the `ip_address_file.txt` file to update the list of ip addresses for the devices that you want to update.

2. Modify the device credentials in the `credentials.py` file. These are the creds that will be used to log into your network devices.
2. Modify the device credentials in the `credentials.py` file. In this file are the creds that will be used to log into your network devices.

3. In the `banners/` directory is where you store the banners that will be used to update your devices. If you want to use a different banner you will need to do two things.
3. In the `banners/` directory is where we store the banners that will be used to update your devices. If you want to use a different banner you will need to do two things.

- First create a new text banner file in the banners directory with the command line command `banner motd ^ENTER CODE HERE`
- ***FIRST*** create a new text banner file in the banners directory with the command line argument `banner motd ^ENTER CODE INSIDE HERE^`

![banner](https://github.com/labeveryday/Notes/blob/main/images/banner.png)

- Second you will need to enter the name of the file as an argument on line 109 of `main.py`
- ***SECOND*** you will need to enter the name of the file as an argument on line 109 of `main.py`

>NOTE: There is no need to enter the file path. Just the name of the file!
![banner_arg](https://github.com/labeveryday/Notes/blob/main/images/banner_arg.png)

## Example: Script in action

Now that you have everything installed and updated you can execute the script

**Failed Attempt**
Now that you have everything installed and updated you can execute the script.

```bash
(venv) duan@ubuntu devicebanner$ python main.py
Attempting to log into 192.168.23.142.....
✅ Banner was successfully added to SW2-IOSv on 03-06-2021 10:32

Attempting to log into 192.168.23.143.....
✅ Banner was successfully added to SW3-IOSv on 03-06-2021 10:32

Attempting to log into 192.168.23.144.....
✅ Banner was successfully added to SW1-IOSv on 03-06-2021 10:32

Attempting to log into 192.168.23.145.....
******************************
TCP connection to device failed.
❌ SSH timeout attempt to 192.168.23.145 on 03-06-2021 10:32

Attempting to log into 192.168.23.148.....
✅ Banner was successfully added to R1-iosv on 03-06-2021 10:32

Common causes of this problem are:
1. Incorrect hostname or IP address.
2. Wrong TCP port.
3. Intermediate firewall blocking access.
Attempting to log into 192.168.23.149.....
❌ SSH timeout attempt to 192.168.23.149 on 03-06-2021 10:32

Device settings: cisco_ios 192.168.23.145:22
Attempting to log into 192.168.23.150.....
❌ SSH timeout attempt to 192.168.23.150 on 03-06-2021 10:32

Attempting to log into 192.168.23.151.....
❌ SSH timeout attempt to 192.168.23.151 on 03-06-2021 10:32

******************************
Attempting to log into 192.168.23.153.....
❌ SSH timeout attempt to 192.168.23.153 on 03-06-2021 10:32

+-------------------+---------+
| Number_of_Devices | Status |
+-------------------+---------+
| 4 | failed |
| 0 | success |
| 5 | failed |
| 4 | success |
+-------------------+---------+
Total Time Taken: 20.03 seconds
Total Time Taken: 37.61 seconds

```

## TO BE CONTINUED....
Once the script has been executed the results will begin to print to the screen. Once complete you can now verify the results in the `results.csv` file and on the network device.

**Banner results.csv**

![banner results](https://github.com/labeveryday/Notes/blob/main/images/banner_results.png)

**Banner verification on router**

![Device banner results](https://github.com/labeveryday/Notes/blob/main/images/banner_example.png)

This script is still in progress. The next phase will be to added device banner verification to ensure that the desired banner state has been implemented. `STAY TUNED`

### About me

Expand Down
4 changes: 4 additions & 0 deletions credentials.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Device credentials file
# Modify device credentials and device type here
# For more supported device types:
# https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py
USERNAME = 'duan'
PASSWORD = 'cisco'
DEVICE_TYPE = 'cisco_ios'
7 changes: 6 additions & 1 deletion ip_address_file.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
192.168.23.142
192.168.23.143
192.168.23.144
192.168.23.145
192.168.23.145
192.168.23.148
192.168.23.149
192.168.23.150
192.168.23.151
192.168.23.153
56 changes: 33 additions & 23 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
import time
import datetime
import csv
import contextlib
import io
# Import variables from credentials.py
from credentials import *
from pathlib import Path
from netmiko import ConnectHandler, ssh_exception
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
from paramiko.ssh_exception import SSHException
from tabulate import tabulate


Expand All @@ -26,33 +28,34 @@ def main(banner_name='cisco_devnet.txt'):
connect_failed = []
connect_successful = []
banner_file = banner_path / banner_name
banner = openFile(banner_file)
ip_list = openFile(ip_file).splitlines()
header = ['device_ip', 'status', 'date/time']
banner = openfile(banner_file)
ip_list = openfile(ip_file).splitlines()
header = ["device_ip", "status", "reason", "date/time"]
with open(results, 'wt') as file:
writer = csv.writer(file)
writer.writerow(i for i in header)
for ip in ip_list:
print(f"Attempting to log into {ip}.....")
try:
net_connect = connect(ip)
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
print("*" * 30)
print(f"{e}")
print("*" * 30 + "\n")
writer.writerow((ip,"failed",get_date()))
connect_failed.append(ip)
continue
send_banner(banner, net_connect)
save(net_connect)
hostname = get_device_info(net_connect)['hostname']
writer.writerow((ip, "success", get_date()))
connect_successful.append(ip)
print(f"Banner was successfully added to {hostname} on {get_date()}\n")
# This is to redirect stderr if netmiko can't connect
with contextlib.redirect_stderr(io.StringIO()):
try:
net_connect = connect(ip)
send_banner(banner, net_connect)
save(net_connect)
hostname = get_device_info(net_connect)['hostname']
writer.writerow((ip, "success", None, get_date()))
connect_successful.append(ip)
print(f"✅ Banner was successfully added to {hostname} on {get_date()}\n")
except (ssh_exception.NetMikoTimeoutException, ssh_exception.NetMikoAuthenticationException,
SSHException) as e:
print(f"❌ SSH timeout attempt to {ip} on {get_date()}\n")
writer.writerow((ip,"failed","ssh timeout", get_date()))
connect_failed.append(ip)
continue
print(tabulate([[len(connect_failed), "failed"], [len(connect_successful), "success"]],
headers=["Number_of_Devices", "Status"], tablefmt="pretty"))

def openFile(filename):
def openfile(filename):
"""
OPEN a file, read and return the data
Args:
Expand Down Expand Up @@ -83,7 +86,8 @@ def connect(ip, username=USERNAME, password=PASSWORD, device_type=DEVICE_TYPE):
return: netmiko ConnectHandler object
rtype: class (object)
"""
return ConnectHandler(ip=ip, device_type=device_type, username=username, password=password)
return ConnectHandler(ip=ip, device_type=device_type,
username=username, password=password, banner_timeout=5)

def get_device_info(net_connect):
"""
Expand All @@ -107,11 +111,17 @@ def send_banner(banner, net_connect):
net_connect.send_config_set(banner, cmd_verify=False)

def save(net_connect):

"""
POST copy running config to startup config
Args:
net_connect (object): Netmiko ConnectHandler object
return: None
rtype: None
"""
net_connect.send_command("wri mem")


if __name__ == "__main__":
starttime = time.time()
main() # <--- Pass a new banner file name here
print(f"Total Time Taken: {str(round(time.time() - starttime, 2))} seconds")
print(f"\nTotal Time Taken: {str(round(time.time() - starttime, 2))} seconds\n")
15 changes: 10 additions & 5 deletions results.csv
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
device_ip,status,date/time
192.168.23.142,failed,03-05-2021 19:09
192.168.23.143,failed,03-05-2021 19:09
192.168.23.144,failed,03-05-2021 19:09
192.168.23.145,failed,03-05-2021 19:10
device_ip,status,reason,date/time
192.168.23.142,success,,03-06-2021 10:42
192.168.23.143,success,,03-06-2021 10:42
192.168.23.144,success,,03-06-2021 10:42
192.168.23.145,failed,ssh timeout,03-06-2021 10:42
192.168.23.148,success,,03-06-2021 10:43
192.168.23.149,failed,ssh timeout,03-06-2021 10:43
192.168.23.150,failed,ssh timeout,03-06-2021 10:43
192.168.23.151,failed,ssh timeout,03-06-2021 10:43
192.168.23.153,failed,ssh timeout,03-06-2021 10:43

0 comments on commit 0ea026a

Please sign in to comment.