示例#1
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as asa:
             commands = ["interface Management0/0", "exit"]
             out = await asa.send_config_set(commands)
             self.assertIn("interface Management0/0", out)
             self.assertIn("exit", out)
示例#2
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hp:
             commands = ["vlan 1", "quit"]
             out = await hp.send_config_set(commands)
             self.assertIn("vlan 1", out)
             self.assertIn("quit", out)
示例#3
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as junos:
             commands = ["show ver", "show conf", "show chassis firmware"]
             for cmd in commands:
                 out = await junos.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#4
0
    async def connect_and_run(device, configpath, output_csv):

        present_output("\nConnecting to {}.....\n".format(device['host']))
        try: 
            ios = netdev.create(**device)
            await ios.connect()
        except netdev.exceptions.TimeoutError as e:
            timeouts.append(device['host'])
            present_output("\nERROR =  {}\n".format(e))
            return
        except netdev.exceptions.DisconnectError as e:
            authfailed.append(device['host'])
            present_output("\nERROR = {}\n".format(e))
            return
        except netdev.exceptions.CommitError as e:
            unknownerror.append(device['host'])
            present_output("\nERROR = {}\n".format(e))
            return
        except Exception as e:
            unknownerror.append(device['host'])
            present_output("\nERROR = {}\n".format(e))
            return

        filename = ios.base_prompt
        ip = device['host'] 
                
        successes.append( (ip , ios.base_prompt) )
                
        present_output("\nGathering device details for host " + device['host']+ ":\n")
        output = await gather_used_port_output(ios, ip, device["device_type"], output_csv)
        present_output(output)
示例#5
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as junos:
             commands = ["edit system", "edit login"]
             out = await junos.send_config_set(commands, with_commit=False)
             self.assertIn("edit system", out)
             self.assertIn("edit login", out)
async def task(param):
    async with netdev.create(**param) as routeros:
        commands = ['/ip address', 'print', '/']
        for cmd in commands:
            print(await routeros.send_command(cmd))
        out = await routeros.send_config_set(commands)
        print(out)
示例#7
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as asa:
             out = await asa.send_command("copy r scp:", pattern=r'\[running-config\]\?', strip_command=False)
             out += await asa.send_command("\n", pattern=r'\[\]\?', strip_command=False)
             out += await asa.send_command("\n", strip_command=False)
             self.assertIn('%Error', out)
async def _gather_commands(device, params) -> None:
    async with netdev.create(**params) as conn:
        async with aiofiles.open(f"output/routers/{device.name}.txt",
                                 'w') as f:
            for command in COMMANDS:
                output = await conn.send_command(command)
                await f.write(f"=== {command} ===\n{output}\n\n")
示例#9
0
async def task(param):
    async with netdev.create(**param) as iosxr:
        # Testing sending simple command
        out = await iosxr.send_command("show ver")
        print(out)
        # Testing sending simple command with long output
        out = await iosxr.send_command("show run")
        print(out)
        # Testing sending configuration set
        commands = ["interface loopback 0", "description TEST LOOPBACK"]
        out = await iosxr.send_config_set(commands, with_commit=True)
        print(out)
        # Testing failed commit
        commands = [
            "interface GigabitEthernet 0/0/0/0", "service-policy input 1"
        ]
        out = await iosxr.send_config_set(commands, with_commit=False)
        print(out)
        try:
            commands = [
                "interface GigabitEthernet 0/0/0/0", "service-policy input 2"
            ]
            await iosxr.send_config_set(commands)
        except netdev.CommitError:
            print("Commit Error")
示例#10
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hw:
             out = await hw.enter_shell_mode()
             out = await hw.enter_shell_mode()
             out = await hw.send_command("id")
             self.assertIn('uid=0(root)', out)
示例#11
0
async def connect_ssh(device, command):
    print(f"\nПодключаюсь к {device['host']}")
    try:
        async with netdev.create(**device) as ssh:
            return await ssh.send_command(command)
    except netdev.exceptions.TimeoutError:
        print('Connection error')
示例#12
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as ios:
             commands = ["line con 0", "exit"]
             out = await ios.send_config_set(commands)
             self.assertIn("line con 0", out)
             self.assertIn("exit", out)
示例#13
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as arista:
             out = await arista.send_command("erase startup", pattern=r'\[confirm\]', strip_command=False)
             out += await arista.send_command("no", strip_command=False)
             out += await arista.send_command("show startup", strip_command=False)
             self.assertIn('Startup-config last modified', out)
示例#14
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hp:
             commands = ["vlan 1", "quit"]
             out = await hp.send_config_set(commands)
             self.assertIn("vlan 1", out)
             self.assertIn("quit", out)
示例#15
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as terminal:
             commands = ["ls -al", "pwd", "echo test"]
             for cmd in commands:
                 out = await terminal.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
async def collect_outputs(device_params, commands):
    """
    Execute commands on devices

    Args:
        device_params (dict): dictionary, where key is hostname, value is netmiko connection dictionary
        commands (list): list of commands to be executed on devices

    Returns:
        dict: key is hostname, value is string with all outputs
    """
    hostname = device_params.pop('hostname')
    device_result = ['{0} {1} {0}'.format('=' * 20, hostname)]

    try:
        async with netdev.create(**device_params) as connection:
            device_result = ['{0} {1} {0}'.format('=' * 20, hostname)]

            for command in commands:
                command_result = await connection.send_command(command)
                device_result.append('{0} {1} {0}'.format('=' * 20, command))
                device_result.append(command_result)

    except netdev.exceptions.TimeoutError as e:
        device_result.append(str(e))
        device_result_string = '\n\n'.join(device_result)

    device_result_string = '\n\n'.join(device_result)
    return device_result_string
示例#17
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as fuj:
             commands = ["vlan database", "exit"]
             out = await fuj.send_config_set(commands)
             self.assertIn("vlan database", out)
             self.assertIn("exit", out)
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hp:
             commands = ["dir", "display ver", "display cur", "display ssh server status"]
             for cmd in commands:
                 out = await hp.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#19
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as nxos:
             commands = ["dir", "show ver", "show run", "show ssh key"]
             for cmd in commands:
                 out = await nxos.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
async def configure_device_from_netbox(connection_params):
    hostname = connection_params.pop('hostname')
    async with netdev.create(**connection_params) as device_conn:
        device_config = await create_device_config(hostname)
        device_config_list = device_config.split('\n')
        device_response = await device_conn.send_config_set(device_config_list)
        return device_response
示例#21
0
async def find_mac_address_on_switch(switch_address: str, username: str,
                                     password: str, platform: str, maclist):
    async with netdev.create(username=username,
                             password=password,
                             device_type=platform,
                             host=switch_address) as connection:
        print(f'Connected to {connection.base_prompt} successfully.')

        for mac in maclist:

            mac_addr = mac['MAC']
            mac_dict = await create_mac_address_dictionary(
                connection, mac_addr)

            if mac_dict is None:
                print(f"{mac_addr} not found on {switch_address}.")
                continue

            if mac_addr in mac_dict.keys():
                print(
                    f"{mac_addr} found on {mac_dict[mac_addr]['port']}.  Checking operational mode..."
                )
                result = await get_switchport_operational_mode(
                    connection, mac_dict[mac_addr]['port'])

                if 'access' in result.lower():
                    print(
                        f"MAC address {mac_addr} is located on {switch_address} on interface {mac_dict[mac_addr]['port']}"
                    )
                else:
                    print(
                        f"{mac_dict[mac_addr]['port']} on {switch_address} is not operating as an access port.  Ignoring..."
                    )
示例#22
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as asa:
             commands = ["interface Management0/0", "exit"]
             out = await asa.send_config_set(commands)
             self.assertIn("interface Management0/0", out)
             self.assertIn("exit", out)
示例#23
0
async def sshing(ip: str, user: str, passwd: str, cmd_list: list, sem) -> list:
    '''
    SSH to IP with USER and PASSWORD uses transform to give IP and MASK VLAN 50
    '''
    async with sem:
        try:

            async with netdev.create(host=ip,
                                     device_type='cisco_ios',
                                     username=user,
                                     password=passwd) as ios:
                output = [
                    await ios.send_command(cmd, strip_command=True)
                    for cmd in cmd_list
                ]
            result = [[
                string for string in command.split('\n')
                if not string.strip() == ''
            ] for command in output]
            return {'ip': ip, 'output': result}
        except:
            print(
                '-=WARNING=- Cant connect to device. PLEASE CHECK USERNAME,HOSTNAME,COMMAND '
                + ip)
            return {
                'ip':
                ip,
                'output': [
                    'Device reachable, 22 port opened but cant connect. Probably wrong username or password'
                ]
            }
示例#24
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hp:
             commands = ["dir", "display ver", "display cur", "display ssh server status"]
             for cmd in commands:
                 out = await hp.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#25
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as aos:
             commands = ["interface loopback", "exit"]
             out = await aos.send_config_set(commands)
             self.assertIn("loopback", out)
             self.assertIn("exit", out)
示例#26
0
async def connect_ssh(device, command, semaphore):
    async with semaphore:
        print(f'Подключаюсь к {device["host"]}')
        async with netdev.create(**device) as ssh:
            output = await ssh.send_command(command)
        print(f'Получен результат от {device["host"]}')
        return output
示例#27
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as mik:
             commands = ["/ip address print", "/system package print", " /user print"]
             for cmd in commands:
                 out = await mik.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#28
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as aos:
             commands = ["interface loopback", "exit"]
             out = await aos.send_config_set(commands)
             self.assertIn("interface loopback", out)
             self.assertIn("exit", out)
示例#29
0
async def task(param):
    async with netdev.create(**param) as junos:
        # Testing sending simple command
        out = await junos.send_command("show version")
        print(out)
        # Testing sending configuration set
        commands = ["edit system", "edit login"]
        out = await junos.send_config_set(commands, with_commit=True)
        print(out)
        # Testing sending simple command with long output
        out = await junos.send_command("show config")
        print(out)
        # Testing interactive dialog
        commands = [
            "set system login message 123", "delete system login message 123"
        ]
        out = await junos.send_config_set(commands,
                                          with_commit=False,
                                          exit_config_mode=False)
        out += await junos.send_command(
            "exit",
            pattern=r'Exit with uncommitted changes\?',
            strip_command=False)
        out += await junos.send_command("no", strip_command=False)
        out += await junos.send_command("rollback 0", strip_command=False)
        out += await junos.send_command("exit configuration-mode",
                                        strip_command=False)
        print(out)
示例#30
0
async def connect_ssh(device, command):
    print(f'ASYNC Подключаюсь к {device["host"]}')
    async with netdev.create(**device) as ssh:
        output = await ssh.send_command(command)
        await asyncio.sleep(5)
    print(f'ASYNC Получен результат от {device["host"]}')
    return output
示例#31
0
async def send_show_commands_to_cisco(device_params, commands):
    results = {device_params['host']: {}}
    async with netdev.create(**device_params) as ssh:
        for command in commands:
            output = await ssh.send_command(command)
            results[device_params['host']][command] = output
    return results
示例#32
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as terminal:
             commands = ["ls -al", "pwd", "echo test"]
             for cmd in commands:
                 out = await terminal.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#33
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as asa:
             commands = ["show ver", "show run", "show ssh"]
             for cmd in commands:
                 out = await asa.send_command(cmd, strip_command=False)
                 self.assertIn(cmd, out)
示例#34
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as ios:
             out = await ios.send_command("conf", pattern=r'\[terminal\]\?', strip_command=False)
             out += await ios.send_command("term", strip_command=False)
             out += await ios.send_command("exit", strip_command=False)
             self.assertIn('Enter configuration commands', out)
示例#35
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as nxos:
             commands = ["line con", "exit"]
             out = await nxos.send_config_set(commands)
             self.assertIn("line con", out)
             self.assertIn("exit", out)
示例#36
0
async def configure_router(device, config_commands):
    errors = [
        'Invalid input detected', 'Incomplete command', 'Ambiguous command'
    ]
    if isinstance(config_commands, str): config_commands = [config_commands]
    print(f"Подключаюсь к {device['host']}")
    async with netdev.create(**device) as ssh:
        print(f'Отправляю команды на {device["host"]}')
        output = await ssh.send_command('conf t\n',
                                        strip_command=False,
                                        strip_prompt=False)
        for command in config_commands:
            res = await ssh.send_command(command,
                                         strip_command=False,
                                         strip_prompt=False)
            for error in errors:
                if error in res:
                    raise ValueError(
                        f'Команда {command} выполнилась с ошибкой {error} на устройстве {device["host"]}'
                    )
            output += res
        output += await ssh.send_command('end\n',
                                         strip_command=False,
                                         strip_prompt=False)
        print(f'Получили данные от {device["host"]}:')
        return output
示例#37
0
async def task(param):

    # Create an object for the devices and open SSH connections
    async with netdev.create(**param) as device:

        # Testing sending simple command

        # Command to send
        cmd = "show system"

        # Sending command
        output = await device.send_command(cmd)

        # Display the output
        print(output)

        # Display separator
        print("*" * 80)

        # Testing sending configuration set

        # Commands to send
        commands = ["vlan 3000", "no vlan 3001"]

        # Sending command
        output = await device.send_config_set(commands)

        # Display the output
        print(output)
async def task(devices):
    for param in devices:
        # The main folder it should be already created
        os.chdir('E:\Backup')
        backupDirName = str((datetime.datetime.now()).date())
        x = os.path.isdir(backupDirName)
        # Script will create a folder هn the name of today's date & if the folder already exist will skip this line
        if x == False:
            os.mkdir(backupDirName)
        os.chdir(backupDirName)
        # inside the folder that was created befor it will be create another folder with name of device & if the folder already exist will skip this line
        z = os.path.isdir(param[1])
        if z == False:
            os.mkdir(param[1])
        os.chdir(param[1])
        # inside the device folder it will be create a file with name "running-config.cfg" & if the file already exist Will be erased the old backup with the new backup
        f = open(
            "E:\Backup/" + backupDirName + "/" + param[1] +
            "/running-config.cfg", "a")
        # Connect with the device
        async with netdev.create(**param[0]) as ios:
            # moment of start process with this device
            start_time = time.time()
            print('+++ Getting the backup from Switch " ' + str(param[1]) +
                  ' " :')
            # the script will send this 2 command into the device
            await ios.send_command("terminal length 1000")
            output = await ios.send_command("show run")
            # save the run config into the file that was created for this device
            print(output, file=f)
            print("\t--- %.2f seconds. " % (time.time() - start_time))
            print('\t--- The backup has been successfully completed. \n')
示例#39
0
async def task(param):
    async with netdev.create(**param) as fuj:
        # Testing sending configuration set
        out = await fuj.send_config_set(['vlan database', 'exit'])
        print(out)
        # Testing sending simple command
        out = await fuj.send_command('show ver')
        print(out)
示例#40
0
async def task(param):
    async with netdev.create(**param) as fuj:
        # Testing sending configuration set
        out = await fuj.send_config_set(['vlan database', 'exit'])
        print(out)
        # Testing sending simple command
        out = await fuj.send_command('show ver')
        print(out)
示例#41
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as ios:
             out = await ios.send_command("conf", strip_command=False)
             out += await ios.send_command("hostname test", strip_command=False)
             out += await ios.send_command("exit", pattern=r'Uncommitted changes found', strip_command=False)
             out += await ios.send_command("no", strip_command=False)
             self.assertIn('commit them before exiting', out)
示例#42
0
async def connect_ssh(device, command):
    await asyncio.sleep(7)
    print(f"\nПодключаюсь к {device['host']}")
    async with netdev.create(**device) as ssh:
        output = await ssh.send_command(command)
        await asyncio.sleep(5)
        print(f'\nПолучили данные от {device["host"]}')
    return output
示例#43
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as junos:
             commands = ["edit system", "edit login"]
             out = await junos.send_config_set(commands,
                                               with_commit=False)
             self.assertIn("edit system", out)
             self.assertIn("edit login", out)
示例#44
0
async def connect_ssh(device, command):
    print(f'Подключаюсь к {device["host"]}')
    try:
        async with netdev.create(**device) as ssh:
            output = await ssh.send_command(command)
        return output
    except (netdev.DisconnectError, netdev.exceptions.TimeoutError):
        return None
示例#45
0
async def task(param):
    async with netdev.create(**param) as arista:
        # Testing sending simple command
        out = await arista.send_command('show run', strip_command=True)
        print(out)
        # Testing sending configuration set
        commands = ["vlan 1", "exit"]
        out = await arista.send_config_set(commands)
        print(out)
示例#46
0
async def task(param):
    async with netdev.create(**param) as arista:
        # Testing sending simple command
        out = await arista.send_command('ls -al', strip_command=True)
        print(out)
        out = await arista.send_command('pwd', strip_command=True)
        print(out)
        out = await arista.send_command('echo test', strip_command=True)
        print(out)
示例#47
0
async def task(param):
    async with netdev.create(**param) as asa:
        # Testing sending simple command
        out = await asa.send_command('show run')
        print(out)
        # Testing interactive dialog
        out = await asa.send_command("copy r scp:", pattern=r'\[running-config\]\?', strip_command=False)
        out += await asa.send_command("\n", pattern=r'\[\]\?', strip_command=False)
        out += await asa.send_command("\n", strip_command=False)
        print(out)
示例#48
0
async def task(param):
    async with netdev.create(**param) as routeros:
        # Testing sending simple command
        commands = ['/ip address', 'print', '/']
        for cmd in commands:
            print(await routeros.send_command(cmd))

        # Testing sending configuration set
        out = await routeros.send_config_set(commands)
        print(out)
示例#49
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as junos:
             commands = ["set system login message 123", "delete system login message 123"]
             out = await junos.send_config_set(commands, with_commit=False, exit_config_mode=False)
             out += await junos.send_command("exit", pattern=r'Exit with uncommitted changes\?',
                                             strip_command=False)
             out += await junos.send_command("no", strip_command=False)
             out += await junos.send_command("rollback 0", strip_command=False)
             out += await junos.send_command("exit configuration-mode", strip_command=False)
             self.assertIn('load complete', out)
示例#50
0
async def task(param):
    async with netdev.create(**param) as ios:
        # Testing sending simple command
        out = await ios.send_command("show ver")
        print(out)
        # Testing sending configuration set
        commands = ["interface loopback", "exit"]
        out = await ios.send_config_set(commands)
        print(out)
        # Testing sending simple command with long output
        out = await ios.send_command("show run")
        print(out)
示例#51
0
 async def connect(self, host, port, username, password, device_type="cisco_ios", enablePass = "******"):
     loginInfo = {
         "host": host,
         "username": username,
         "password": password,
         "device_type": device_type,
     }
     if device_type in ["cisco_ios"]:
         loginInfo["secret"] = password
     print(loginInfo)
     self.net_connect = netdev.create(**loginInfo)
     await self.net_connect.connect()
示例#52
0
async def task(param):
    async with netdev.create(**param) as hp:
        # Testing sending simple command
        out = await hp.send_command('display ver')
        print(out)
        # Testing sending configuration set
        commands = ["Vlan 1", "quit"]
        out = await hp.send_config_set(commands)
        print(out)
        # Testing sending simple command with long output
        out = await hp.send_command('display cur')
        print(out)
示例#53
0
async def task(param):
    async with netdev.create(**param) as ios:
        # Testing sending simple command
        out = await ios.send_command("show ver")
        print(out)
        # Testing sending configuration set
        commands = ["line console 0", "exit"]
        out = await ios.send_config_set(commands)
        print(out)
        # Testing sending simple command with long output
        out = await ios.send_command("show run")
        print(out)
        # Testing interactive dialog
        out = await ios.send_command("conf", pattern=r'\[terminal\]\?', strip_command=False)
        out += await ios.send_command("term", strip_command=False)
        out += await ios.send_command("exit", strip_command=False, strip_prompt=False)
        print(out)
示例#54
0
async def task(param):
    async with netdev.create(**param) as junos:
        # Testing sending simple command
        out = await junos.send_command("show version")
        print(out)
        # Testing sending configuration set
        commands = ["edit system", "edit login"]
        out = await junos.send_config_set(commands, with_commit=True)
        print(out)
        # Testing sending simple command with long output
        out = await junos.send_command("show config")
        print(out)
        # Testing interactive dialog
        commands = ["set system login message 123", "delete system login message 123"]
        out = await junos.send_config_set(commands, with_commit=False, exit_config_mode=False)
        out += await junos.send_command("exit", pattern=r'Exit with uncommitted changes\?', strip_command=False)
        out += await junos.send_command("no", strip_command=False)
        out += await junos.send_command("rollback 0", strip_command=False)
        out += await junos.send_command("exit configuration-mode", strip_command=False)
        print(out)
示例#55
0
async def task(param):
    async with netdev.create(**param) as nxos:
        # Testing sending simple command
        out = await nxos.send_command('show run', strip_command=True)
        print(out)
示例#56
0
 async def task():
     for dev in self.devices:
         with self.assertRaises(netdev.TimeoutError):
             async with netdev.create(**dev, timeout=0.1) as nxos:
                 await nxos.send_command('show run | i hostname')
示例#57
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as nxos:
             out = await nxos.send_command('sh run | i hostname')
             self.assertIn(nxos.base_prompt, out)
示例#58
0
 async def task():
     for dev in self.devices:
         with self.assertRaises(netdev.TimeoutError):
             async with netdev.create(**dev, timeout=0.1) as terminal:
                 out = await terminal.send_command("uname -a")
示例#59
0
 async def task():
     for dev in self.devices:
         async with netdev.create(**dev) as hp:
             out = await hp.send_command('display cur | i sysname')
             self.assertIn(hp.base_prompt, out)
示例#60
0
 async def task():
     for dev in self.devices:
         with self.assertRaises(netdev.TimeoutError):
             async with netdev.create(**dev, timeout=0.1) as hp:
                 await hp.send_command('display cur | i sysname')