def async_cfg_object(): scrapli_conn = AsyncScrapli(host="localhost", platform="cisco_iosxe", transport="asynctelnet") async_cfg_conn = AsyncScrapliCfg(conn=scrapli_conn, config_sources=["running", "startup"]) return async_cfg_conn
async def get_serial_num(): async with AsyncScrapli(**DEVICE) as device_conn: device_conn = cast("AsyncNetworkDriver", device_conn) response = await device_conn.send_command("show license udi") if re_match := re.search(r"SN:(?P<serial_num>\w+)", response.result): return re_match.group("serial_num") raise ValueError("Serial number not found")
async def send_show(device, show_command): try: async with AsyncScrapli(**device) as ssh: reply = await ssh.send_command(show_command) return reply.result except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): try: async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) return reply.result except ScrapliException as error: print(error)
async def _scan_device(self, device): ip = device["host"] try: async with AsyncScrapli(**device) as conn: prompt = await conn.get_prompt() return True, prompt except (ScrapliException, asyncio.exceptions.TimeoutError) as error: return False, f"{error} {ip}"
async def _scan(self, device): host = device["host"] try: async with AsyncScrapli(**device) as conn: prompt = await conn.get_prompt() return True, prompt except ScrapliException as error: return False, error
async def send_show(device, command): try: async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) parsed = reply.textfsm_parse_output() return parsed except ScrapliException as error: print(error)
async def send_show(device, command): print(f">>> connect {device['host']}") try: async with AsyncScrapli(**device) as conn: result = await conn.send_command(command) return result.result except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): print(f'Подключаюсь к {device["host"]}') try: async with AsyncScrapli(**device) as conn: result = await conn.send_command(command) return result.result except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): try: async with AsyncScrapli(**device) as conn: result = await conn.send_command(command) await asyncio.sleep(2) return result.result except ScrapliException as error: print(error, device["host"])
async def check_connection(devices_list): for device in devices_list: ip = device["host"] transport = device.get("transport") try: async with timeout(5): # для asynctelnet async with AsyncScrapli(**device) as conn: prompt = await conn.get_prompt() yield True, f"{ip=} {prompt=} {transport=}" except (ScrapliException, asyncio.exceptions.TimeoutError) as error: yield False, f"{ip=} {error=} {transport=}"
async def send_show(device, command): try: async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) await asyncio.sleep(10) return reply.result except ScrapliException as error: print(error) except asyncio.CancelledError: print("Task is cancelled") raise
async def send_show(device, show_commands): cmd_dict = {} if type(show_commands) == str: show_commands = [show_commands] try: async with AsyncScrapli(**device) as ssh: for cmd in show_commands: reply = await ssh.send_command(cmd) cmd_dict[cmd] = reply.result return cmd_dict except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): try: host = device["host"] print(f'>>> Подключаюсь к {host}') async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) print(f'<<< Получен результат от {host}') return reply.result except ScrapliException as error: print(error) except asyncio.CancelledError: await asyncio.sleep(5) print(f'### Отменено подключение к {host}')
async def send_show(device, show_commands): print(f'>>> Подключаюсь к {device["host"]}') cmd_dict = {} if type(show_commands) == str: show_commands = [show_commands] try: async with AsyncScrapli(**device) as ssh: for cmd in show_commands: reply = await ssh.send_command(cmd) cmd_dict[cmd] = reply.result print(f'<<< Получен результат от {device["host"]}') return cmd_dict except ScrapliException as error: print(error, device["host"])
async def send_cfg(device, cfg_commands, strict=False): output = "" if type(cfg_commands) == str: cfg_commands = [cfg_commands] try: async with AsyncScrapli(**device) as ssh: reply = await ssh.send_configs(cfg_commands, stop_on_failed=strict) for cmd_reply in reply: if cmd_reply.failed: print(f"При выполнении команды возникла ошибка:\n{reply.result}\n") output = reply.result return output except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): host = device["host"] print(f"Подключаюсь к {host}") try: async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) await asyncio.sleep(10) return reply.result except ScrapliException as error: print(error, host) except asyncio.CancelledError: print(f"Отмена... {host}") await asyncio.sleep(2) print("Отменено")
async def send_show(device, show_commands): cmd_dict = {} if type(show_commands) == str: show_commands = [show_commands] try: async with AsyncScrapli(**device) as ssh: for cmd in show_commands: reply = await ssh.send_command(cmd) cmd_dict[cmd] = reply.result prompt = await ssh.get_prompt() # тут добавлено приглашение, так как as_completed не сохраняет порядок устройст # и таким образом понятно от какого устройства пришел вывод и как называть файл return prompt, cmd_dict except ScrapliException as error: print(error, device["host"])
async def send_show(device, command): host = device["host"] print(f"Подключаюсь к {host}") try: async with AsyncScrapli(**device) as conn: reply = await conn.send_command(command) if host == "192.168.100.1": await asyncio.sleep(10) print(f"Получен результат от {host}") return reply.result except ScrapliException as error: print(error) except asyncio.CancelledError: print("Отмена...") await asyncio.sleep(10) print("Отменено")
async def show_commands_and_config(device_data: Dict[str, Any]): """Sends show commands and a config and saves output to a file using scrapli""" dt_str = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") device_name = device_data["device_name"] output_path = OUTPUT_PATH / f"{device_name}_{dt_str}.txt" cfg = CFG.format(device=device_name).splitlines() conn_data = create_conn_data(device_data) async with AsyncScrapli(**conn_data) as conn, aiofiles.open( output_path, "w") as f: # conn = IOSXEDriver(**CONN_DATA) # conn.open() conn = cast(AsyncNetworkDriver, conn) sh_commands_responses = await conn.send_commands(COMMANDS, strip_prompt=False) for response in sh_commands_responses: await f.write( f"===== {response.channel_input} ===== \n{response.result}\n") # print([response.failed for response in sh_commands_responses]) await f.write("\nSending configuration...\n") cfg_responses = await conn.send_configs(cfg, strip_prompt=False) for response in cfg_responses: await f.write(f"{response.channel_input}\n{response.result} ")
def async_scrapli_conn(request): return AsyncScrapli(host="localhost", platform=request.param, transport="asyncssh")