Ejemplo n.º 1
0
def main():
    #####################################################
    ######extraer lineas del archivo de Accesso##########
    try:
        with open("perfiles") as f:
            archivo = f.read().splitlines()
    except:
        print("Fallo al abrir el Archivo")
        sys.exit()

        #####################################################
        ############Intentamos la conexion###################
    try:
        net_connect = ConnectHandler(**device)
    except:
        print("Fallo la Conexion")
        sys.exit()
    print("conexion Exitosa")
    #####################################################
    #######Recorremos los nombres de las listas##########
    ###############Y adicionamos las reglas##############
    for nombre in archivo:
        NumRegla = 2
        net_connect.send_command("config acl rule add " + nombre + " " +
                                 str(NumRegla))
        net_connect.send_command("config acl rule action " + nombre + " " +
                                 str(NumRegla) + permit)
        net_connect.send_command("config acl rule destination address " +
                                 nombre + " " + str(NumRegla) + direccionu)
        print("Regla Agregada: " + str(NumRegla))
        NumRegla += 1
        net_connect.send_command("config acl rule add " + nombre + " " +
                                 str(NumRegla))
        net_connect.send_command("config acl rule action " + nombre + " " +
                                 str(NumRegla) + deny)
        net_connect.send_command("config acl rule destination address " +
                                 nombre + " " + str(NumRegla) + direcciond)
        print("Regla Agregada: " + str(NumRegla))
        NumRegla += 1
        net_connect.send_command("config acl rule add " + nombre + " " +
                                 str(NumRegla))
        net_connect.send_command("config acl rule action " + nombre + " " +
                                 str(NumRegla) + deny)
        net_connect.send_command("config acl rule destination address " +
                                 nombre + " " + str(NumRegla) + direcciont)
        print("Regla Agregada: " + str(NumRegla))
        NumRegla += 1
        net_connect.send_command("config acl rule add " + nombre + " " +
                                 str(NumRegla))
        net_connect.send_command("config acl rule action " + nombre + " " +
                                 str(NumRegla) + deny)
        net_connect.send_command("config acl rule destination address " +
                                 nombre + " " + str(NumRegla) + direccionc)
        print("Regla Agregada: " + str(NumRegla))
        print("Terminado perfil: " + nombre)
    net_connect.close()
Ejemplo n.º 2
0
 def disconnect(
     self, library: str, device: Device, connection: ConnectHandler
 ) -> None:
     try:
         connection.disconnect() if library == "netmiko" else connection.close()
         self.log("info", f"Closed {library} Connection to {device}")
     except Exception as exc:
         self.log(
             "error", f"{library} Connection to {device} couldn't be closed ({exc})"
         )
Ejemplo n.º 3
0
    def __wrap_net_connect(cls, net_connect: netmiko.ConnectHandler,
                           host: Host) -> Closer:
        name = "{}-{}-{}".format(host.addr, host.device_type, host.protocol)

        def close_net_connect():
            debug_print("will close net_connect: " + name)
            if net_connect:
                net_connect.disconnect()
            debug_print("closed net_connect: " + name, flush=True)

        net_connect.close = close_net_connect
        return Closer(net_connect, name=name)
Ejemplo n.º 4
0
def install_hotfix(hotfix_name_full, hfn_installed, device):
    conn = ConnectHandler(**device)
    if not enter_maintenance_mode(conn):
        print(device["host"] +
              "could not enter maintenance mode. Failing gracefully")
        conn.close()
        return False
    conn.send_command("package install " + hotfix_name_full)
    output = conn.send_command("show packages")
    if hfn_installed in output:
        print(device["host"] + "successfully installed on host " +
              device["host"] + ". rebooting")
        conn.save_config()
        conn.send_command_timing("reload")
        return True
    else:
        print(device["host"] +
              "possible issue with install. Troubleshoot host " +
              device["host"])
        return False
    pass
     configStartPoint = 'running'
     device = driver(hostname=netDevice['ip'], username=netDevice['username'],
                     password=netDevice['password'], timeout=10)
 elif netDevice['device_type'] == 'cisco_asa':
     device = ConnectHandler(**netDevice)
 elif netDevice['device_type'] == 'hp_procurve':
     device = ConnectHandler(**netDevice)
 else:
     print('Unknown Device Type')
 # Begin Connection
 try:
     print('\nConnecting to ' + netDevice['ip'] + '...')
     if netDevice['device_type'] == 'cisco_asa' or netDevice['device_type'] == 'hp_procurve':
         runningConfig = device.send_command('sh run')
         deviceName = device.send_command('sh hostname').strip('\n')
         device.disconnect()
     else:
         device.open()
         runningConfig = device.get_config()
         deviceName = device.get_facts()['hostname']
         device.close()
     print('Saving config: ' + deviceName)
     file = open("c:/users/"+os.getenv('username')+"/desktop/Configs/"+deviceName+"-"+netDevice['ip']+"-"+dateTime+".txt", "w")
     if netDevice['device_type'] == 'cisco_asa':
         file.write(runningConfig)
     else:
         file.write(runningConfig[configStartPoint])
     file.close()
 except:
     print('Failed to connect to ' + netDevice['ip'])
     
Ejemplo n.º 6
0
from netmiko import ConnectHandler
import json

load_dotenv()

user = os.environ.get('username')
pw = os.environ.get('password')
sec = os.environ.get('secret')

# Connect
switch = {
    'device_type': 'cisco_ios_telnet',
    'ip': '10.10.10.2',
    'username': user,
    'password': pw,
    'secret': sec,
    'port': 23
}

try:
    c = ConnectHandler(**switch)
    c.enable()
    interfaces = c.send_command('show ip int brief', use_textfsm=True)
    #print(json.dumps(interfaces, indent=2))
    for interface in interfaces:
        if interface['status'] == 'down':
            print(f"{interface['intf']} is down!")
    c.close()
except Exception as e:
    print(e)
Ejemplo n.º 7
0
linux = {
    'device_type': 'linux',
    'ip': '10.1.1.1',
    'username': '******',
    'password': '******',
    'port': 22,
    'secret': 'cisco',
    'verbose': True
}
connection = ConnectHandler(**linux)

connection.enable()
output = connection.send_command('apt-get update')
print(output)
connection.close()

## SCP
connection = ConnectHandler(**cisco_device)
transfer_output = file_transfer(connection, source_file='1.cfg', dest_file='config.cfg', 
                                file_system='disk0:', direction='put', overwrite_file=True)
connection.disconnect()

## логирование
import logging
logging.basicConfig(filename='test.log', level=logging.DUBUG)
logger = logging.getLogger('netmiko')

# через каналы
connection.write_channel('show run\n')
time.sleep(3)
Ejemplo n.º 8
0
def main():
    NumRegla = 1
    codigo = 0
    #####################################################
    ######extraer lineas del archivo de Accesso##########
    try:
        with open("TemplateACL") as f:
            archivo = f.read().splitlines()
    except:
        print("Fallo al abrir el Archivo")
        sys.exit()

        #####################################################
        ############Intentamos la conexion###################
    try:
        net_connect = ConnectHandler(**device)
    except:
        print("Fallo la Conexion")
        # main()
        sys.exit()
    print("conexion Exitosa")

    #####################################################
    ##########Extraemos nombre de la ACL#################
    nombre = archivo[0].strip()
    del archivo[0]
    net_connect.send_command("config acl create " + nombre)

    #####################################################
    #############Recorrecmos el archivo##################
    for linea in archivo:
        linea = linea.strip()
        if linea == "host":
            codigo = 1
            continue
        elif linea == "mask":
            codigo = 2
            continue
        elif linea == "dhcp":
            net_connect.send_command(
                "config acl rule add " + nombre + " " + str(NumRegla)
            )
            net_connect.send_command(
                "config acl rule action " + nombre + " " + str(NumRegla) + permit
            )
            net_connect.send_command(
                "config acl rule protocol " + nombre + " " + str(NumRegla) + " " + udp
            )
            net_connect.send_command(
                "config acl rule source port range "
                + nombre
                + " "
                + str(NumRegla)
                + " "
                + dhcp[0]
                + " "
                + dhcp[0]
            )
            net_connect.send_command(
                "config acl rule destination port range "
                + nombre
                + " "
                + str(NumRegla)
                + " "
                + dhcp[1]
                + " "
                + dhcp[1]
            )
            print("Regla Agregada: " + str(NumRegla))
            NumRegla += 1
            codigo = 0
            continue
        elif linea == "udp":
            for puerto in udpport:
                net_connect.send_command(
                    "config acl rule add " + nombre + " " + str(NumRegla)
                )
                net_connect.send_command(
                    "config acl rule action " + nombre + " " + str(NumRegla) + permit
                )
                net_connect.send_command(
                    "config acl rule protocol "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + udp
                )
                net_connect.send_command(
                    "config acl rule destination port range "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + puerto
                    + " "
                    + puerto
                )
                print("Regla Agregada: " + str(NumRegla))
                NumRegla += 1
                codigo = 0
            continue
        elif linea == "tcp":
            for puerto in tcpport:
                net_connect.send_command(
                    "config acl rule add " + nombre + " " + str(NumRegla)
                )
                net_connect.send_command(
                    "config acl rule action " + nombre + " " + str(NumRegla) + permit
                )
                net_connect.send_command(
                    "config acl rule protocol "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + tcp
                )
                net_connect.send_command(
                    "config acl rule destination port range "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + puerto
                    + " "
                    + puerto
                )
                print("Regla Agregada: " + str(NumRegla))
                NumRegla += 1
            codigo = 0
            continue
        elif linea == "icmp":
            net_connect.send_command(
                "config acl rule add " + nombre + " " + str(NumRegla)
            )
            net_connect.send_command(
                "config acl rule action " + nombre + " " + str(NumRegla) + permit
            )
            net_connect.send_command(
                "config acl rule protocol " + nombre + " " + str(NumRegla) + " " + icmp
            )
            print("Regla Agregada: " + str(NumRegla))
            NumRegla += 1
            codigo = 0
            continue
        elif linea == "ip":
            net_connect.send_command(
                "config acl rule add " + nombre + " " + str(NumRegla)
            )
            net_connect.send_command(
                "config acl rule action " + nombre + " " + str(NumRegla) + permit
            )
            print("Regla Agregada: " + str(NumRegla))
            NumRegla += 1
            codigo = 0
            continue
        else:
            if codigo == 1:
                net_connect.send_command(
                    "config acl rule add " + nombre + " " + str(NumRegla)
                )
                net_connect.send_command(
                    "config acl rule action " + nombre + " " + str(NumRegla) + permit
                )
                net_connect.send_command(
                    "config acl rule destination address "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + linea
                    + " 255.255.255.255"
                )
                print("Regla Agregada: " + str(NumRegla))
                NumRegla += 1
                continue
            elif codigo == 2:
                linea = linea.split()
                ip = linea[0].strip()
                mask = linea[1].strip()
                net_connect.send_command(
                    "config acl rule add " + nombre + " " + str(NumRegla)
                )
                net_connect.send_command(
                    "config acl rule action " + nombre + " " + str(NumRegla) + permit
                )
                net_connect.send_command(
                    "config acl rule destination address "
                    + nombre
                    + " "
                    + str(NumRegla)
                    + " "
                    + ip
                    + " "
                    + mask
                )
                print("Regla Agregada: " + str(NumRegla))
                NumRegla += 1
                continue
            else:
                continue
    print("final: " + nombre)
    net_connect.close()