Python netmiko.ConnectHandler() Examples
The following are 30
code examples of netmiko.ConnectHandler().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
netmiko
, or try the search function
.
Example #1
Source File: conftest.py From pyplus_course with Apache License 2.0 | 9 votes |
def netmiko_connect(request): """Connect to arista1 and return connection object""" password = os.getenv("PYNET_PASSWORD") if os.getenv("PYNET_PASSWORD") else getpass() arista1 = { "device_type": "arista_eos", "host": "arista1.lasthop.io", "username": "pyclass", "password": password, } net_connect = ConnectHandler(**arista1) def fin(): net_connect.disconnect() request.addfinalizer(fin) return net_connect
Example #2
Source File: tasks.py From network-programmability-stream with MIT License | 9 votes |
def switch_interface(device_id: str, interface_name: str, enable_interface: str) -> Any: device = Device.objects.get(pk=device_id) config_commands = [f'interface {interface_name}'] result = {"interface_name": interface_name} if enable_interface == 'False': config_commands.append(' shutdown') result["up"] = False else: config_commands.append(' no shutdown') result["up"] = True conn_params = { 'ip': device.host, 'username': device.username, 'password': device.password, 'device_type': device.netmiko_device_type, } with ConnectHandler(**conn_params) as device_conn: device_conn.send_config_set(config_commands) return result
Example #3
Source File: ex7_netmiko.py From pynet with Apache License 2.0 | 8 votes |
def main(): ''' Use Netmiko to change the logging buffer size on pynet-rtr2. ''' password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False net_connect = ConnectHandler(**pynet2) config_commands = ['logging buffered 20000'] net_connect.send_config_set(config_commands) output = net_connect.send_command("show run | inc logging buffer") print print '#' * 80 print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print '#' * 80 print
Example #4
Source File: ex6_netmiko.py From pynet with Apache License 2.0 | 8 votes |
def main(): ''' Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx ''' password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False print "\nStart time: " + str(datetime.now()) for a_device in (pynet1, pynet2, juniper_srx): net_connect = ConnectHandler(**a_device) output = net_connect.send_command("show arp") print print '#' * 80 print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print '#' * 80 print print "\nEnd time: " + str(datetime.now())
Example #5
Source File: spark_threaded.py From NetSpark-Scripts with GNU General Public License v3.0 | 7 votes |
def switch_run_config(username, password, secret, devicetype, ipaddr, hostname, clicomm): '''All the logic happens here. Take the data, process it, print results''' sessiondict = { 'device_type': devicetype, 'ip': ipaddr, 'username': username, 'password': password, 'secret': secret, 'verbose': False } try: # Start the session, enable, send the commands, capture terminal output and remove the connections session = netmiko.ConnectHandler(**sessiondict) session.enable() session_return = session.send_config_set(COMMANDLIST) session.disconnect() except (netmiko.ssh_exception.NetMikoTimeoutException): session_return = "----------DEVICE CONNECTION FAILED----------" # Fancy formatting here for results print("\n\n>>>>>>>>> {0} {1} <<<<<<<<<\n".format(hostname, ipaddr) + session_return + "\n>>>>>>>>> End <<<<<<<<<\n")
Example #6
Source File: ex8_netmiko.py From python_course with Apache License 2.0 | 7 votes |
def main(): """ Use Netmiko to change the logging buffer size and to disable console logging from a file for both pynet-rtr1 and pynet-rtr2 """ password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False for a_device in (pynet1, pynet2): net_connect = ConnectHandler(**a_device) net_connect.send_config_from_file(config_file='config_file.txt') # Verify configuration output = net_connect.send_command("show run | inc logging") print() print('#' * 80) print("Device: {}:{}".format(net_connect.ip, net_connect.port)) print() print(output) print('#' * 80) print()
Example #7
Source File: ex6_netmiko.py From python_course with Apache License 2.0 | 7 votes |
def main(): """Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.""" password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False print("\nStart time: " + str(datetime.now())) for a_device in (pynet1, pynet2, juniper_srx): net_connect = ConnectHandler(**a_device) output = net_connect.send_command("show arp") print() print('#' * 80) print("Device: {}:{}".format(net_connect.ip, net_connect.port)) print() print(output) print('#' * 80) print() print("\nEnd time: " + str(datetime.now()))
Example #8
Source File: ex8_proc_w_queue.py From python_course with Apache License 2.0 | 7 votes |
def show_version_queue(a_device, output_q): ''' Use Netmiko to execute show version. Use a queue to pass the data back to the main process. ''' output_dict = {} creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='', verbose=False) output = ('#' * 80) + "\n" output += remote_conn.send_command_expect("show version") + "\n" output += ('#' * 80) + "\n" output_dict[a_device.device_name] = output output_q.put(output_dict)
Example #9
Source File: ex7_netmiko.py From python_course with Apache License 2.0 | 7 votes |
def main(): """Use Netmiko to change the logging buffer size on pynet-rtr2.""" password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False net_connect = ConnectHandler(**pynet2) config_commands = ['logging buffered 20000'] net_connect.send_config_set(config_commands) output = net_connect.send_command("show run | inc logging buffer") print() print('#' * 80) print("Device: {}:{}".format(net_connect.ip, net_connect.port)) print() print(output) print('#' * 80) print()
Example #10
Source File: gather_commands_sync.py From network-programmability-stream with MIT License | 7 votes |
def collect_outputs(devices, commands): """ Collects commands from the dictionary of devices Args: devices (dict): dictionary, where key is the hostname, value is netmiko connection dictionary commands (list): list of commands to be executed on every device Returns: dict: key is the hostname, value is string with all outputs """ for device in devices: hostname = device.pop("hostname") connection = netmiko.ConnectHandler(**device) device_result = ["{0} {1} {0}".format("=" * 20, hostname)] for command in commands: command_result = connection.send_command(command) device_result.append("{0} {1} {0}".format("=" * 20, command)) device_result.append(command_result) device_result_string = "\n\n".join(device_result) connection.disconnect() yield device_result_string
Example #11
Source File: ex6_threads_show_ver.py From python_course with Apache License 2.0 | 7 votes |
def show_version(a_device): ''' Execute show version command using Netmiko ''' creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='') print() print('#' * 80) print(remote_conn.send_command_expect("show version")) print('#' * 80) print() remote_conn.disconnect()
Example #12
Source File: connection.py From insightconnect-plugins with MIT License | 7 votes |
def connect_key(self, params={}): home_dir = (path.expanduser('~')) key_file = "{}/.ssh".format(home_dir) f = params.get('key').get('privateKey') fb = f.get('content') fb64 = base64.b64decode(fb) fb64 = fb64.decode("utf-8") if not path.exists(key_file): os.makedirs(key_file) os.chmod(key_file, 0o700) key_file_path = path.join(key_file, "id_rsa") with open(key_file_path, 'w+') as f: f.write(fb64) os.chmod(key_file_path, 0o600) self.logger.info("Establishing connection") device = {'device_type': params.get('device_type'), 'ip': params.get('host'), 'username': params.get('credentials').get('username'), 'use_keys': True, 'key_file': key_file_path, 'password': params.get('credentials').get('password'), 'port': params.get('port'), 'secret': params.get('secret').get('secretKey'), 'allow_agent': True, 'global_delay_factor': 4} self.device_connect = ConnectHandler(**device) return self.device_connect
Example #13
Source File: collection_threading.py From network-programmability-stream with MIT License | 7 votes |
def get_mac_address_table(host): device_params = GLOBAL_DEVICE_PARAMS.copy() device_params['ip'] = host device_conn = ConnectHandler(**device_params) parsed_values = dict() parsed_values.update(parse_show_version(device_conn.send_command('show version'))) parsed_values.update(parse_show_mac_address_table(device_conn.send_command('show mac address-table'))) result = '{hostname} MAC address table:\n{mac_address_table}'.format(**parsed_values) device_conn.disconnect() return result
Example #14
Source File: ex9_netmiko.py From pynet with Apache License 2.0 | 7 votes |
def worker_cmd(a_device, mp_queue, cmd='show arp'): ''' Return a dictionary where the key is the device identifier Value is (success|fail(boolean), return_string) ''' identifier = '{ip}:{port}'.format(**a_device) return_data = {} try: net_connect = ConnectHandler(**a_device) output = net_connect.send_command(cmd) return_data[identifier] = (True, output) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put(return_data)
Example #15
Source File: ex5_netmiko.py From pynet with Apache License 2.0 | 7 votes |
def main(): ''' Using Netmiko enter into configuration mode on a network device. Verify that you are currently in configuration mode. ''' password = getpass() for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password net_connect2 = ConnectHandler(**pynet2) net_connect2.config_mode() print "\n>>>>" print "Checking pynet-rtr2 is in configuration mode." print "Config mode check: {}".format(net_connect2.check_config_mode()) print "Current prompt: {}".format(net_connect2.find_prompt()) print ">>>>\n"
Example #16
Source File: send_script_window.py From pyNMS with GNU General Public License v3.0 | 7 votes |
def send_script(self): config = self.script_content_edit.toPlainText() for node in self.nodes: # log in to the device credentials = self.network.get_credentials(node) connection_parameters = { 'device_type': node.netmiko_operating_system, 'ip': node.ip_address, # credentials to log in to the device 'username': credentials['username'], 'password': credentials['password'], 'secret': credentials['enable_password'] } netmiko_connection = ConnectHandler(**connection_parameters) # turn the script into a Jinja2 template j2_config = Template(config).render(**node.__dict__) # send the script line per line for line in j2_config.splitlines(): netmiko_connection.send_command(line) netmiko_connection.disconnect()
Example #17
Source File: netmiko_mod.py From napalm-salt with Apache License 2.0 | 7 votes |
def _prepare_connection(**kwargs): ''' Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. ''' init_args = {} fun_kwargs = {} netmiko_kwargs = __salt__['config.get']('netmiko', {}) netmiko_kwargs.update(kwargs) # merge the CLI args with the opts/pillar netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__) check_self = netmiko_init_args.pop(0) for karg, warg in six.iteritems(netmiko_kwargs): if karg not in netmiko_init_args: if warg is not None: fun_kwargs[karg] = warg continue if warg is not None: init_args[karg] = warg conn = ConnectHandler(**init_args) return conn, fun_kwargs # ----------------------------------------------------------------------------- # callable functions # -----------------------------------------------------------------------------
Example #18
Source File: netmiko_px.py From napalm-salt with Apache License 2.0 | 7 votes |
def init(opts): ''' Open the connection to the network device managed through netmiko. ''' proxy_dict = opts.get('proxy', {}) opts['multiprocessing'] = proxy_dict.get('multiprocessing', False) netmiko_connection_args = proxy_dict.copy() netmiko_connection_args.pop('proxytype', None) netmiko_device['always_alive'] = netmiko_connection_args.pop('always_alive', opts.get('proxy_always_alive', True)) try: connection = ConnectHandler(**netmiko_connection_args) netmiko_device['connection'] = connection netmiko_device['initialized'] = True netmiko_device['args'] = netmiko_connection_args netmiko_device['up'] = True if not netmiko_device['always_alive']: netmiko_device['connection'].disconnect() except NetMikoTimeoutException as t_err: log.error('Unable to setup the netmiko connection', exc_info=True) except NetMikoAuthenticationException as au_err: log.error('Unable to setup the netmiko connection', exc_info=True) return True
Example #19
Source File: iosxr.py From pyiosxr with Apache License 2.0 | 7 votes |
def open(self): """ Open a connection to an IOS-XR device. Connects to the device using SSH and drops into XML mode. """ try: self.device = ConnectHandler(device_type='cisco_xr', ip=self.hostname, port=self.port, username=self.username, password=self.password, **self.netmiko_kwargs) self.device.timeout = self.timeout self._xml_agent_alive = True # successfully open thus alive except NetMikoTimeoutException as t_err: raise ConnectError(t_err.args[0]) except NetMikoAuthenticationException as au_err: raise ConnectError(au_err.args[0]) self._cli_prompt = self.device.find_prompt() # get the prompt self._enter_xml_mode()
Example #20
Source File: load_bgp_config_part2.py From pynet with Apache License 2.0 | 7 votes |
def main(): device_list = [cisco_ios, cisco_xr, arista_veos] start_time = datetime.now() print for a_device in device_list: net_connect = ConnectHandler(**a_device) net_connect.enable() print "{}: {}".format(net_connect.device_type, net_connect.find_prompt()) if check_bgp(net_connect): print "BGP currently configured" else: print "No BGP" print print "Time elapsed: {}\n".format(datetime.now() - start_time)
Example #21
Source File: ex6_threads_show_ver.py From pynet with Apache License 2.0 | 7 votes |
def show_version(a_device): ''' Execute show version command using Netmiko ''' creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='') print print '#' * 80 print remote_conn.send_command_expect("show version") print '#' * 80 print remote_conn.disconnect()
Example #22
Source File: ex8_netmiko.py From pynet with Apache License 2.0 | 7 votes |
def main(): ''' Use Netmiko to change the logging buffer size and to disable console logging from a file for both pynet-rtr1 and pynet-rtr2 ''' password = getpass() # Get connection parameters setup correctly for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password a_dict['verbose'] = False for a_device in (pynet1, pynet2): net_connect = ConnectHandler(**a_device) net_connect.send_config_from_file(config_file='config_file.txt') # Verify configuration output = net_connect.send_command("show run | inc logging") print print '#' * 80 print "Device: {}:{}".format(net_connect.ip, net_connect.port) print print output print '#' * 80 print
Example #23
Source File: exercise2_with_threads.py From python_course with Apache License 2.0 | 7 votes |
def scp_file(net_device): # Make a copy of the dictionary since we modify it device_dict = net_device.copy() file_system = device_dict.pop('file_system') # Create the Netmiko SSH connection ssh_conn = ConnectHandler(**device_dict) # Transfer the IOS image to device source_file = "my_file.txt" dest_file = "my_file.txt" transfer_dict = file_transfer( ssh_conn, source_file=source_file, dest_file=dest_file, file_system=file_system, direction='put', overwrite_file=False, ) md5_check = transfer_dict['file_verified'] file_exists = transfer_dict['file_exists'] if md5_check and file_exists: print("File successfully transferred to: {host}".format(**net_device)) else: print("Failure on SCP: {host} !!!".format(**net_device)) ssh_conn.disconnect()
Example #24
Source File: connection.py From insightconnect-plugins with MIT License | 6 votes |
def connect_password(self, params={}): self.logger.info("Establishing connection") device = {'device_type': params.get('device_type'), 'ip': params.get('host'), 'username': params.get('credentials').get('username'), 'password': params.get('credentials').get('password'), 'port': params.get('port'), 'secret': params.get('secret').get('secretKey'), 'global_delay_factor': 4} self.device_connect = ConnectHandler(**device) return self.device_connect
Example #25
Source File: ex7_processes_show_ver.py From python_course with Apache License 2.0 | 6 votes |
def show_version(a_device): ''' Execute show version command using Netmiko ''' creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='') print() print('#' * 80) print(remote_conn.send_command_expect("show version")) print('#' * 80) print()
Example #26
Source File: netmiko-vault.py From network-programmability-stream with MIT License | 6 votes |
def get_outputs(device_info: Dict[str, str], commands: Sequence[str]) -> Dict[str, str]: result = {} with ConnectHandler(**device_info) as device_conn: for command in commands: result[command] = device_conn.send_command(command) return result
Example #27
Source File: collection_serial.py From network-programmability-stream with MIT License | 6 votes |
def get_mac_address_table(host): device_params = GLOBAL_DEVICE_PARAMS.copy() device_params['ip'] = host device_conn = ConnectHandler(**device_params) parsed_values = dict() parsed_values.update(parse_show_version(device_conn.send_command('show version'))) parsed_values.update(parse_show_mac_address_table(device_conn.send_command('show mac address-table'))) result = '{hostname} MAC address table:\n{mac_address_table}'.format(**parsed_values) device_conn.disconnect() return result
Example #28
Source File: exercise2.py From python_course with Apache License 2.0 | 6 votes |
def main(): password = getpass() hostnames = [ 'arista1.twb-tech.com', 'arista2.twb-tech.com', 'arista3.twb-tech.com', 'arista4.twb-tech.com', ] for host in hostnames: net_device = create_device_dict(host, password) file_system = net_device.pop('file_system') # Create the Netmiko SSH connection ssh_conn = ConnectHandler(**net_device) print() print(">>>>>") print(ssh_conn.find_prompt()) # Transfer the IOS image to device source_file = "my_file.txt" dest_file = "my_file.txt" transfer_dict = file_transfer( ssh_conn, source_file=source_file, dest_file=dest_file, file_system=file_system, direction='put', overwrite_file=False, ) md5_check = transfer_dict['file_verified'] file_exists = transfer_dict['file_exists'] if md5_check and file_exists: print("File successfully transferred to: {host}".format(**net_device)) else: print("Failure on SCP: {host} !!!".format(**net_device)) print(">>>>>")
Example #29
Source File: exercise3.py From python_course with Apache License 2.0 | 6 votes |
def main(): password = getpass() filename = 'my_devices.yml' my_devices = read_yaml(filename) for hostname, net_device in my_devices.items(): file_system = net_device.pop('file_system') net_device['password'] = password # Create the Netmiko SSH connection ssh_conn = ConnectHandler(**net_device) print() print(">>>>>") print(ssh_conn.find_prompt()) # Transfer the IOS image to device source_file = "my_file.txt" dest_file = "my_file.txt" transfer_dict = file_transfer( ssh_conn, source_file=source_file, dest_file=dest_file, file_system=file_system, direction='put', overwrite_file=False, ) md5_check = transfer_dict['file_verified'] file_exists = transfer_dict['file_exists'] if md5_check and file_exists: print("File successfully transferred to: {host}".format(**net_device)) else: print("Failure on SCP: {host} !!!".format(**net_device)) print(">>>>>")
Example #30
Source File: ex5_db_show_version.py From python_course with Apache License 2.0 | 6 votes |
def show_version(a_device): """Execute show version command using Netmiko.""" creds = a_device.credentials remote_conn = ConnectHandler(device_type=a_device.device_type, ip=a_device.ip_address, username=creds.username, password=creds.password, port=a_device.port, secret='') print() print('#' * 80) print(remote_conn.send_command_expect("show version")) print('#' * 80) print()