def execute(device, commands, outputDirectory):
    executionStatus = False
    reasonForFailure = "NA"
    executionProtocol = "SSH"

    try:
        logging.info('verifying the existence of the output folder : %s',
                     outputDirectory)
        if not os.path.exists(outputDirectory):
            logging.info(
                'outputDirectory : %s not available, so creating one...')
            os.mkdir(outputDirectory)

        logging.info('started...')
        net_connect = Netmiko(**device)
        hostname = str(net_connect.find_prompt())[:-1]
        logging.info('prompt identified as : %s', net_connect.find_prompt())
        output = 'Device IP : ' + device['host'] + '\n'

        logging.info(
            'completed executing command, redirecting to output file %s',
            outFileName)
        outFile = open(outFileName, 'w')
        outFile.write(output)
        outFile.flush()
        outFile.close()
        logging.info('completed... disconnecting...')
        net_connect.disconnect()
    except:
        logging.error('exception in thread function for %s ip , stack : %s',
                      threading.currentThread().getName(),
                      traceback.extract_stack())
        raise
def send_config_command(device, config_commands):
    net_connect = Netmiko(**device)
    net_connect.find_prompt()
    net_connect.config_mode(config_command='configure private')
    if net_connect.check_config_mode():
        for c in config_commands:
            output = net_connect.send_config_set(c, exit_config_mode=False)
            if 'syntax error' in output:
                print('''Command "{}" error!
{}
'''.format(c, output)[:-23])
                if exit_or_continue():
                    break
            elif 'missing argument' in output:
                print('''Command "{}" error!
{}
'''.format(c, output)[:-23])
                if exit_or_continue():
                    break
            elif 'invalid interface type in' in output:
                print('''Command "{}" error!
{}
'''.format(c, output)[:-23])
                if exit_or_continue():
                    break

        net_connect.send_config_set("show | compare", exit_config_mode=False)
        net_connect.commit(and_quit=True)
    
    net_connect.disconnect()
def gatewayconnect(target,username,password):
    try:
        net_connect = Netmiko(host=target,username=username,password=password,device_type='cisco_asa', timeout=3)
        net_connect.find_prompt()
    except:
        net_connect = False

    return net_connect
Exemple #4
0
def ssh_verify(host, username, password, device_type):
    try:
        net_connect = Netmiko(host=host,
                              username=username,
                              password=password,
                              device_type=device_type,
                              timeout=5)
        net_connect.find_prompt()
        print("Verification successful!")
        return True
    except Exception as e:
        print(e)
        return None
Exemple #5
0
def test_login():
    global net_conn             # Make connection variable global so can be used in all functions

    while True:
        try:
            device = input("Enter IP of the ASA firewall: ")
            username = input("Enter your username: ")
            password = getpass()
            net_conn = Netmiko(host=device, username=username, password=password, device_type='cisco_asa')
            net_conn.find_prompt()      # Expects to recieve prompt back from access switch
            break
        except Exception as e:              # If login fails loops to begining with the error message
            print(e)

    gather_info()                   # Runs next function
Exemple #6
0
def config_applier():
    config = open("configs.txt")
    devicelist = []
    device = open("device_generated.txt")
    username = input("Input device username: "******"Input device password: "******"Input device secret: ")

    for line in device:
        line = line.rstrip()
        devicelist.append(line)

    config_set = config

    for host in devicelist:
        net_connect = Netmiko(host,
                              username=username,
                              password=password,
                              device_type="cisco_nxos",
                              secret=secret)

        print(net_connect.find_prompt())
        print(net_connect.enable())

        output = net_connect.send_config_set(config_set)
        print(net_connect.send_config_set(config_set))
        print(net_connect.save_config())
        print(net_connect.disconnect())

        with open("audit.txt", "a") as f:
            f.write(output)

    print("See 'audit.txt' for confirmation of process")
Exemple #7
0
def getHostInfo(host, user, passwd):
    net_connect = Netmiko(
        host, username=user, password=passwd, device_type="juniper_junos"
    )

    commands = [
        "show version | no-more",
        "show system alarms | no-more",
        "show chassis alarms | no-more",
        "show interfaces terse | match inet | match up",
        "show route 0.0.0.0",
        "request system storage cleanup dry-run | no-more",
        "show system storage detail | no-more",
        "show system config rescue | no-more",
    ]

    print("Logging in as " + user)
    print("*" * 30)
    print(net_connect.find_prompt())
    print()

    for command in commands:
        print("*" * 30)
        print("Sending command: " + command)
        print(net_connect.send_command(command))

    print("*" * 30)
    print("Logging out and closing session . . .")
    net_connect.disconnect()
def ciscoasacon(ipaddr, username, password, secret, networknodetype):
    if secret == "none":
        CiscoASAConnectNoEnable = {
            "host": ipaddr,
            "username": username,
            "password": password,
            "device_type": networknodetype}
        net_connect = Netmiko(**CiscoASAConnectNoEnable)  # This is where it connect with SSH for no enable/secret

    elif secret != "none":
        CiscoASAConnectWithEnable = {
            "host": ipaddr,
            "username": username,
            "secret": secret,
            "password": password,
            "device_type": networknodetype}
        net_connect = Netmiko(**CiscoASAConnectWithEnable)  # This is where it connect with SSH

    print("\n")

    print(net_connect.find_prompt())
    print(net_connect.enable())
    print(net_connect.send_command("sh clock"))
    clock = net_connect.send_command("sh clock")
    print(net_connect.send_command("sh int ip brief"))
    interfaces = net_connect.send_command("sh int ip brief")
    shrun = net_connect.send_command("sh run")
    print(net_connect.send_command("sh run"))

    net_connect.disconnect()
    writetohdd(interfaces, shrun)
Exemple #9
0
def detect(device):
    net_connect = Netmiko(**device)
    commands = [
        "show cpu", "show temperat", "sho fan", "sho power", "sho ip rout",
        "show cloc", "ls", "sho ip interface", "show mem pool", "sho devic",
        "show versi", "sho ip int", "sho run inc sub 8908"
    ]
    # print(net_connect.find_prompt())
    with open(path, 'a+') as f:
        for command in commands:
            info = net_connect.send_command(command)
            print("Finished!\n", net_connect.find_prompt())
            f.write(
                str(info) + '\n===========' + net_connect.find_prompt() +
                '===========\n')
    net_connect.disconnect()
Exemple #10
0
def run_cmds(host, username, password, cmds):
    homedir = os.path.dirname(os.path.realpath(__file__))
    print(host, username, password)
    net_connect = Netmiko(host=host,
                          username=username,
                          password=password,
                          device_type="cisco_ios",
                          timeout=30)
    hostname = net_connect.find_prompt()
    hostname = re.sub('#', '', hostname)
    net_connect.send_command("term len 0")
    for cmd in cmds:
        print("\t", cmd)
        try:
            cmd_output = net_connect.send_command(cmd, hostname)
            net_connect.read_until_prompt_or_pattern()
            timestr = time.strftime("%Y%m%d-%H%M%S")
            filename = os.path.join(homedir,
                                    hostname + "_OUTPUT_" + timestr + ".txt")
            cmd_output = cmd_output.strip()
            if cmd_output != "":
                print(cmd_output.strip())
            """
            if 'hostname' in cmd_output:
                text_file = open(filename, "w")
                text_file.write(cmd_output)
                text_file.close()
                print("  output file saved as:", filename)
            else:
                print("  output file was NOT saved for:", host)
            """
        except Exception as e:
            print("ERROR EXECUTING", cmd, "on host: ", host)
            print(e)
Exemple #11
0
def main():
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')

    # Get input from user
    while True:
        try:
            subnets = input(
                "Enter a subnet(s) (CIDR notation, space delimited): ").split(
                )
            for i in range(0, len(subnets)):
                subnets[i] = ipaddress.IPv4Network(subnets[i])
        except:
            if input(
                    "Invalid data entered. Press any key to continue or 'q' to quit. "
            ) == 'q':
                exit()
        else:
            break

    if len(subnets) > 0:

        # gather username and password
        cisco_user = input("Device Username: "******"Device Password: "******"Please wait while inventory report is being generated")

        # Open csv file for write operation
        with open(f'{os.getcwd()}/discovered_switches_{timestamp}.csv',
                  'w') as csv_file:
            report_writer = csv.writer(csv_file,
                                       delimiter=',',
                                       quotechar='"',
                                       quoting=csv.QUOTE_MINIMAL)
            report_writer.writerow(['Hostname', 'IP Address', 'Model'])
            for subnet in subnets:
                for ip in subnet.hosts():

                    # Create connection object for Netmiko
                    conn = {
                        "host": str(ip),
                        "username": cisco_user,
                        "password": cisco_pass,
                        "device_type": "cisco_ios",
                    }

                    # Attempt connection
                    try:
                        net_connect = Netmiko(**conn)
                        vers = net_connect.send_command('show version')
                    except:
                        print(f"Error connecting to {str(ip)}")

                    else:
                        hostname = net_connect.find_prompt().split('#')[0]
                        model = net_connect.send_command(
                            'show inventory | inc PID').splitlines()[0].split(
                                ',')[0].lstrip('PID:').strip()
                        report_writer.writerow([hostname, str(ip), model])
                        net_connect.disconnect()
                        print(f"Completed successfully on {str(ip)}")
Exemple #12
0
def ARP(j):
    net_conn = Netmiko(**j)
    print(net_conn.find_prompt())
    if j['device_type'] == 'juniper_junos':
        cmd = "show arp"
    else:
        cmd = "show ip arp"
    return net_conn.send_command(cmd)
def main():
    while True:
        try:
            dev_ips = input("Destination IP or IPs (space delimited): ").split()
            for i in range(0, len(dev_ips)):
                dev_ips[i] = ipaddress.IPv4Address(dev_ips[i])
            add_ips = input("SNMP Manager IP(s) to add (space delimited): ").split()
            for i in range(0, len(add_ips)):
                add_ips[i] = ipaddress.IPv4Address(add_ips[i])
            #rem_ips = input("SNMP Manager IP(s) to remove (space delimited): ").split()
            #for i in range(0, len(rem_ips)):
                #rem_ips[i] = ipaddress.IPv4Address(rem_ips[i])
        except:
            if input("Invalid data entered. Press any key to continue or 'q' to quit. ") == 'q':
                exit()
        else:
            break

    if len(add_ips) > 0 or len(rem_ips) > 0:
        # gather username and password
        cisco_user = input("username: "******"Please wait while the update is being performed")
        
        # Create Connection object for Netmiko
        for ip in dev_ips:
            conn = {
                "host": str(ip).rstrip("\n"),
                "username": cisco_user,
                "password": cisco_pass,
                "device_type": "cisco_ios",
            }

            # Attempt the connection
            try:
                net_connect = Netmiko(**conn)
                vers = net_connect.send_command('show version')
            except:
                print(f"Connection to {ip} failed")
            else:
                hostname = net_connect.find_prompt().split('#')[0]
                # Special handling for Nexus
                if "Nexus" in vers:
                    #add handling for nexus switches here
                    pass
                acl = net_connect.send_command('show running-config | inc snmp-server community bstar')
                if acl == "":
                    acl = net_connect.send_command('show running-config | inc snmp-server community GIpublicD')
                #for i in rem_ips:
                    #net_connect.send_config_set(['interface vlan '+vlan, rem_comm+str(i)])
                for i in add_ips:
                    net_connect.send_config_set([f"access-list {acl.split()[-1]} permit {i}"])
                
                # Save config and disconnect session
                net_connect.save_config()
                net_connect.disconnect()
                print(f"Successfully updated SNMP ACL on {hostname}")
Exemple #14
0
def ssh_command(j, cmd="show version"):
    print("#" * 80)
    net_conn = Netmiko(**j)
    print(net_conn.find_prompt())
    output = net_conn.send_command(cmd)
    net_conn.disconnect()
    print(output)
    print("#" * 80)
    return output
Exemple #15
0
def simpleConnect(ip):  # Values within need to be changed for functionality!
    node = {
    "host": (ip),
    "username": userName,
    "password": userPass,
    "device_type": "cisco_ios",}

    try:
        net_connect = Netmiko(**node)
        hostname = (net_connect.find_prompt())
        net_connect.find_prompt()
        sleep(1)
        if '#' not in (net_connect.find_prompt()):  # Checking for enable mode
            net_connect.write_channel("en" + "\r")
            net_connect.write_channel(userPass + "\r")  # Passing in credentials for enable mode
        print(net_connect.read_channel())
        sleep(1)
        print(net_connect.read_channel())
        output = net_connect.send_command('show inventory') # Change me and ball-out
        sleep(1)
        print(output)
        if "2960x" in output:  # Change me and ball-out
            print ("\n\n\n\t\t\t" +hostname+ " is a 2960x model switch!")
            results.write(hostname+ " is a 2960x model switch!\n")
            sleep(1)
            checkfunc = net_connect.send_command('test interfaces vlan 1')
            print (checkfunc)
            if "No IP address" in checkfunc:  # Change me and ball-out
                print ("\n\t" + hostname + " VLAN 1 has no IP address!\n")
                results.write(hostname +" VLAN 1 has no IP address!\n")
            else:
                pass
        if "2901" in output:  # Change me and ball-out
            print ("\n\n\n\t\t\t" +hostname+ " is a 2901 router!")
            results.write(hostname+ " is a 2901 router!\n")
            sleep(1)
        if "% Invalid" in output:  # Change me and ball-out
            print("Syntax Error! Check compatibility for CLI command!")
            results.write(hostname + " experienced a ***Syntax Error!***\n")
        sleep(1)
        net_connect.disconnect()

    except:
        print("*Authentication Error!*")
Exemple #16
0
def print_prompt(ip_addr, username):
    my_device = {
        'host': ip_addr,
        'username': username,
        'password': getpass(),
        'device_type': 'cisco_ios'
    }

    net_conn = Netmiko(**my_device)
    print(net_conn.find_prompt())
    net_conn.disconnect()
Exemple #17
0
def send_config_command(device, config_commands):
    net_connect = Netmiko(**device)
    output = net_connect.find_prompt()
    output += net_connect.config_mode(config_command='configure private')
    if net_connect.check_config_mode():
        output += net_connect.send_config_set(config_commands, exit_config_mode=False)
        output += net_connect.send_config_set("show | compare", exit_config_mode=False)
        output += net_connect.commit(and_quit=True)
        print(output)
    
    net_connect.disconnect()
Exemple #18
0
def conn(device):

    ##    guesser = SSHDetect(**device)
    ##    best_match = guesser.autodetect()
    ##    print(best_match)  # Name of the best device_type to use further
    ##    print(guesser.potential_matches)  # Dictionary of the whole matching result

    device["device_type"] = "linux"
    connection = Netmiko(**device)
    print(connection.find_prompt())
    out = connection.send_command("man man", expect_string="MAN")
    print(out)
    writetxt(out)
    return device
Exemple #19
0
def ssh_get_mac(device_type):
    global inventory
    global mac_table_all
    table_header = [
        'DESTINATION_ADDRESS', 'TYPE', 'VLAN', 'DESTINATION_PORT', 'HOSTNAME'
    ]
    homedir = os.path.dirname(os.path.realpath(__file__))
    homedir = os.path.join(homedir, 'mac')
    if not os.path.exists(homedir):
        os.makedirs(homedir)
    for device in inventory[device_type]:
        table = []
        host = device['host']
        username = device['username']
        password = device['password']
        try:
            print("Retrieving MAC table for:", host)
            net_connect = Netmiko(host=host,
                                  username=username,
                                  password=password,
                                  device_type=device_type,
                                  timeout=10)
            hostname = net_connect.find_prompt()
            hostname = re.sub('#', '', hostname)
            net_connect.send_command("term len 0", use_textfsm=False)
            cmd_output = net_connect.send_command("show mac address-table",
                                                  use_textfsm=False)
            re_table = textfsm.TextFSM(io.StringIO(fsm[device_type]['mac']))
            cmd_output = re_table.ParseText(cmd_output)

            if "ailed" not in cmd_output:
                print(" Success!: ", cmd_output[0], "more...")
                for mac_entry in cmd_output:
                    mac_entry.append(hostname)
                    table.append(mac_entry)
                table = sorted(table, key=None, reverse=False)
                filename = os.path.join(
                    homedir, hostname + "_mac_" +
                    time.strftime("%Y%m%d-%H%M%S") + ".csv")
                write_csv(table_header, table, filename)
            else:
                print(" Failed!:\n", cmd_output)
        except Exception as e:
            print(e)
        mac_table_all = mac_table_all + table
    filename = os.path.join(
        homedir, "all_mac_" + time.strftime("%Y%m%d-%H%M%S") + ".csv")
    mac_table_all = sorted(mac_table_all, key=None, reverse=False)
    write_csv(table_header, mac_table_all, filename)
Exemple #20
0
def main():
    my_device = {
        'host': 'ios-xe-mgmt.cisco.com',
        'username': '******',
        'password': '',
        'device_type': 'cisco_ios',
        'port': 8181
    }

    net_connect = Netmiko(**my_device)

    output = net_connect.find_prompt()
    print(output)

    net_connect.disconnect()
def call(ip_add,cmd):
        ip=ip_add
        cmd=cmd
        ios_ssh= {
                'device_type':'cisco_ios',
                'username':'******',
                'password':'******',
                'ip':ip,
                }

        net_connect = Netmiko(**ios_ssh)
        print(net_connect.find_prompt())
        #config_commands=['do sh ip int br | i 2/1']
        config_commands=cmd
        output=net_connect.send_config_set(config_commands)
Exemple #22
0
def make_connection_to_device():
    '''Helper invoked from main() to set up a netmiko connection to the
    device, and put it into enable mode'''

    # access the netrc to read the credentials
    try:
        rc = netrc.netrc()
    except FileNotFoundError as e:
        print('(Failed to access netrc file for gathering ',
              'login credentials: {})'.format(str(e)), file=sys.stderr)
        sys.exit(-1)

    netmiko_device_info = {}
    netmiko_device_info['host'] = DESIRED_SETTINGS['device']
    netmiko_device_info['device_type'] = 'cisco_ios'

    try:
        host = netmiko_device_info['host']
        (login, enable_password, password) = rc.authenticators(host)
    except TypeError:
        print('No entry in netrc file for device "{}", and no default '
              'either.'.format(netmiko_device_info['host']), file=sys.stderr)
        sys.exit(-1)

    # Fill in the user name / password / enable password device_info
    # attributes from the info we read from .netrc
    netmiko_device_info['username'] = login
    netmiko_device_info['password'] = password
    if enable_password:
        netmiko_device_info['secret'] = enable_password

    print('Connecting to device_info "{}"...'.format(
        netmiko_device_info['host']), end='', flush=True)

    device = Netmiko(**netmiko_device_info)
    print('connected.')

    print('Entering enable mode...', end='', flush=True)
    device.enable()
    print('done.')

    prompt = device.find_prompt()
    print('Prompt is "{}"'.format(prompt))

    return device
Exemple #23
0
def main():
    net_connect = Netmiko(
        conf.host,
        username=conf.username,
        password=conf.password,
        device_type=conf.device_type,
    )

    # command = "show ip int brief"
    # command = "show interfaces description"
    command = "show mac-address-table"

    print()
    print(net_connect.find_prompt())
    output = net_connect.send_command(command)
    type(output)
    net_connect.disconnect()
    print(output)
    print()
Exemple #24
0
def worker(host, jobs):
    """ Обработчик заданий
    """
    device = {
        "device_type": "cisco_ios",
        "host": host,
        "username": USERNAME,
        "password": PASSWORD,
        "secret": SECRET
    }
    con = Netmiko(**device)

    if con.find_prompt():
        device = {"con": con, "host": host}
        result = [host]
        for job in jobs:
            result.append(job(**device))
        return result
    else:
        return "Не удалось подключиться к f{host}"
Exemple #25
0
def main():

    my_device = {
        'host': 'ios-xe-mgmt.cisco.com',
        'username': '******',
        'password': '',
        'device_type': 'cisco_ios',
        'port': 8181
    }

    net_connect = Netmiko(**my_device)
    prompt = net_connect.find_prompt()
    output = net_connect.send_command_timing("delete bootflash:macdb.txt",
                                             strip_prompt=False,
                                             strip_command=False)
    while prompt not in output:
        output += net_connect.send_command_timing('n')
    print(output)

    net_connect.disconnect()
Exemple #26
0
def ssh_show_run(device_type):
    global inventory
    homedir = os.path.dirname(os.path.realpath(__file__))
    homedir = os.path.join(homedir, 'config')
    if not os.path.exists(homedir):
        os.makedirs(homedir)
    try:
        iter(inventory[device_type])
    except Exception as e:
        return False  # no good yaml content found
    for device in inventory[device_type]:
        host = device['host']
        username = device['username']
        password = device['password']
        try:
            print("Saving configration file for:", host)
            net_connect = Netmiko(host=host,
                                  username=username,
                                  password=password,
                                  device_type=device_type,
                                  timeout=10)
            hostname = net_connect.find_prompt()
            hostname = re.sub('#', '', hostname)
            net_connect.send_command("term len 0", use_textfsm=False)
            cmd_output = net_connect.send_command("show run",
                                                  use_textfsm=False)
            timestr = time.strftime("%Y%m%d-%H%M%S")
            filename = os.path.join(homedir,
                                    hostname + "_CONFIG_" + timestr + ".txt")
            if 'hostname' in cmd_output:
                text_file = open(filename, "w")
                text_file.write(cmd_output)
                text_file.close()
                print("  Saved Configuration files as:", filename)
            else:
                print("  Configration file was NOT saved for:", host)
        except Exception as e:
            print("  Configration file was NOT saved for:", host)
            print(e)
Exemple #27
0
def Conectar_Equipamento(ip, device_type='-', comando='\n'):

    try:
        dados_conexao = {
            "host": ip,
            "username": usuario,
            "password": senha,
            "device_type": device_type,
            "banner_timeout": 100,
            "timeout": 100
        }

        if dados_conexao['device_type'] == '-':
            dados_conexao['device_type'] = 'autodetect'
            guesser = SSHDetect(**dados_conexao)
            best_match = guesser.autodetect()
            print('Equipamento {} é do tipo: {}'.format(dados_conexao['host'], best_match))
            dados_conexao["device_type"] = best_match
        net_connect = Netmiko(**dados_conexao)
        prompt = net_connect.find_prompt()

        # if device_type=='huawei':
        #     print(net_connect.disable_paging(command='screen-length 0 temporary'))

        info_equip = net_connect.send_command(comando).splitlines()

        return info_equip

    except (NetMikoAuthenticationException) as e:
        print('Falha ao conectar ao equipamento {}. {} '.format(ip, e))
        # output = ['', '-']

    except (NetMikoTimeoutException, Exception) as e:
        print('Falha ao conectar ao equipamento {}. {} '.format(ip, e))
        # output = ['', '-']
        #
    return None
Exemple #28
0
    'host': 'cisco1.twb-tech.com',
    'username': '******',
    'password': password,
    'device_type': 'cisco_ios',
}

cisco2 = {
    'host': 'cisco2.twb-tech.com',
    'username': '******',
    'password': password,
    'device_type': 'cisco_ios',
}

nxos1 = {
    'host': 'nxos1.twb-tech.com',
    'username': '******',
    'password': password,
    'device_type': 'cisco_nxos',
}

srx1 = {
    'host': 'srx1.twb-tech.com',
    'username': '******',
    'password': password,
    'device_type': 'juniper_junos',
}

for device in (cisco1, cisco2, nxos1, srx1):
    net_connect = Netmiko(**device)
    print(net_connect.find_prompt())
from netmiko import Netmiko

connection_object = Netmiko(host='192.168.1.254',
                            username='******',
                            password='******',
                            device_type='cisco_asa',
                            secret="cisco")
#calling netmiko function, it has usual attributes and plust device_type attribute which tell on whcich vendor we would connect to.
output = connection_object.send_command('show version')
print(output)
promt_object = connection_object.find_prompt()
print(promt_object)
connection_object.config_mode()
promt_object = connection_object.find_prompt()
print(promt_object)
connection_object.send_command('username test1 password test privilege 15')
output = connection_object.send_command("show run user")
print(output)
connection_object.disconnect()
Exemple #30
0
#!/usr/bin/env python
from __future__ import print_function, unicode_literals

# Netmiko is the same as ConnectHandler
from netmiko import Netmiko
from getpass import getpass

my_device = {
    'host': "host.domain.com",
    'username': '******',
    'password': getpass(),
    'device_type': 'cisco_ios',
}

net_connect = Netmiko(**my_device)
# Ensure in enable mode
net_connect.enable()
print(net_connect.find_prompt())

net_connect.disconnect()
Exemple #31
0
"""
1. Using Netmiko, establish a connection to a network device and print out the device's prompt.
"""
from netmiko import Netmiko

# Create dictionary that holds device details
cisco_device = {
    'host': 'sbx-iosxr-mgmt.cisco.com',
    'username': '******',
    'password': '******',
    'device_type': 'cisco_xr',
    'port': 8181
}

# Establish SSH connection to the network device using **kwargs to pull in details from dictionary
net_connection = Netmiko(**cisco_device)
# Get the devices prompt
output = net_connection.find_prompt()
# Print prompt to console
print(output)

# Gracefully disconnect from SSH session
net_connection.disconnect()
Exemple #32
0
#!/usr/bin/env python
from netmiko import SSHDetect, Netmiko
from getpass import getpass

device = {
    'device_type': 'autodetect',
    'host': 'cisco1.twb-tech.com', 
    'username': '******', 
    'password': getpass(), 
}

guesser = SSHDetect(**device)
best_match = guesser.autodetect()
print(best_match)                   # Name of the best device_type to use further
print(guesser.potential_matches)    # Dictionary of the whole matching result

device['device_type'] = best_match
connection = Netmiko(**device)

print(connection.find_prompt())