Exemple #1
0
def main():

    # generate input_file from input_subnets containing all IPs to perform inventory scan against
    while True:
        try:
            input_ips = input(
                "Enter a space delimited list of IPs to scan: ").split()
            for i in range(0, len(input_ips)):
                input_ips[i] = ipaddress.IPv4Address(input_ips[i])
        except:
            if input(
                    "Invalid data entered. Press any key to continue or 'q' to quit. "
            ) == 'q':
                exit()
        else:
            break

    if len(input_ips) > 0:

        # gather username and password
        cisco_user = input("Device Username: "******"Device Password: "******"Please wait while inventory report is being generated")
        sys.stdout.flush()

        for ip in input_ips:
            # Create connection object for Netmiko
            conn = {
                "host": str(ip),
                "username": cisco_user,
                "password": cisco_pass,
                "device_type": "cisco_ios",
            }

            # Attempt connection
            try:
                net_connect = Netmiko(**conn)
                vers = net_connect.send_command('show version')
            except:
                print(f"Error connecting to {str(ip)}")
            else:

                # Special handling for Nexus
                if "Nexus" in vers:
                    ports = net_connect.send_command(
                        'show int bri | inc "Administratively"')
                # Normal handling for IOS
                else:
                    ports = net_connect.send_command(
                        'show ip int bri | inc administratively')
                for line in ports.splitlines():
                    int = line.split()[0]
                    if int.startswith('Gig'):
                        net_connect.send_config_set(
                            [f'interface {int}', f'no shutdown'])
                net_connect.save_config()
                net_connect.disconnect()
def main():
    while True:
        try:
            dev_ips = input("Destination IP or IPs (space delimited): ").split()
            for i in range(0, len(dev_ips)):
                dev_ips[i] = ipaddress.IPv4Address(dev_ips[i])
            add_ips = input("SNMP Manager IP(s) to add (space delimited): ").split()
            for i in range(0, len(add_ips)):
                add_ips[i] = ipaddress.IPv4Address(add_ips[i])
            #rem_ips = input("SNMP Manager IP(s) to remove (space delimited): ").split()
            #for i in range(0, len(rem_ips)):
                #rem_ips[i] = ipaddress.IPv4Address(rem_ips[i])
        except:
            if input("Invalid data entered. Press any key to continue or 'q' to quit. ") == 'q':
                exit()
        else:
            break

    if len(add_ips) > 0 or len(rem_ips) > 0:
        # gather username and password
        cisco_user = input("username: "******"Please wait while the update is being performed")
        
        # Create Connection object for Netmiko
        for ip in dev_ips:
            conn = {
                "host": str(ip).rstrip("\n"),
                "username": cisco_user,
                "password": cisco_pass,
                "device_type": "cisco_ios",
            }

            # Attempt the connection
            try:
                net_connect = Netmiko(**conn)
                vers = net_connect.send_command('show version')
            except:
                print(f"Connection to {ip} failed")
            else:
                hostname = net_connect.find_prompt().split('#')[0]
                # Special handling for Nexus
                if "Nexus" in vers:
                    #add handling for nexus switches here
                    pass
                acl = net_connect.send_command('show running-config | inc snmp-server community bstar')
                if acl == "":
                    acl = net_connect.send_command('show running-config | inc snmp-server community GIpublicD')
                #for i in rem_ips:
                    #net_connect.send_config_set(['interface vlan '+vlan, rem_comm+str(i)])
                for i in add_ips:
                    net_connect.send_config_set([f"access-list {acl.split()[-1]} permit {i}"])
                
                # Save config and disconnect session
                net_connect.save_config()
                net_connect.disconnect()
                print(f"Successfully updated SNMP ACL on {hostname}")
Exemple #3
0
def main():
    """
    Funcion principal
    """

    # Llamada a la funcion "clear_screen"
    clear_screen()

    # variable de texto con el valor "ips.txt"
    name_file_ip_list = "ips.txt"
    # variable de texto con el valor "commands.txt"
    name_file_commands_list = "commands.txt"

    # Llamada a la funcion "read_files" y guardarla en la variable "ips_list".
    ips_list = read_files(name_file_ip_list)
    # Dividir las lineas de la variable ips_list en una lista.
    ips_list = ips_list.splitlines()

    # Llamada a la funcion "read_files" y guardarla en la variable
    # "command_list".
    command_list = read_files(name_file_commands_list)
    # Dividir las lineas de la variable ips_list en una lista.
    command_list = command_list.splitlines()

    # Realizar ciclo for con la lista "ip_list". para determinar que "ips"
    # estan activas.
    for ip in ips_list:
        # Llamada a la funcion "ping_alive" con el argumento "ip".
        ping_alive(ip)

    # Realizar ciclo for con la lista "ip_list". para realizar las conexions
    # y configuraciones con la libreria Netmiko.
    for ip in ips_list:
        dispositivo = {
            "username": "******",
            "ip": ip,
            "password": "******",
            "device_type": "cisco_ios",
            "secret": "pythonautomationcourse",
        }

        # Creacion de la conexion SSH.
        net_connect = Netmiko(**dispositivo)  # ** Significa que es pasado
        # todos los valores del
        # Diccionario.

        net_connect.enable()  # Entrar en modo Privilegiado.

        # Enviar lista "command_list" en modo "Configuracion Global".
        net_connect.send_config_set(command_list)

        # Salvar la configuracion en los dispositivos.
        net_connect.save_config()

        # Finalizar la conexión del dispositivo.
        net_connect.disconnect()
Exemple #4
0
def config_applier():
    config = open("configs.txt")
    devicelist = []
    device = open("device_generated.txt")
    username = input("Input device username: "******"Input device password: "******"Input device secret: ")

    for line in device:
        line = line.rstrip()
        devicelist.append(line)

    config_set = config

    for host in devicelist:
        net_connect = Netmiko(host,
                              username=username,
                              password=password,
                              device_type="cisco_nxos",
                              secret=secret)

        print(net_connect.find_prompt())
        print(net_connect.enable())

        output = net_connect.send_config_set(config_set)
        print(net_connect.send_config_set(config_set))
        print(net_connect.save_config())
        print(net_connect.disconnect())

        with open("audit.txt", "a") as f:
            f.write(output)

    print("See 'audit.txt' for confirmation of process")
Exemple #5
0
class Asa():
    def __init__(self, asa_user, asa_pass):
        self.asa_user = asa_user
        self.asa_pass = asa_pass
        self.net_conn = Netmiko(host=dc1_asa,
                                username=asa_user,
                                password=asa_pass,
                                device_type='cisco_asa')

    def get_asa_pfxs(self):
        asa_ex_online, asa_ex_protect = ([] for i in range(2))
        # Gathers the object-groups for exchange-online and protection from the ASA
        asa_ex_online1 = self.net_conn.send_command(
            'show run object-group id Exchange-online-v1')
        asa_ex_protect1 = self.net_conn.send_command(
            'show run object-group id Exchange-online-protection-v1')
        self.net_conn.disconnect()

        # Strip so just have network and subnet mask
        for x in asa_ex_online1.splitlines():
            if 'network-object' in x:
                asa_ex_online.append((x.replace(' network-object ', '')))
        for x in asa_ex_protect1.splitlines():
            if 'network-object' in x:
                asa_ex_protect.append((x.replace(' network-object ', '')))
        # Swap any host entries for 255.255.255.255
        for x in asa_ex_online:
            if 'host' in x:
                asa_ex_online.remove(x)
                asa_ex_online.append(x.split('host ')[1] + ' 255.255.255.255')
        for x in asa_ex_protect:
            if 'host' in x:
                asa_ex_protect.remove(x)
                asa_ex_protect.append(x.split('host ')[1] + ' 255.255.255.255')
        return [asa_ex_online, asa_ex_protect]

    # Applies the configuration to the ASAs
    def post_asa_pfxs(self):
        print("Applying configuration on {}, please wait...".format(dc1_asa))
        show_cmds = [
            'show run object-group id Exchange-online-v1',
            'show run object-group id Exchange-online-protection-v1'
        ]
        asa_log = []
        asa_before = self.net_conn.send_config_set(show_cmds)
        asa_log.append(self.net_conn.send_config_set(asa_config))
        asa_log.append(self.net_conn.save_config())
        asa_after = self.net_conn.send_config_set(show_cmds)
        self.net_conn.disconnect()
        return [asa_before[13:-33], asa_after[13:-33], asa_log]
Exemple #6
0
def get_prompt(dev):
    ping_reply = subprocess.call(
        ['ping', '-c', '3', '-w', '3', '-q', '-n', dev['host']],
        stdout=subprocess.PIPE)
    if ping_reply == 0:
        net_conn = Netmiko(**dev)
        print("device %s is reachable" % dev['host'])
        # the commnad file used associated wit the ip address
        cfg_file = "%s.txt" % dev['host']
        output = net_conn.send_config_from_file(cfg_file)
        print(output)
        net_conn.save_config()
        net_conn.disconnect()
        # its always a good idea to write output to file to make sure that your commands have been executed successfully to the device
        print(
            "\nWriting output to file for %s ..please wait while output is printed and saved to File.\n"
            % dev['host'])
        with open('cfg-%s.txt' % dev['host'], 'a') as f:
            f.writelines(output)
    else:
        status = "%s is not reachable..skipping" % dev['host']
        print(status)
        pass
Exemple #7
0
from getpass import getpass

password = getpass()

csr1000v = {
    'device_type': 'cisco_ios',
    'username': '******',
    'password': password,
    'secret': password,
    'ip': '192.168.8.136'
}

connection = Netmiko(**csr1000v)

print connection.find_prompt()

cmd = ['logging on', 'logging buffered']
print()
print('Sending logging config to device')
print('-' * 80)
output = connection.send_config_set(cmd)
#print(output)
print('Saving Configuration to NVRAM')
print('-' * 80)
connection.save_config()
output = connection.send_config_from_file('logging_config.txt')
print(output)
show_run = connection.send_command('show run | include logging')
print(show_run)
connection.disconnect()
Exemple #8
0
    # Enviar comando para la creacion de VLAN's
    for vlan in vlan_list:
        # Variable de texto con el comando para crear vlan".
        vlan_id = "vlan {}".format(vlan)
        # Ingresado al modo "VLAN" enviar el respectivo nombre.
        vlan_name = "name Automation_VLAN_{}".format(vlan)
        
        # Ingresar las variables a una lista para enviar en "send_config_set".
        command_list = [
            vlan_id, vlan_name,
            ]
        
        # Enviar lista de comandos en "Modo Configuracion Global".
        net_connect.send_config_set(command_list)
    
    
    # Salvar la configuracion en el Swtich.
    net_connect.save_config()
    
    # Finalizar la conexion del dispositivo.
    net_connect.disconnect()
        


elif "VIOS-ADVENTERPRISEK9-M" in output:
    # Imprimir que es un Router
    print("Este es un dispositivo L3 no necesita crear VLAN's")
    
    # Finalizar la conexion del dispositivo.
    net_connect.disconnect()
Exemple #9
0
# Create dictionary that holds device details
nxos_device1 = {
    'host': 'nxos1.lasthop.io',
    'username': '******',
    'password': getpass(),
    'device_type': 'cisco_nxos',
}
nxos_device2 = {
    'host': 'nxos2.lasthop.io',
    'username': '******',
    'password': getpass(),
    'device_type': 'cisco_nxos',
}

for device in (nxos_device1, nxos_device2):

    # Establish SSH connection to the network devices using **kwargs to pull in details from dictionary
    net_connection = Netmiko(**device)

    # Send config to device from specified file
    output = net_connection.send_config_from_file('config.txt')
    # Print to console
    print(output)
    # Save to startup config
    print(net_connection.save_config())

    # Gracefully disconnect from device
    net_connection.disconnect()

Exemple #10
0
#!/usr/bin/env python
from netmiko import Netmiko
from getpass import getpass

nxos1 = {
    'host': 'nxos1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
    'device_type': 'cisco_nxos',
}

cfg_file = 'config_changes.txt'
net_connect = Netmiko(**nxos1)

print()
print(net_connect.find_prompt())
output = net_connect.send_config_from_file(cfg_file)
print(output)
print()

net_connect.save_config()
net_connect.disconnect()
Exemple #11
0
import os
from netmiko import Netmiko
from getpass import getpass
from pprint import pprint
from datetime import datetime

#password = getpass()
hosts = ["cisco1.lasthop.io", "cisco2.lasthop.io"]

for host in hosts:
    device = {'host': host, 'username': '******', 'password': '******', 'device_type': 'cisco_ios', 'session_log': 'logging.txt', 'fast_cli': True}
    ssh_conn = Netmiko(**device)
    print(ssh_conn.find_prompt())

    print("Configuration of vlan 100-105")
    sent_vlan = ssh_conn.send_config_from_file("vlans.txt")
    print("Commit")
    write_conf = ssh_conn.save_config()
    print(write_conf)





    "desc This has changed",
]

commands_Router2 = [
    "interface g0/1",
    "desc This has changed too",
]

#  ssh to device, pass in dictionary to net_connect
net_connect = Netmiko(**Router1)

print("\nRunning commands to S1...\n\n" + net_connect.find_prompt())
output = net_connect.send_config_set(commands_Router1)
output = net_connect.save_config
print(output)
print("\n\n")
output = net_connect.send_command("show int des")
print(output)
print("\n\nCommands to Router1 complete")
net_connect.disconnect()

net_connect = Netmiko(**Router2)

print("\nRunning commands to R1...\n\n" + net_connect.find_prompt())
output = net_connect.send_config_set(commands_Router2)
output = net_connect.save_config()
print(output)
output = net_connect.send_command("show int des")
print(output)
print("\n\nCommands to Router2 complete")
Exemple #13
0
from netmiko import Netmiko

username = ''
password = ''

nxos1 = {
    'host': 'nxos1.lasthop.io',
    'username': username,
    'password': password,
    'device_type': 'cisco_nxos',
}

nxos2 = {
    'host': 'nxos2.lasthop.io',
    'username': username,
    'password': password,
    'device_type': 'cisco_nxos',
}

devices = [nxos1, nxos2]

for dev in devices:
    conn = Netmiko(**dev)
    output = conn.send_config_from_file('config.txt')
    conn.save_config()
    print(output)
    conn.disconnect()
Exemple #14
0
def write_conf(ip):
    net_connect = Netmiko(**get_dic(ip))
    net_connect.enable()
    net_connect.save_config()
    show_result("configuration saved")
Exemple #15
0
from netmiko import Netmiko
from getpass import getpass

devices = ['nxos1.lasthop.io', 'nxos2.lasthop.io']
for i in devices:

    net_device = {
        'host': i,
        'username': '******',
        'password': '******',
        'device_type': 'cisco_nxos',
        'session_log': 'l2ex5.txt',
    }

    net_connection = Netmiko(**net_device)
    print(net_connection.find_prompt())

    command = "show version"
    output = net_connection.send_command(command)
    print(output)
    output1 = net_connection.send_config_from_file('vlan-exercise5.txt')
    print(output1)
    output2 = net_connection.save_config()
    print(output2)