How to use the netmiko.ConnectHandler function in netmiko

To help you get started, we’ve selected a few netmiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ktbyers / pyplus_course / bonus2 / collateral / PYTEST / test3 / test_netmiko.py View on Github external
def netmiko_conn():
    net_connect = ConnectHandler(
        host="cisco3.lasthop.io",
        device_type="cisco_ios",
        username="pyclass",
        password=getpass(),
    )
    return net_connect
github admiralspark / NetSpark-Scripts / Example_Scripts / Cisco / automatedtftpBackups.py View on Github external
reader = csv.DictReader(csvfile)

        for row in reader:
            hostname = row['SysName']
            device_type = row['device_type']
            ip = row['IP_Address']
            switch = {
                'device_type': device_type,
                'ip': ip,
                'username': username,
                'password': password,
                'secret': secret,
                'verbose': False,
            }

            net_connect = ConnectHandler(**switch)

            # Insert enables et al here
            net_connect.enable()

            # Temporary variable, need raw input later
            change_number = "1"
            # Then command strings
            net_connect.send_command('send log "Starting change ticket {}"'.format(change_number))
            iphost = net_connect.send_command("sh run | inc ip host tftp")
            archive = net_connect.send_command("sh run | inc archive")
            kronpolicy = net_connect.send_command("sh run | inc kron policy-list BACKUP-CONFIG")
            kronoccur = net_connect.send_command("sh run | inc kron occurrence DAILY-CONFIG-BACKUP")

            print("\n\n>>>>>>>>> Device {0} <<<<<<<<<\n".format(row['SysName']))
            if iphost == "":
                net_connect.config_mode()
github ktbyers / netmiko / examples / asa_upgrade.py View on Github external
ip_addr = input("Enter ASA IP address: ")
    my_pass = getpass()
    start_time = datetime.now()
    print(">>>> {}".format(start_time))

    net_device = {
        'device_type': 'cisco_asa',
        'ip': ip_addr,
        'username': 'admin',
        'password': my_pass,
        'secret': my_pass,
        'port': 22,
    }

    print("\nLogging in to ASA")
    ssh_conn = ConnectHandler(**net_device)
    print()

    # ADJUST TO TRANSFER IMAGE FILE
    dest_file_system = 'disk0:'
    source_file = 'test1.txt'
    dest_file = 'test1.txt'
    alt_dest_file = 'asa825-59-k8.bin'

    with FileTransfer(ssh_conn, source_file=source_file, dest_file=dest_file,
                      file_system=dest_file_system) as scp_transfer:

        if not scp_transfer.check_file_exists():
            if not scp_transfer.verify_space_available():
                raise ValueError("Insufficient space available on remote device")

            print("Enabling SCP")
github afourmy / eNMS / pynms / scheduling / models.py View on Github external
def netmiko_job(script, username, password, ips, driver, global_delay_factor):
    for ip_address in ips:
        netmiko_handler = ConnectHandler(                
            ip = ip_address,
            device_type = driver,
            username = username,
            password = password,
            global_delay_factor = global_delay_factor
            )
        netmiko_handler.send_config_set(script.splitlines())
github twr14152 / Network-Automation-Scripts_Python3 / netmiko / netmiko_show_cmds.py View on Github external
def run_script(host_ip):
    ios_rtr = {
        "device_type": "cisco_ios",
        "ip": host_ip,
        "username": uname,
        "password": passwd,
        }
    #connect to the device via ssh
    net_connect = ConnectHandler(**ios_rtr)
    #print the device IP or Hostname
    print("Connected to host:", host_ip)
    #this for loop is used to iterate through the show commands
    for show_commands in cmds:
        output = net_connect.send_command(show_commands)
        print("Connected to host:", host_ip)
        print(output)
        print('\n---- Elapsed time=', time()-starting_time)
github networktocode / pyntc / pyntc / devices / aireos_device.py View on Github external
def open(self):
        if self.connected:
            try:
                self.native.find_prompt()
            except:  # noqa E722
                self.connected = False

        if not self.connected:
            self.native = ConnectHandler(
                device_type="cisco_wlc",
                ip=self.host,
                username=self.username,
                password=self.password,
                port=self.port,
                global_delay_factor=self.global_delay_factor,
                secret=self.secret,
                verbose=False,
            )
            self.connected = True
github ktbyers / python_course / bonus_lesson_examples / collateral / os_upgrade / upgrade_device_alt.py View on Github external
def upgrade_device(net_device):

    start_time = datetime.now()

    print()
    print("Upgrading OS on device: {}".format(net_device['host']))
    print("-" * 50)

    # Extract file and file system variables
    file_system = net_device.pop('file_system')
    source_file = net_device.pop('source_file')
    dest_file = net_device.pop('dest_file')

    # Establish SSH control channel
    print(".establishing SSH connection.")
    ssh_conn = ConnectHandler(**net_device)

    # SCP new image file
    print(".transferring image file.")
    enable_transfer = True
    if enable_transfer:
        transfer_dict = file_transfer(ssh_conn, source_file=source_file, dest_file=dest_file,
                                      file_system=file_system, direction='put',
                                      overwrite_file=False)
    else:
        transfer_dict = {}

    # Check the file exists and the MD5 matches the source file
    if not transfer_dict.get('file_exists') or not transfer_dict.get('file_verified'):
        raise ValueError("File doesn't exist or MD5 doesn't match on the remote system")

    print(".verifying new image file.")
github ktbyers / scp_sidecar / ansible_modules / cisco_config_replace.py View on Github external
merge_file=dict(required=True),
            dest_file_system=dict(default='flash:', required=False),
        ),
        supports_check_mode=False
    )

    net_device = {
        'device_type': 'cisco_ios',
        'ip': module.params['host'],
        'username': module.params['username'],
        'password': module.params['password'],
        'port': int(module.params['port']),
        'verbose': False,
    }

    ssh_conn = ConnectHandler(**net_device)
    ssh_conn.enable()

    merge_file = module.params['merge_file']
    dest_file_system = module.params['dest_file_system']

    # Disable file copy confirmation
    ssh_conn.send_config_set(['file prompt quiet'])

    # Perform configure replace
    cmd = "configure replace {0}{1}".format(dest_file_system, merge_file)
    output = ssh_conn.send_command(cmd, delay_factor=8)

    # Enable file copy confirmation
    ssh_conn.send_config_set(['file prompt alert'])

    if 'The rollback configlet from the last pass is listed below' in output:
github slemire / sshpoller / sshpoller.py View on Github external
def connect(self):
        """ Connects SSH session """

        try:
            self.sock = ConnectHandler(
                device_type=self.device_type,
                ip=self.hostname,
                port=self.port,
                username=self.username,
                password=self.password)
            logging.debug('Connection to %s successful!' % self.hostname)
            self.prompt = self.sock.find_prompt()

            if self.prompt:
                logging.debug('Prompt found: %s' % self.prompt)

                # Send commands after login that won't be parsed
                if self.precommand_list:
                    for precommand in self.precommand_list:
                        self.sock.send_command(precommand)
            else: