forked from AlexMunoz905/Python-Cisco-Backup
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ni_run_cisco.py
60 lines (55 loc) · 2.24 KB
/
ni_run_cisco.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# All pre-installed besides Netmiko.
from csv import reader
from datetime import date, datetime
from netmiko import ConnectHandler
from ping3 import ping, verbose_ping
import getpass
import os
#import sys
#sys.tracebacklimit = 0
# Checks if the folder exists, if not, it creates it.
if not os.path.exists('backup-config'):
os.makedirs('backup-config')
# Current time and formats it to the North American time of Month, Day, and Year.
now = datetime.now()
dt_string = now.strftime("%m-%d-%Y_%H-%M")
# Gives us the information we need to connect.
def get_saved_config(host, username, password, enable_secret):
cisco_ios = {
'device_type': 'cisco_ios',
'host': host,
'username': username,
'password': password,
'secret': enable_secret,
}
# Creates the connection to the device.
net_connect = ConnectHandler(**cisco_ios)
net_connect.enable()
# Gets the running configuration.
output = net_connect.send_command("show run")
# Gets and splits the hostname for the output file name.
hostname = net_connect.send_command("show ver | i uptime")
hostname = hostname.split()
hostname = hostname[0]
# Creates the file name, which is the hostname, and the date and time.
fileName = hostname + "_" + dt_string
# Creates the text file in the backup-config folder with the special name, and writes to it.
backupFile = open("backup-config/" + fileName + ".txt", "w+")
backupFile.write(output)
print("Outputted to " + fileName + ".txt!")
# Gets the CSV file name, and grabs the information from it.
with open('cisco_backup_hosts.csv') as csvfile:
csv_reader = reader(csvfile)
list_of_rows = list(csv_reader)
rows = len(list_of_rows)
while rows >= 2:
rows = rows - 1
ip = list_of_rows[rows][0]
ip_ping = ping(ip)
if ip_ping == None:
fileName = "downDevices_" + dt_string + ".txt"
downDeviceOutput = open("backup-config/" + fileName, "a")
downDeviceOutput.write(str(ip) + "\n")
print(str(ip) + " is down!")
else:
get_saved_config(list_of_rows[rows][0], list_of_rows[rows][1], list_of_rows[rows][2], list_of_rows[rows][3])