
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import AuthenticationException
import os
import getpass
import readline
os.chdir("/root/Scripts")
uname = input("Please enter your Username: ")
passwd = getpass.getpass("Please enter your Password: ")

r19 = {
"device_type": "cisco_xe",
"ip": "192.168.122.19",
"username": uname,
"password": passwd
}
r20 = {
"device_type": "cisco_xe",
"ip": "192.168.122.20",
"username": uname,
"password": passwd
}
r21 = {
"device_type": "cisco_xe",
"ip": "192.168.122.21",
"username": uname,
"password": passwd
}
r29 = {
"device_type": "cisco_xe",
"ip": "192.168.122.29",
"username": uname,
"password": passwd
}
r30 = {
"device_type": "cisco_xe",
"ip": "192.168.122.30",
"username": uname,
"password": passwd
}
r31 = {
"device_type": "cisco_xe",
"ip": "192.168.122.31",
"username": uname,
"password": passwd
}
r10 = {
"device_type": "cisco_xe",
"ip": "192.168.122.10",
"username": uname,
"password": passwd
}
r17 = {
"device_type": "cisco_xe",
"ip": "192.168.122.17",
"username": uname,
"password": passwd
}
devices = [r19, r20, r21, r29, r30, r31, r10, r17]
def devices_configs(dev):
    dev.establish_connection()
    hostname = dev.send_command("show run | in hostname").split()[1]
    dev.send_command("terminal length 0")
    print(f"*****Connecting to device: {hostname}*****")
    dev.send_command("wr mem")
    print(f"*****Copying config for: {hostname}*****\n")
    temp = dev.send_command("show run")
    with open(f"{hostname}.cfg", "w") as dev_file:
        dev_file.write(temp)
    dev.disconnect()


for item in devices:
    try:
        net_conn = ConnectHandler(**item)
        devices_configs(net_conn)
    except (AuthenticationException):
        print("Authentication Failure: " + item["ip"])
        continue
    except (NetMikoTimeoutException):
        print("Timeout to device: " + item["ip"])
        continue
