async def main(): """Simple example of connecting to an IOSXEDevice with the AsyncIOSXEDriver""" async with AsyncIOSXEDriver(**MY_DEVICE) as conn: # Platform drivers will auto-magically handle disabling paging for you result = await conn.send_command("show run") print(result.result)
async def send_show(device, command): try: async with AsyncIOSXEDriver(**device) as conn: result = await conn.send_command(command) return result.result except ScrapliException as error: print(error, device["host"])
class Device(DriverBase): """ DriverBase for Cisco IOS devices via SSH. """ def __init__(self, name: str): super().__init__(name) self.driver: AsyncIOSXEDriver = Optional[None] async def login(self, creds: Optional[Credential] = None) -> bool: conn_args = dict( auth_username=creds.username, auth_password=creds.password.get_secret_value(), auth_strict_key=False, timeout_socket=60, # connect timeout transport="asyncssh", ) if (port := self.private.get("port")) is not None: conn_args["port"] = int(port) self.log.info(f"{self.name}: Connecting to Cisco SSH device") self.driver = AsyncIOSXEDriver(host=self.device_host, **conn_args) try: await self.driver.open() await self.driver.send_command("show users") except Exception as exc: emsg = f"{self.name} No Cisco SSH access: {str(exc)}, skipping." self.log.error(emsg) return False self.creds = creds return True
async def test_non_async_transport(): device = DEVICES["mock_cisco_iosxe"].copy() with pytest.raises(TransportPluginError) as exc: AsyncIOSXEDriver(transport="system", **device) assert ( str(exc.value) == "Attempting to use transport type system with an asyncio driver, must use one of ['asyncssh', 'asynctelnet'] transports" )
async def send_show(device, command): # На данный момент (scrapli 2021.1.30) таймаут при подключении к недоступному # хосту будет 2 минуты, поэтому пока что лучше добавлять wait_for или # async_timeout вокруг подключения try: #async with timeout(10): async with AsyncIOSXEDriver(**device) as ssh: result = await ssh.send_command(command) return result.result except ScrapliException as error: print(error, device["host"]) except asyncio.exceptions.TimeoutError: print("asyncio.exceptions.TimeoutError", device["host"])
def test_check_kwargs_comms_prompt_pattern(): with pytest.warns(UserWarning) as warn: conn = AsyncIOSXEDriver(host="localhost", comms_prompt_pattern="something") assert ( conn.comms_prompt_pattern == "(^[a-z0-9.\\-_@()/:]{1,63}>$)|(^[a-z0-9.\\-_@/:]{1,63}#$)|(^[a-z0-9.\\-_@/:]{1,63}\\(conf[a-z0-9.\\-@/:\\+]{" "0,32}\\)#$)" ) assert ( str(warn[0].message) == "\n***** `comms_prompt_pattern` found in kwargs! " "*****************************************\n`comms_prompt_pattern` is ignored (dropped) when using network " "drivers. If you wish to modify the patterns for any network driver sub-classes, please do so by modifying " "or providing your own `privilege_levels`.\n***** `comms_prompt_pattern` found in kwargs! " "*****************************************" )
async def main(): """Main""" async with AsyncIOSXEDriver(**device) as conn: callbacks = [ ReadCallback( contains="rtr1#", callback=callback_one, name="enter config mode callback", case_insensitive=False, ), ReadCallback( contains_re=r"^rtr1\(config\)#", callback=callback_two, complete=True, ), ] await conn.read_callback(callbacks=callbacks, initial_input="show run | i hostname")
async def send_show(device, command): async with AsyncIOSXEDriver(**device) as conn: result = await conn.send_command(command) return result.result
async def test_context_manager(): device = DEVICES["mock_cisco_iosxe"].copy() async with AsyncIOSXEDriver(transport="asyncssh", **device) as conn: assert conn.isalive() is True assert conn.isalive() is False
async def main_config(device: dict): """ - Get detailed device info from inventory ( yaml mock for now ... TO DO : get full from netbox) ... async - generate config from device info using jinja template .. async - Connect to device ( scrapli async ), push the rest of the config - TO DO perform some tests from device ( scrapli )and add device to PRTG ... async :param: device: dict - dict with basic device info :return: """ print(f"\n get device info from yaml inventory \n") dev_info = await _get_device_data(device['serial']) env = Environment(loader=FileSystemLoader('.'), enable_async=True) template = env.get_template("config.j2") print(f"\n Render data with Jinja2 template \n") logging.info(f"Rendering data for device with SN : {device['serial']}") config = str(await template.render_async(device=dev_info)).splitlines() # pprint.pprint(config) # dbg print(f" \n Scrapli async part ... push config to device \n") rtr = { "host": device['device_IP'], "auth_username": "******", "auth_password": "******", "auth_strict_key": False, "transport": "asyncssh", } # wait for router to exit guestshell and complete the boot process because you cant ssh to it before that for i in range(3): print(f"\nWaiting for RTR to finish booting\n") logging.info("Waiting 30 sec for device to complete booting") await asyncio.sleep(30) try: async with AsyncIOSXEDriver(**rtr) as conn: logging.info( f"sending config to device with SN : {device['serial']}") results3 = await conn.send_configs( configs=config, failed_when_contains=["Invalid input detected"], stop_on_failed=True, timeout_ops=5) pprint.pprint( f"RESULT 3 : {[result.result for result in results3]}" ) # dbg # get some verification commands results1 = await conn.send_commands( ["show int des", "sh ip route", "sh ip int brie"]) pprint.pprint([result.result for result in results1]) break except: print(f"\nUnable to ssh to device .. waiting another 30 sec\n") logging.info( f"Unable to ssh to dev with SN {device['serial']}, waiting for another 30 sec" ) print(f"\nAdding device to PRTG\n") try: await prtg_add(device['device_IP'], dev_info['location']) logging.info(f"adding device with SN : {device['serial']} to PRTG") except: print(f"Failed to add a device : Error - {sys.exc_info()[0]}") return
async def main(): async with AsyncIOSXEDriver(**MY_DEVICE) as conn: # Platform drivers will auto-magically handle disabling paging for you result = await conn.send_command("show version") breakpoint()