Exemple #1
0
def checkPOEPort(switch_interface):
    device = {
        "host": switch_interface['SwitchIP'],
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    logging.info("Logging in to switch {} with IP {}".format(
        switch_interface['SwitchName'], switch_interface['SwitchIP']))
    conn = Scrapli(**device)
    conn.open()
    response = conn.send_command("show poe interface {}".format(
        switch_interface['PortName']))
    if '0.5W' in response.result:
        #print('AP-needs {} reboot'.format(ap['Caption']))
        logging.info('AP-needs {} reboot'.format(ap['Caption']))
        return True
    else:
        logging.info(
            "Another fault troubleshoot {} connected to {} on {} with IP {}".
            format(ap['Caption'], switch_interface['PortName'],
                   switch_interface['SwitchName'],
                   switch_interface['SwitchIP']))
        #print("Another fault troubleshoot {} connected to {} on {} with IP {}".format(
        #    ap['Caption'], switch_interface['PortName'], switch_interface['SwitchName'], switch_interface['SwitchIP']))
        return False
Exemple #2
0
def checkPOEPower(switch_interface):
    device = {
        "host": switch_interface['SwitchIP'],
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    logging.info("Logging in to switch {} with IP {}".format(
        switch_interface['SwitchName'], switch_interface['SwitchIP']))
    conn = Scrapli(**device)
    conn.open()
    try:
        response = conn.send_command(
            "show poe interface {} | display xml".format(
                switch_interface['PortName']))
        response_dict = xmltodict.parse(response.result)
        response_json = json.dumps(response_dict)
        interface_poe = json.loads(response_json)
        poe_interface_power = interface_poe['rpc-reply']['poe'][
            'interface-information-detail']
        ['interface-power-detail']
        return poe_interface_power['interface-power-detail']
    except:
        return 'Non POE-switch'
def rebootPrimary(switch_ip):
    device = {
        "host": switch_ip,
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    logging.info("Logging in to switch {}".format(switch_ip))
    try:
        conn = Scrapli(**device)
        conn.open()
        response = conn.send_command("request system configuration rescue save")
        response = conn.send_interactive(
            [
                ("request system reboot slice alternate media internal at 22",
                "Reboot the system ", False),
                ("yes", "", False)
            ]
        )
        logging.info(response.elapsed_time)
        logging.info(response.result)
        if 'Shutdown at' in response.result:
            return True
        else:
            return False
        conn.close()
    except:
        logging.warning("Couldn't reboot switch {}".format(switch_ip))
        print("Couldn't reboot switch {}".format(switch_ip))
        return False
Exemple #4
0
def checkCable(switch_interface):
    device = {
        "host": switch_interface['SwitchIP'],
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    try:
        logging.info("Logging in to switch {} with IP {}".format(
            switch_interface['SwitchName'], switch_interface['SwitchIP']))
        conn = Scrapli(**device)
        conn.open()
        interface_test_status = 'Started'
        response = conn.send_command(
            "request diagnostics tdr start interface {}".format(
                switch_interface['PortName']))
        response = conn.send_command("show chassis hardware | display xml")
        switch_hardware_xml = str(response.result)
        response_dict = xmltodict.parse(switch_hardware_xml)
        response_json = json.dumps(response_dict)
        switch_hardware = json.loads(
            response_json)['rpc-reply']['chassis-inventory']['chassis']
        switch_model = switch_hardware['description']
        #print(switch_model)
        if "EX2300" in switch_model:
            while interface_test_status == 'Started':
                response = conn.send_command(
                    "show diagnostics tdr interface {} | display xml".format(
                        switch_interface['PortName']))
                response_dict = xmltodict.parse(response.result)
                response_json = json.dumps(response_dict)
                interface_tdr = json.loads(response_json)
                interface_test_status = interface_tdr['rpc-reply']['vct'][
                    'vct-interface-information-detail'][
                        'vct-interface-test-status']
        elif "EX2200" in switch_model:
            while interface_test_status == 'Started':
                response = conn.send_command(
                    "show diagnostics tdr interface {} | display xml".format(
                        switch_interface['PortName']))
                response_dict = xmltodict.parse(response.result)
                response_json = json.dumps(response_dict)
                interface_tdr = json.loads(response_json)
                interface_test_status = interface_tdr['rpc-reply']['tdr'][
                    'interface-information-detail']['interface-test-status']
        response = conn.send_command(
            "show diagnostics tdr interface {}".format(
                switch_interface['PortName']))
        return response.result
    except:
        #print("interface test didn't work", sys.exc_info()[0])
        return response.result
Exemple #5
0
def main():
    """
    Connect to a generic device and then commandeer that connection

    Generally this would be used for connecting to a terminal server, then doing *something* to
    connect to one of its downstream devices (i.e. access terminal server port 123 or whatever).
    Once on the console of the downstream device, we can "commandeer" this terminal server
    connection object and basically transform it into a connection object of the type (i.e. IOSXE)
    that we ultimately want.
    """
    # firstly we create the "outer"/"parent" connection -- this would be the connection to the
    # terminal server or similar device. generally this will be the `GenericDriver`, but there is
    # nothing stopping you from using any other driver type!
    term_server_conn = GenericDriver(**GENERIC_DEVICE)
    # open this connection
    term_server_conn.open()

    # here you would normally need to add some logic to get connected to the terminal server port or
    # to ssh from this "outer" device to the target device, in this example we're just ssh'ing to a
    # device using the generic driver then transforming that to the IOSXE driver so we dont need to
    # do anything

    # next create, but dont open, a connection for the target device type
    target_device_conn = Scrapli(**TARGET_DEVICE)

    # we can then call `commandeer` from the "inner"/"child" connection, passing it the connection
    # object of the "outer"/"parent"
    target_device_conn.commandeer(conn=term_server_conn)

    # we can confirm the "target_device_conn" is of course of type IOSXE (in this example), and that
    # we see the send_config methods of the *network* driver (rather than the parent connection not
    # having those config methods as it is *generic* driver type).
    print(type(target_device_conn), dir(target_device_conn))

    # we can acquire the config mode (which only the IOSXE driver would know how to do) to confirm
    # things are working as expected
    target_device_conn.acquire_priv("configuration")
    print(target_device_conn.get_prompt())
    target_device_conn.acquire_priv("privilege_exec")
    print(target_device_conn.get_prompt())

    # closing the "inner"/"child" connection will close the "outer"/"parent" connection, so if you
    # wish to keep using the outer connection.... dont close this one :)
    # target_device_conn.close()

    # if you dont close the inner connection, you can keep using the outer connection to do whatever
    # it is you need to do with it!
    print(term_server_conn.get_prompt())
def send_show(device, show_command):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(show_command)
            return reply.result
    except ScrapliException as error:
        print(error, device["host"])
Exemple #7
0
def send_show(device, commands, parse=True):
    if type(commands) == str:
        commands = [commands]
    host_output_dict = {}
    try:
        with Scrapli(**device) as conn:
            mresponse = conn.send_commands(commands)
            for cmd, res in zip(commands, mresponse):
                out = res.result
                if res.failed:
                    host_output_dict[cmd] = None
                else:
                    host_output_dict[cmd] = out
                    if parse:
                        parsed_out = res.textfsm_parse_output()
                        if parsed_out:
                            host_output_dict[cmd] = res.textfsm_parse_output()
            # mresponse.raise_for_status()
            return host_output_dict
    except ScrapliCommandFailure:
        raise
    except ScrapliException as error:
        print(device["host"], error)
    except socket.timeout as error:
        print(device["host"], error)
Exemple #8
0
def base_cfg_object():
    base = ScrapliCfgBase
    base.conn = Scrapli(host="localhost", platform="cisco_iosxe")
    cfg_conn = ScrapliCfgBase(config_sources=["running", "startup"])
    cfg_conn.on_prepare = None
    cfg_conn.ignore_version = True
    return cfg_conn
Exemple #9
0
def send_show(device, show_command):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(show_command)
            return reply.result
    except ScrapliException as error:
        logging.info(f"Error {error} on {device['host']}")
def send_cfg(device, cfg_commands):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_configs(cfg_commands)
            return reply.result
    except ScrapliException as error:
        print(error, device["host"])
Exemple #11
0
def send_show(device, show):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(show)
            return reply.result
    except ScrapliAuthenticationFailed:
        raise MyException("TEST")
    except ScrapliException as err:
        print(err)
Exemple #12
0
def send_show(device, show_commands):
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    with Scrapli(**device) as ssh:
        for cmd in show_commands:
            reply = ssh.send_command(cmd)
            cmd_dict[cmd] = reply.result
    return cmd_dict
Exemple #13
0
def send_show(device, command):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(command)
            output = reply.result
            reply.raise_for_status()
        return output
    except ScrapliCommandFailure:
        raise
    except ScrapliException as error:
        print(error, device["host"])
Exemple #14
0
def send_show(device, show_commands):
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    try:
        with Scrapli(**device) as ssh:
            for cmd in show_commands:
                reply = ssh.send_command(cmd)
                cmd_dict[cmd] = reply.result
        return cmd_dict
    except ScrapliException as error:
        print(error, device["host"])
def main():
    """
    Example demonstrating basic logging with scrapli

    In this example rather than dealing with python logging module directly, we simply import and
    call the `enable_basic_logging` function of the scrapli.logging package. This will apply logging
    formatting and handlers in an opinionated fashion -- so basically just use this for testing or
    for quickly getting logs, but do not use this for your custom applications.
    """
    with Scrapli(**MY_DEVICE) as conn:
        print(conn.get_prompt())
        print(conn.send_command("show run | i hostname").result)
def send_show(device, command):
    try:
        with Scrapli(**device) as conn:
            print(conn.get_prompt())
            # если добавить пароль на enable, то так можно перейти в enable
            # conn.acquire_priv("privilege_exec") # перейти в режим enable
            # print(conn.get_prompt())
            response = conn.send_command(command)
            out = response.result
            return out
    except ScrapliException as error:
        print(device["host"], error)
Exemple #17
0
def connect_ssh(device, command):
    host = device["host"]
    print(f">>> Connecting to {host}")
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(command)
            output = reply.result
            prompt = ssh.get_prompt()
            print(f"<<< Received output from {host}")
            hostname = re.search(r"(\S+)[>#]", prompt).group(1)
            return hostname, output
    except ScrapliException as error:
        print(f"Error connecting to {host}")
Exemple #18
0
def send_show(device, command):
    ip = device["host"]
    console.log(f"Подключаюсь к {ip}")
    try:
        with Scrapli(**device) as ssh:
            progress.update(t2, advance=1)
            console.log(f"Подключение успешно {ip}", style="success")
            reply = ssh.send_command(command)
            output = reply.result
            return output
    except ScrapliException as error:
        console.log(error, ip, style="fail")
        progress.update(t3, advance=1)
def send_show(device, show_command):
    try:
        with Scrapli(**device) as ssh:
            reply = ssh.send_command(show_command)
            return reply.result
    except ScrapliAuthenticationFailed as error:
        error_str = str(error).lower()
        if "no route to host" in error_str:
            print(error)
        elif "no matching key exchange" in error_str:
            print(error)
        else:
            print(error, device["host"])
Exemple #20
0
def checkLink(switch_interface):
    device = {
        "host": switch_interface['SwitchIP'],
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    logging.info("Logging in to switch {} with IP {}".format(
        switch_interface['SwitchName'], switch_interface['SwitchIP']))
    conn = Scrapli(**device)
    conn.open()
    response = conn.send_command("show interfaces terse {}".format(
        switch_interface['PortName']))
    interface_status = re.search(regex_interface_status, response.result)
    if 'up' in interface_status.group('link'):
        try:
            logging.info(
                "AP {} has ethernet link{} connected to {} on {} with IP {}".
                format(ap['Caption'], switch_interface['PortName'],
                       switch_interface['SwitchName'],
                       switch_interface['SwitchIP']))
            #print("AP interface status admin: {} link: {}".format(interface_status.group(
            #    'admin'), interface_status.group('link')))
            return True
        except:
            logging.info("AP has link but is down")
            return True
    else:
        logging.info(
            "AP has no ethernet link {} connected to {} on {} with IP {}".
            format(ap['Caption'], switch_interface['PortName'],
                   switch_interface['SwitchName'],
                   switch_interface['SwitchIP']))
        #print("AP interface status admin: {} link: {}".format(interface_status.group(
        #    'admin'), interface_status.group('link')))
        return False
def send_show(device, show_commands):
    host = device["host"]
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    logging.info(f">>> Connecting to {host}")
    try:
        with Scrapli(**device) as ssh:
            for cmd in show_commands:
                reply = ssh.send_command(cmd)
                cmd_dict[cmd] = reply.result
        logging.info(f"<<< Received output from {host}")
        return cmd_dict
    except ScrapliException as error:
        logging.error(f"{error} {host}")
def send_show(device, show_commands):
    ip = device["host"]
    console.log(f"Подключаюсь к {ip}")
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    try:
        with Scrapli(**device) as ssh:
            console.log(f"Подключение успешно {ip}", style="success")
            for cmd in show_commands:
                reply = ssh.send_command(cmd)
                cmd_dict[cmd] = reply.result
        return cmd_dict
    except ScrapliException as error:
        console.log(error, ip, style="fail")
Exemple #23
0
def send_show(device, show_commands):
    transport = device.get("transport") or "system"
    host = device.get("host")
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    print(f">>> Connecting to {host}")
    try:
        with Scrapli(**device) as ssh:
            for cmd in show_commands:
                reply = ssh.send_command(cmd)
                cmd_dict[cmd] = reply.result
        print(f"<<< Received output from {host}")
        return cmd_dict
    except (ScrapliException, SSHException, socket.timeout, OSError) as error:
        print(f"Device {host}, Transport {transport}, Error {error}")
Exemple #24
0
def test_pre_and_post_clear_config_sessions(eos_base_cfg_object, dummy_logger):
    eos_base_cfg_object.logger = dummy_logger
    eos_base_cfg_object.conn = Scrapli(host="localhost", platform="arista_eos")
    pre_response = eos_base_cfg_object._pre_clear_config_sessions()
    assert isinstance(pre_response, ScrapliCfgResponse)

    scrapli_response = Response(host="localhost",
                                channel_input="diff a config")
    post_response = eos_base_cfg_object._post_clear_config_sessions(
        response=pre_response, scrapli_responses=[scrapli_response])
    assert post_response.result == "failed to clear device configuration session(s)"

    scrapli_response.failed = False
    post_response = eos_base_cfg_object._post_clear_config_sessions(
        response=pre_response, scrapli_responses=[scrapli_response])
    assert post_response.result == "configuration session(s) cleared"
def send_show(device, show_commands):
    if type(show_commands) == str:
        show_commands = [show_commands]
    cmd_dict = {}
    try:
        with Scrapli(**device) as ssh:
            for cmd in show_commands:
                reply = ssh.send_command(cmd)
                parsed_data = reply.textfsm_parse_output()
                if parsed_data:
                    cmd_dict[cmd] = parsed_data
                else:
                    cmd_dict[cmd] = reply.result
        return cmd_dict
    except ScrapliException as error:
        print(error, device["host"])
def send_cfg(device, cfg_commands, strict=False):
    output = ""
    if type(cfg_commands) == str:
        cfg_commands = [cfg_commands]
    try:
        with Scrapli(**device) as ssh:
            reply = 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"])
Exemple #27
0
def bouncePOE(switch_interface):
    device = {
        "host": switch_interface['SwitchIP'],
        "auth_username": switch_username,
        "auth_password": switch_password,
        "auth_strict_key": False,
        "platform": "juniper_junos"
    }
    logging.info("Logging in to switch {} with IP {}".format(
        switch_interface['SwitchName'], switch_interface['SwitchIP']))
    conn = Scrapli(**device)
    conn.open()
    response = conn.send_config("set poe interface {} disable".format(
        switch_interface['PortName']))
    response = conn.send_config("commit confirmed 2 comment netscripts01")
    logging.info(response.elapsed_time)
    logging.info(response.result)
    conn.close()
Exemple #28
0
def send_cfg(device, commands, stop_on_error=True):
    if type(commands) == str:
        commands = [commands]
    try:
        with Scrapli(**device) as conn:
            mresponse = conn.send_configs(commands,
                                          stop_on_failed=stop_on_error)
            for r in mresponse:
                if r.failed:
                    print(
                        f"Возникла ошибка при выполнении команды {r.channel_input}"
                        f"{r.result}")
            return mresponse.result
    except ScrapliException as error:
        print(device["host"], error)
    except socket.timeout as error:
        print(device["host"], error)
def send_show(device, command):
    ip = device["host"]
    console.log(f"Подключаюсь к {ip}")
    live.update(generate_stats_table(stats_data))  # Rich
    try:
        with Scrapli(**device) as ssh:
            stats_data["success"] += 1
            console.log(f"Подключение успешно {ip}", style="success")
            reply = ssh.send_command(command)
            output = reply.result
        return output
    except ScrapliAuthenticationFailed as error:
        console.log(error, ip, style="fail")
        if "Timed out connecting to host" in str(error):
            stats_data["failed to connect"] += 1
        else:
            stats_data["auth error"] += 1
Exemple #30
0
def main():
    """Demo basic selective config replace functionality"""

    # load up a config to use for the candidate config; this config is a bit different though! take
    # a look and you'll see that there are no ethernet interfaces! how can we do a config replace
    # if we have no configuration on any of our ethernet ports?!?! Easy! We can just drop a flag
    # in the configuration that looks an awful lot like a jinja2 variable, in this case:
    # "{{ ethernet_interfaces }}" -- all we need to do is tell scrapli_cfg how to match (from the
    # actual running config) what *should* go in this section (see the next comment section!)
    with open("config", "r", encoding="utf-8") as f:
        my_config = f.read()

    # in this example we have a `dedicated_connection` which means that the scrapli connection is
    # just for scrapli-cfg, when setting `dedicated_connection` to True scrapli cfg will auto open
    # and close the scrapli connection when using a context manager -- or when calling `prepare`
    # and `cleanup`.
    with ScrapliCfgEOS(conn=Scrapli(**DEVICE),
                       dedicated_connection=True) as cfg_conn:
        # the scrapli cfg `render_substituted_config` method accepts a template config, and a list
        # of "substitutes" -- these substitutes are a tuple of the "tag" that needs to be replaced
        # with output from the real device, and a regex pattern that "pulls" this section from the
        # actual device itself. In other words; the "{{ ethernet_interfaces }}" section will be
        # replaced with whatever the provided pattern finds from the real device. clearly the trick
        # here is being good with regex so you can properly snag the section from the real device.
        # In this case there are a handful of already built "patterns" in scrapli cfg you can use,
        # like this ETHERNET_INTERFACES pattern that matches all ethernet interfaces on a device
        # (on a veos at least!) NOTE: this will likely have some changes soon, this is the alpha
        # testing of this!
        rendered_config = cfg_conn.render_substituted_config(
            config_template=my_config,
            substitutes=[("ethernet_interfaces", ETHERNET_INTERFACES)])
        cfg_conn.load_config(config=rendered_config, replace=True)

        diff = cfg_conn.diff_config()
        print(diff.device_diff)
        print(diff.side_by_side_diff)
        print(diff.side_by_side_diff)

        cfg_conn.commit_config()