-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBackup Cisco Switch and Router Configuration using telnet with Python
54 lines (44 loc) · 1.71 KB
/
Backup Cisco Switch and Router Configuration using telnet with Python
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
import sys
import getpass
import telnetlib
import time
from datetime import date
from datetime import datetime
import os
def get_filename_datetime():
# Use current date & time to get a text file name.
return str(datetime.now().strftime('%Y_%m_%d %H_%M_%S'))
# Get full path for writing.
fname = get_filename_datetime()
user = input("Enter your remote telnet account: ")
password = getpass.getpass()
with open("switchlist.txt") as file:
for ip in file:
HOST = ip.strip()
#Removed Space of any at the end of IP address.
try:
tn = telnetlib.Telnet(HOST)
#print("trying to connect a host" + " " +HOST)
except:
print("\x1b[0;31;40m" + "Error to connect" + " " +HOST +"\x1b[0m")
#If Telnet failed to device due to some reason then show error and continue to next hop this Error will be highlighted.
continue
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b'\r')
n, match, previous_text = tn.expect([br'Login invalid', br'\$'], 10)
if n == 0:
print("Username and password failed - giving up" + " " +HOST)
else:
print("Login into the device and trying for backup on " + " " +HOST)
tn.write(b"terminal len 0\n")
tn.write(b"show run\n")
tn.write(b"exit\n")
backupread=tn.read_all().decode('ascii')
saveoutput=open("backup" + " " +HOST + " " +fname + ".txt", "w")
saveoutput.write(backupread)
saveoutput.close()
print(" Backup Successfully " + " " +HOST)