def connectToDevice(deviceconfig): """ Parse device config data & open SSH connection """ print("Loading device configuration...") device = {} device["host"] = deviceconfig["address"] device["auth_username"] = deviceconfig["username"] device["auth_password"] = deviceconfig["password"] device["auth_strict_key"] = False device["timeout_socket"] = 10 device["timeout_ops"] = 10 try: device["port"] = deviceconfig["port"] except KeyError: pass if deviceconfig["type"] == "ios-xe": conn = IOSXEDriver(**device) elif deviceconfig["type"] == "nx-os": conn = NXOSDriver(**device) try: print(f"Attempting connection to {device['host']}") conn.open() print(f"Successfully connected to {device['host']}") except Exception as e: print(f"Failed connection to {device['host']}") print("Error message is: %s" % e) return None return conn
def main(): """Simple example of configuring banners and macros on an IOSXEDevice""" conn = IOSXEDriver(**MY_DEVICE) conn.open() my_banner = """This is my router, get outa here! I'm serious, you can't be in here! Go away! """ # the overall pattern/process is that we must use send_interactive as this is an "interactive" # style command/input because the prompt changes and relies on a human to understand what is # going on. this whole operation is completed by the `send_interactive` method, but we break it # up here so its easier to understand what is going on. first we have a "start" point -- where # we send the actual command that kicks things off -- in this case "banner motd ^" -- we need to # tell scrapli what to expect so it knows there is success; "Enter TEXT message." in this # exmaple. We set the "hidden input" to `True` because this forces scrapli to not try to read # the inputs back off the channel -- we can't read the inputs because they are interrupted by # the prompt of enter your text blah blah. banner_start = ("banner motd ^", "Enter TEXT message.", True) # next we can simply create an "event" for each line of the banner we want to send, we dont # need to set the "hidden_prompt" value to `True` here because scrapli can simply read the # inputs off the channel normally as there is no prompts/inputs from the device banner_lines = [(line, "\n") for line in my_banner.splitlines()] # then we need to "end" our interactive event and ensure scrapli knows how to find the prompt # that we'll be left at at the end of this operation. note that you could just capture the # config mode prompt via `get_prompt` if you wanted and pass that value here, but we'll set it # manually for this example banner_end = ("^", "csr1000v(config)#", True) # finally we need to add all these sections up into a single list of tuples so that we can pass # this to the `send_interactive` method -- note the `*` in front of the `banner_lines` argument # we "unpack" the tuples from the list into this final list object banner_events = [banner_start, *banner_lines, banner_end] result = conn.send_interactive(interact_events=banner_events, privilege_level="configuration") print(result.result) # Note: csr1000v (at least the version scrapli is regularly tested with does not support macros # the following has been tested and works on a 3560 switch my_macro = """# description desc this_is_a_neat_macro # do a thing power inline never """ macro_start = ("macro name my_macro", "Enter macro commands one per line.", True) macro_lines = [(line, "\n", True) for line in my_macro.splitlines()] macro_end = ("@", "csr1000v(config)#", True) macro_events = [macro_start, *macro_lines, macro_end] result = conn.send_interactive(interact_events=macro_events, privilege_level="configuration") print(result.result)
def gather_info(device, path): data = dict() conn = IOSXEDriver(**device) conn.open() # выполняем необходимые команды show_version = conn.send_command("show version") config = conn.send_command("show running-config") show_cdp = conn.send_command("show cdp neighbors") conn.send_configs(NTP_COMMANDS) show_ntp = conn.send_command("show ntp status") conn.close() # записываем инфу для вывода data["hostname"] = re.search(r"\s*(\S+)\s+uptime\s+is", show_version.result).group(1) data["model"] = re.search(r"[Cc]isco\s+(\S+)\s+\(", show_version.result).group(1) data["software"] = re.search(r".*Software\s+\((?P<package>\S+)\),\s+Version\s+(?P<version>\S+),\s+", show_version.result).groupdict() # выяснем NPE или PE if re.search(r"NPE", data["software"]["package"]): data["payload"] = "NPE" else: data["payload"] = "PE" # делаем бэкап backup_path = os.path.join(path, 'backups') now = datetime.datetime.now() if not os.path.exists(backup_path): os.mkdir(backup_path) with open(f"{backup_path}/{data['hostname']}-{now.strftime('%Y_%m_%d-%H_%M_%S')}.conf", "w") as input: input.write(config.result) # проверяем cdp if re.search(r"cdp\s+is\s+not\s+enabled", show_cdp.result, re.IGNORECASE): data["cdp_status"] = "CDP is OFF" data["cdp_peers"] = "0 peers" else: data["cdp_status"] = "CDP is ON" peers = re.search(r"total\s+cdp\s+entries\s+displayed\s*:\s*(\d+)", show_cdp.result, re.IGNORECASE) data["cdp_peers"] = f"{peers.group(1)} peers" # проверяем ntp if re.search(r"clock\s+is\s+unsynch", show_ntp.result, re.IGNORECASE): data["ntp_status"] = "Clock not Sync" elif re.search(r"clock\s+is\s+synch", show_ntp.result, re.IGNORECASE): data["ntp_status"] = "Clock in Sync" elif re.search(r"ntp\s+is\s+not\s+enabled", show_ntp.result, re.IGNORECASE): data["ntp_status"] = "Clock not Sync" print(f"{data['hostname']}|{data['model']}|{data['software']['package']} {data['software']['version']}|{data['payload']}|{data['cdp_status']}, {data['cdp_peers']}|{data['ntp_status']}")
def main(): """Simple example of configuring banners and macros on an IOSXEDevice""" conn = IOSXEDriver(**MY_DEVICE) conn.open() my_banner = """banner motd ^ This is my router, get outa here! I'm serious, you can't be in here! Go away! ^ """ # Because the banner "input mode" is basically like a text editor where we dont get the prompt # printed out between sending lines of banner config we need to use the `eager` mode to force # scrapli to blindly send the banner/macro lines without looking for the prompt in between each # line. You should *not* use eager unless you need to and know what you are doing as it # basically disables one of the core features that makes scrapli reliable! result = conn.send_config(config=my_banner, eager=True) print(result.result)
def connect_cli(self, **kwargs): def to_telnet(cli, **kwargs): try: cli.close() except Exception: pass cli = False if self.device["port"] != 23: self.debug("Swiching to telnet") self.device["port"] = 23 self.device["transport"] = "telnet" cli = self.connect_cli(**kwargs) return cli cli = IOSXEDriver(**self.device, **kwargs) try: self.debug(f'Trying to connect via TCP/{self.device["port"]} ...') cli.open() except ScrapliAuthenticationFailed: self.debug( f'Incorrect username while connecting to the device via TCP/{self.device["port"]}' ) cli = to_telnet(cli, **kwargs) except ScrapliConnectionError: self.debug( f'Device closed connection on TCP/{self.device["port"]}') # raise cli = to_telnet(cli, **kwargs) except Exception: self.debug( f'Unknown error while connecting to the device via TCP/{self.device["port"]}' ) cli = to_telnet(cli, **kwargs) else: self.debug( f'Login successful while connecting to the device via TCP/{self.device["port"]}' ) return cli
from scrapli.driver.core import IOSXEDriver switch = { "host": "192.168.65.137", "auth_username": "******", "auth_password": "******", "auth_strict_key": False } cli = IOSXEDriver(**switch) cli.open() sh_int = cli.send_command("show interface") print(sh_int.output)
"host": "ios-xe-mgmt-latest.cisco.com", "auth_username": "******", "auth_password": "******", "auth_strict_key": False }, { "host": "sbx-iosxr-mgmt.cisco.com", "auth_username": "******", "auth_password": "******", "port": 8181, "auth_strict_key": False }] os.system("clear") conn_XE = IOSXEDriver(**devices[0]) conn_XE.open() response = conn_XE.send_command("show ip int brief") print("RESPONSE") print("*" * 100) print(response.result) conn_XE.close() conn_XR = IOSXRDriver(**devices[1]) conn_XR.open() response = conn_XR.send_command("show ip int brief") print("RESPONSE") print("*" * 100) # print(response.result) # print(re.findall("Giga.+", response.result)) print(json.dumps(re.findall("Giga.+", response.result), indent=2))
level=logging.DEBUG, ) logger = logging.getLogger("scrapli") args = { "host": device["host"], "port": device["port"], "ssh_config_file": True, "auth_strict_key": False, "keepalive_interval": device["keepalive_interval"], "transport": device["transport"], "keepalive": device["keepalive"], } conn = IOSXEDriver(**args) conn.open() print("***** Get Prompt:") print(conn.get_prompt()) print("***** Show run | i hostname:") result = conn.send_commands("show run | i hostname") print(result, result[0].result) print("***** Clear logging buffer:") interact = [("clear logg", "Clear logging buffer [confirm]"), ("", "3560CX#")] result = conn.send_interactive(interact) print(result, result[0].result) print("***** Disable Paging:") result = conn.send_commands("term length 0")
def main(): """Example demonstrating basic logging with scrapli""" conn = IOSXEDriver(**MY_DEVICE) conn.open() print(conn.get_prompt()) print(conn.send_command("show run | i hostname").result)