def worker_config_cmds(a_device, mp_queue): ''' Return a dictionary where the key is the device identifier Value is (success|fail(boolean), return_string) ''' try: a_device['port'] except KeyError: a_device['port'] = 22 identifier = '{ip}:{port}'.format(**a_device) return_data = {} SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) config_cmds = net_connect.send_config_set(config, delay_factor=.3) print "configuration pushed to: " + a_device["ip"] except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put(return_data) return None return_data[identifier] = (True, config_cmds) mp_queue.put(return_data)
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'sf-arista-sw4', 'user_exec_prompt': 'sf-arista-sw4>', 'enable_prompt': 'sf-arista-sw4#', 'interface_ip': '10.220.88.31', 'config_mode': '(config)', } SSHClass = netmiko.ssh_dispatcher(arista_veos_sw['device_type']) net_connect = SSHClass(**arista_veos_sw) # Enter enable mode module.prompt_initial = net_connect.find_prompt() net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Send a set of config commands module.config_mode = net_connect.config_mode() config_commands = [ 'logging buffered 20000', 'logging buffered 20010', 'no logging console' ] net_connect.send_config_set(config_commands) # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command( 'show run | inc logging buffer') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'openstack-rb5', 'config_mode': '(config)', } SSHClass = netmiko.ssh_dispatcher(brocade_vdx['device_type']) net_connect = SSHClass(**brocade_vdx) # Enter enable mode module.prompt_initial = net_connect.find_prompt() net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Send a set of config commands module.config_mode = net_connect.config_mode() config_commands = [ 'logging raslog console WARNING', 'interface vlan 20', 'banner motd test_message' ] net_connect.send_config_set(config_commands) # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command('show vlan brief') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'sf-arista-sw4', 'user_exec_prompt' : 'sf-arista-sw4>', 'enable_prompt' : 'sf-arista-sw4#', 'interface_ip' : '10.220.88.31', 'config_mode' : '(config)', } SSHClass = netmiko.ssh_dispatcher(arista_veos_sw['device_type']) net_connect = SSHClass(**arista_veos_sw) # Enter enable mode module.prompt_initial = net_connect.find_prompt() net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Send a set of config commands module.config_mode = net_connect.config_mode() config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console'] net_connect.send_config_set(config_commands) # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command('show run | inc logging buffer') net_connect.disconnect()
def ssh_manager(net_device): ''' args -> network device mappings returns -> ssh connection ready to be used ''' try: SSHClient = netmiko.ssh_dispatcher( device_type=net_device["device_type"]) try: conn = SSHClient(**net_device) connected = True except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: # if routerDict.verbose: # print("could not connect to {}, due to {}".format( # net_device["ip"], e)) connected = False except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: # if routerDict.verbose: # print("could not connect to {}, due to {}".format( # net_device["ip"], e)) connected = False try: if connected: yield conn else: yield False finally: if connected: conn.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'root@pynet-jnpr-srx1', 'router_prompt' : 'root@pynet-jnpr-srx1>', 'router_conf_mode' : 'root@pynet-jnpr-srx1#', 'interface_ip' : '10.220.88.39', } show_ver_command = 'show version' multiple_line_command = 'show configuration' module.basic_command = 'show interfaces terse' SSHClass = netmiko.ssh_dispatcher(juniper_srx['device_type']) net_connect = SSHClass(**juniper_srx) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Test buffer clearing net_connect.remote_conn.send(show_ver_command) time.sleep(2) net_connect.clear_buffer() # Should not be anything there on the second pass module.clear_buffer_check = net_connect.clear_buffer()
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt' : 'vna1ds1-sf#', 'router_enable' : 'vna1ds1-sf#', 'interface_ip' : '10.3.3.245', 'config_mode' : '(config)' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_nxos['device_type']) net_connect = SSHClass(**cisco_nxos) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.router_prompt_initial = net_connect.router_prompt net_connect.enable() module.router_prompt = net_connect.router_prompt module.config_mode = net_connect.config_mode() config_commands = ['logging monitor 3', 'logging monitor 7', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command("show run | inc 'logging monitor'") net_connect.disconnect()
def worker_show_command(target_device, command, return_data_queue): ''' For a given target device, execute a show command and store the output in a queue as a value in a dictionary, with the key being the target device name. :param target_device: A dict containing parameters for the device we're running the command against :param return_data_queue: A queue containing output and the hostname :return: ''' device_ip_port = "{ip}:{port}".format(**target_device) return_data = {} ''' return_data is a dict {} identifier is a string in the "ip_addr:port" format (this is the key) return_data[identifier] stores a value, which is a tuple in the form (True|False, "string output from show cmd") True if the attempt worked, with output from the command, and False if attempt failed, with error string return_data = { 'ip:port': '(True|False),"show cmd output"' } ''' SSHClass = netmiko.ssh_dispatcher(target_device['device_type']) try: device_connection = SSHClass(**target_device) show_cmd_output = device_connection.send_command(command) return_data[device_ip_port] = (True, show_cmd_output) except (NetMikoTimeoutException, NetMikoAuthenticationException) as conn_except: return_data[device_ip_port] = (False, conn_except) return_data_queue.put(return_data)
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'xe-test-rtr#', 'base_prompt' : 'xe-test-rtr', 'interface_ip' : '172.30.0.167', 'config_mode' : '(config)', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xe['device_type']) net_connect = SSHClass(**cisco_xe) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) net_connect.enable() module.enable_prompt = net_connect.find_prompt() module.config_mode = net_connect.config_mode() config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command('show run | inc logging buffer') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'pynet-rtr1', 'interface_ip' : '10.220.88.20' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(device_type=cisco_881['device_type']) net_connect = SSHClass(**cisco_881) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt module.show_ip_alt = net_connect.send_command_expect(module.basic_command) module.show_version_alt = net_connect.send_command_expect(show_ver_command) # Test buffer clearing net_connect.remote_conn.send(show_ver_command) time.sleep(2) net_connect.clear_buffer() # Should not be anything there on the second pass module.clear_buffer_check = net_connect.clear_buffer()
def worker_commands(a_device, mp_queue): try: a_device['port'] except KeyError: a_device['port'] = 22 identifier = '{ip}'.format(**a_device) return_data = {} cmd = '' command_jnpr = 'show configuration protocols mpls | display set' command_csco = 'show running-config formal interface | i tunnel' SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) if net_connect.device_type == 'juniper': cmd = net_connect.send_command(command_jnpr) elif net_connect.device_type == 'cisco_ios': cmd = net_connect.send_command(command_csco) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = False # Add data to the queue (for parent process) mp_queue.put(return_data) return None #print cmd return_data[identifier] = pytricia.PyTricia() return_data[identifier] = generate_json(cmd, identifier, net_connect.device_type) mp_queue.put(return_data)
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt' : 'pynet-rtr1>', 'router_enable' : 'pynet-rtr1#', 'interface_ip' : '10.220.88.20', 'config_mode' : '(config)', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_881['device_type']) net_connect = SSHClass(**cisco_881) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.router_prompt_initial = net_connect.router_prompt net_connect.enable() module.router_prompt = net_connect.router_prompt module.config_mode = net_connect.config_mode() config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command('show run | inc logging buffer') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt': 'vna1ds1-sf#', 'router_enable': 'vna1ds1-sf#', 'interface_ip': '10.3.3.245', 'config_mode': '(config)' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_nxos['device_type']) net_connect = SSHClass(**cisco_nxos) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.router_prompt_initial = net_connect.router_prompt net_connect.enable() module.router_prompt = net_connect.router_prompt module.config_mode = net_connect.config_mode() config_commands = [ 'logging monitor 3', 'logging monitor 7', 'no logging console' ] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command( "show run | inc 'logging monitor'") net_connect.disconnect()
def worker_show_version(a_device, mp_queue): ''' Return a dictionary where the key is the device identifier Value is (success|fail(boolean), return_string) ''' try: a_device['port'] except KeyError: a_device['port'] = 22 identifier = '{ip}:{port}'.format(**a_device) return_data = {} show_ver_command = 'show version' SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) show_version = net_connect.send_command(show_ver_command) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put(return_data) return None return_data[identifier] = (True, show_version) mp_queue.put(return_data)
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'root@pynet-jnpr-srx1', 'router_prompt': 'root@pynet-jnpr-srx1>', 'router_conf_mode': 'root@pynet-jnpr-srx1#', 'interface_ip': '10.220.88.39', } show_ver_command = 'show version' multiple_line_command = 'show configuration' module.basic_command = 'show interfaces terse' SSHClass = netmiko.ssh_dispatcher(juniper_srx['device_type']) net_connect = SSHClass(**juniper_srx) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command( multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Test buffer clearing net_connect.remote_conn.send(show_ver_command) time.sleep(2) net_connect.clear_buffer() # Should not be anything there on the second pass module.clear_buffer_check = net_connect.clear_buffer()
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt': 'xe-test-rtr>', 'router_enable': 'xe-test-rtr#', 'interface_ip': '172.30.0.167', 'config_mode': '(config)', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xe['device_type']) net_connect = SSHClass(**cisco_xe) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.router_prompt_initial = net_connect.router_prompt net_connect.enable() module.router_prompt = net_connect.router_prompt module.config_mode = net_connect.config_mode() config_commands = [ 'logging buffered 20000', 'logging buffered 20010', 'no logging console' ] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command( 'show run | inc logging buffer') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'pynet-rtr1', 'interface_ip' : '10.220.88.20' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(device_type=cisco_881['device_type']) net_connect = SSHClass(**cisco_881) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt module.show_ip_alt = net_connect.send_command_expect(module.basic_command) module.show_version_alt = net_connect.send_command_expect(show_ver_command) # Test buffer clearing net_connect.remote_conn.sendall(show_ver_command) time.sleep(2) net_connect.clear_buffer() # Should not be anything there on the second pass module.clear_buffer_check = net_connect.clear_buffer()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'pynet-rtr1', 'user_exec_prompt' : 'pynet-rtr1>', 'enable_prompt' : 'pynet-rtr1#', 'interface_ip' : '10.220.88.20', 'config_mode' : '(config)', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_881['device_type']) net_connect = SSHClass(**cisco_881) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.prompt_initial = net_connect.find_prompt() net_connect.enable() module.enable_prompt = net_connect.find_prompt() module.config_mode = net_connect.config_mode() config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console'] net_connect.send_config_set(config_commands) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command('show run | inc logging buffer') module.exit_enable_mode = net_connect.exit_enable_mode() net_connect.disconnect()
def backup_configs(a_device, mp_queue): ''' Copying Config to TFTP Server Return a dictionary where the key is the device identifier Value is (success|fail(boolean), return_string, name_of_device) ''' identifier = '{ip}'.format(**a_device) return_data = {} # backup_to_tftp_result = [] SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) hostname = net_connect.find_prompt() tftp_command = 'copy running-config tftp://{0}/{1}-{2}-config'.format(tftp,hostname[:-1],a_device['ip']); backup_to_tftp_result = net_connect.send_command_timing(tftp_command) if '[' in backup_to_tftp_result: backup_to_tftp_result += net_connect.send_command_timing("\n") if '[' in backup_to_tftp_result: backup_to_tftp_result += net_connect.send_command_timing("\n") except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put(return_data) return None return_data[identifier] = (True, backup_to_tftp_result) mp_queue.put(return_data)
def command_runner(dispatcher, cmd): """Run show version on many devices.""" # Prepare the dispatcher dsp = netmiko.ssh_dispatcher(dispatcher["device_type"]) # Run the dispatcher and get the device ready dev = dsp(**dispatcher) # returns the output of the variable `cmd` that was passed return dev.send_command(cmd)
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'root@pynet-jnpr-srx1', 'router_prompt' : 'root@pynet-jnpr-srx1>', 'router_conf_mode' : 'root@pynet-jnpr-srx1#', 'interface_ip' : '10.220.88.39', 'config_mode' : '[edit', } show_ver_command = 'show version' multiple_line_command = 'show configuration' module.basic_command = 'show interfaces terse' SSHClass = netmiko.ssh_dispatcher(juniper_srx['device_type']) net_connect = SSHClass(**juniper_srx) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt_initial = net_connect.base_prompt module.config_mode = net_connect.config_mode() module.base_prompt = net_connect.base_prompt config_commands = [ 'set system syslog archive size 110k files 3', 'set system syslog archive size 120k files 3', 'set system time-zone America/New_York', ] net_connect.send_config_set(config_commands, commit=True) module.exit_config_mode = net_connect.exit_config_mode() module.config_commands_output = net_connect.send_command('show configuration | match time-zone') # Test a manual commit net_connect.config_mode() net_connect.send_command('set system time-zone America/Los_Angeles') net_connect.commit() net_connect.exit_config_mode() module.manual_commit = net_connect.send_command('show configuration | match time-zone') # Test that prompt is stripped correctly from config mode net_connect.config_mode() net_connect.send_command('edit services') module.show_version_from_config = net_connect.send_command('run show version') print "*** SHOW VERSION: {0}".format(module.show_version_from_config) net_connect.exit_config_mode() net_connect.disconnect()
def connect(self): self.is_connected = False try: SSHClass = netmiko.ssh_dispatcher(self.device_class) username = self.credentials.username password = self.credentials.password ssh = SSHClass(ip=self.device_name, username=username, password=password) self.conn = ssh is_connected = True except Exception as e: print("failed to connect to device {}, error was {}. Appending it to failed".format(self.device_name, e)) return self.is_connected
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'RP/0/0/CPU0:XRv-1', 'interface_ip' : '169.254.254.181' } show_ver_command = 'show version' module.basic_command = 'show ipv4 int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xr['device_type']) net_connect = SSHClass(**cisco_xr) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'xe-test-rtr', 'interface_ip': '172.30.0.167', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xe['device_type']) net_connect = SSHClass(**cisco_xe) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'xe-test-rtr', 'interface_ip' : '172.30.0.167', } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xe['device_type']) net_connect = SSHClass(**cisco_xe) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'n7k1', 'interface_ip': '10.3.3.245' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_nxos['device_type']) net_connect = SSHClass(**cisco_nxos) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'n7k1', 'interface_ip' : '10.3.3.245' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(cisco_nxos['device_type']) net_connect = SSHClass(**cisco_nxos) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'device_type' : 'BIG-IP', 'pool_name' : 'Ltm::Pool: TEST', } show_sys_command = 'tmsh show sys version' multiple_line_command = 'tmsh show sys log ltm' module.basic_command = 'tmsh show ltm pool TEST' SSHClass = netmiko.ssh_dispatcher(f5_ltm_1['device_type']) net_connect = SSHClass(**f5_ltm_1) module.show_version = net_connect.send_command(show_sys_command) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=2) module.show_pool = net_connect.send_command(module.basic_command)
def crawl_branch_wan(device): class_mapper = { '26' : 'cisco_asa', '5' : 'cisco_ios', '30' : 'cisco_ios', } SSHClient = netmiko.ssh_dispatcher(class_mapper[device.split('.')[-1]]) try: print 'connecting to {}'.format(device) ssh = SSHClient(ip=device, username=creds.username, password=creds.password, secret=creds.password) except (AuthenticationException, gaierror, SSHException, NetMikoAuthenticationException, NetMikoTimeoutException, ValueError) as e: print 'Failed to connect to {} due to {}'.format(device, e) return False output = ssh.send_command("show version", delay_factor=3) serial = find_serial_number(output) version = find_os_version(output) name = find_device_name(output) model = find_model(output) new_dev = NetworkDevice( device_name = name, ip_address = device, credentials = creds, ssh_port = 22, vendor = 'Cisco', model = model, device_class = class_mapper[device.split('.')[-1]]+'_ssh', domain = 'nfcu.net', serial_number = serial, os_version = version, ) try: new_dev.save() except django.db.utils.IntegrityError as e: print "The following device does NOT have a name {}".format(device) print name, device, model, serial, version return True
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt': 'twb-py-lab#', 'router_enable': 'twb-py-lab#', 'interface_ip': '10.220.88.1', 'config_mode': '(config)', } show_ver_command = 'show version' multiple_line_command = 'show version' module.basic_command = 'show ip' SSHClass = netmiko.ssh_dispatcher(cisco_asa['device_type']) net_connect = SSHClass(**cisco_asa) # ASA enters enable mode as part of connection (disable paging is # a config-mode command) module.router_prompt = net_connect.router_prompt # Test connection successful module.show_version = net_connect.send_command(show_ver_command) # Test output paging module.multiple_line_output = net_connect.send_command( multiple_line_command) # Test sending a show command module.show_ip = net_connect.send_command(module.basic_command) # Send a set of config commands config_commands = [ 'logging buffered notifications', 'logging buffered warnings', 'no logging console' ] net_connect.send_config_set(config_commands) # Enter/exit config mode module.config_mode = net_connect.config_mode() module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command( 'show run | inc logging buffer') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'sf-arista-sw4', 'interface_ip' : '10.220.88.31' } show_ver_command = 'show version' multiple_line_command = 'show logging' module.basic_command = 'show ip int brief' SSHClass = netmiko.ssh_dispatcher(arista_veos_sw['device_type']) net_connect = SSHClass(**arista_veos_sw) module.show_version = net_connect.send_command(show_ver_command, delay_factor=2) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=4) module.show_ip = net_connect.send_command(module.basic_command, delay_factor=2) module.base_prompt = net_connect.base_prompt
def setup_module(module): module.EXPECTED_RESPONSES = { 'device_type': 'BIG-IP', 'pool_name': 'Ltm::Pool: TEST', } show_sys_command = 'tmsh show sys version' multiple_line_command = 'tmsh show sys log ltm' module.basic_command = 'tmsh show ltm pool TEST' SSHClass = netmiko.ssh_dispatcher(f5_ltm_1['device_type']) net_connect = SSHClass(**f5_ltm_1) module.show_version = net_connect.send_command(show_sys_command) module.multiple_line_output = net_connect.send_command( multiple_line_command, delay_factor=2) module.show_pool = net_connect.send_command(module.basic_command)
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'openstack-rb5', 'interface_ip' : '10.254.8.8', } show_ver_command = 'show version' multiple_line_command = 'show interface' module.basic_command = 'show system' SSHClass = netmiko.ssh_dispatcher(brocade_vdx['device_type']) net_connect = SSHClass(**brocade_vdx) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command(multiple_line_command) module.show_system = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt
def show_interfaces(a_device, mp_queue): debug = True return_data = {} show_interfaces_command = 'show interfaces ' SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) hostname = net_connect.find_prompt() identifier = hostname identifier += '{ip}'.format(**a_device) show_interfaces = net_connect.send_command_timing(show_interfaces_command) return_data[identifier] = (True, show_interfaces) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) return None mp_queue.put(return_data)
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt': 'twb-sf-hpsw1#', 'base_prompt': 'twb-sf-hpsw1', 'interface_ip': '10.220.88.10', 'config_mode': '(config)', } show_ver_command = 'show version' multiple_line_command = 'show logging' module.basic_command = 'show ip' SSHClass = netmiko.ssh_dispatcher(hp_procurve['device_type']) net_connect = SSHClass(**hp_procurve) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command( multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Enable doesn't do anything on ProCurve net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Enter config mode module.config_mode = net_connect.config_mode() # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Send a set of config commands config_commands = [ 'time timezone -420', 'time timezone -480', 'time daylight-time-rule Continental-US-and-Canada' ] net_connect.send_config_set(config_commands) # Verify config changes module.config_commands_output = net_connect.send_command('show run') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt': 'RP/0/0/CPU0:XRv-1#', 'base_prompt': 'RP/0/0/CPU0:XRv-1', 'interface_ip': '169.254.254.181', 'config_mode': '(config)' } show_ver_command = 'show version' commit_history_cmd = 'show configuration commit list' module.basic_command = 'show ipv4 int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xr['device_type']) net_connect = SSHClass(**cisco_xr) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) net_connect.enable() module.enable_prompt = net_connect.find_prompt() current_commit_history = net_connect.send_command(commit_history_cmd) # get the current 10 digit commit Label ID module.current_commit = current_commit_history.split('\n')[4].split()[1] module.config_mode = net_connect.config_mode() config_commands = [ 'logging monitor warning', 'logging buffered 30720100', 'logging console errors' ] net_connect.send_config_set(config_commands, commit=True) new_commit_history = net_connect.send_command(commit_history_cmd) # get the new 10 digit commit Label ID module.new_commit = new_commit_history.split('\n')[4].split()[1] module.config_commands_output = net_connect.send_command( "show run | inc logging") net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'twb-py-lab', 'enable_prompt' : 'twb-py-lab#', 'interface_ip' : '10.220.88.1', 'config_mode' : '(config)', } show_ver_command = 'show version' multiple_line_command = 'show version' module.basic_command = 'show ip' SSHClass = netmiko.ssh_dispatcher(cisco_asa['device_type']) net_connect = SSHClass(**cisco_asa) # ASA enters enable mode as part of connection (disable paging is # a config-mode command) module.base_prompt = net_connect.base_prompt module.enable_prompt = net_connect.find_prompt() # Test connection successful module.show_version = net_connect.send_command(show_ver_command) # Test output paging module.multiple_line_output = net_connect.send_command(multiple_line_command) # Test sending a show command module.show_ip = net_connect.send_command(module.basic_command) # Send a set of config commands config_commands = ['logging buffered notifications', 'logging buffered warnings', 'no logging console'] net_connect.send_config_set(config_commands) # Enter/exit config mode module.config_mode = net_connect.config_mode() module.exit_config_mode = net_connect.exit_config_mode() # Verify config changes module.config_commands_output = net_connect.send_command('show run | inc logging buffer') net_connect.disconnect()
def show_arp( a_device, mp_queue ) : identifier = '{ip}:{port}'.format( **a_device ) return_data = {} cmd = 'show arp' SSHClass = netmiko.ssh_dispatcher( a_device['device_type'] ) try: net_connect = SSHClass( **a_device ) output = net_connect.send_command( cmd ) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put( return_data ) return None return_data[identifier] = (True, output ) mp_queue.put( return_data )
def connect_to_device(device_params, command): ''' create a function to utilize the netmiko python module pass in the device paramaters (ip, username, password) issue the command passed into the function set DEBUG to true to get entire command output ''' SSHClass = netmiko.ssh_dispatcher(device_type=device_params['device_type']) net_connect = SSHClass(**device_params) output = net_connect.send_command(command) # print the output of the command if DEBUG is enabled. if DEBUG: print "-" * 20 + "[Command Output Debug]" + "-" * 20 print output print "-" * 62 + "\n" return output
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt': 'vsr1000', 'router_prompt': '<vsr1000>', 'interface_ip': '192.168.112.11', 'config_mode': '[vsr1000]', } show_ver_command = 'display version' multiple_line_command = 'display logbuffer' module.basic_command = 'display ip interface brief' SSHClass = netmiko.ssh_dispatcher(hp_comware['device_type']) net_connect = SSHClass(**hp_comware) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command( multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Enter config mode module.config_mode = net_connect.config_mode() # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Send a set of config commands config_commands = ['vlan 3000', 'name 3000-test'] net_connect.send_config_set(config_commands) # Verify config changes module.config_commands_output = net_connect.send_command( 'display vlan 3000') # Undo config changes net_connect.send_command('undo vlan 3000') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'twb-sf-hpsw1#', 'base_prompt' : 'twb-sf-hpsw1', 'interface_ip' : '10.220.88.10', 'config_mode' : '(config)', } show_ver_command = 'show version' multiple_line_command = 'show logging' module.basic_command = 'show ip' SSHClass = netmiko.ssh_dispatcher(hp_procurve['device_type']) net_connect = SSHClass(**hp_procurve) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Enable doesn't do anything on ProCurve net_connect.enable() module.enable_prompt = net_connect.find_prompt() # Enter config mode module.config_mode = net_connect.config_mode() # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Send a set of config commands config_commands = ['time timezone -420', 'time timezone -480', 'time daylight-time-rule Continental-US-and-Canada' ] net_connect.send_config_set(config_commands) # Verify config changes module.config_commands_output = net_connect.send_command('show run') net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'router_prompt' : 'RP/0/0/CPU0:XRv-1#', 'router_enable' : 'RP/0/0/CPU0:XRv-1#', 'interface_ip' : '169.254.254.181', 'config_mode' : '(config)' } show_ver_command = 'show version' commit_history_cmd = 'show configuration commit list' module.basic_command = 'show ipv4 int brief' SSHClass = netmiko.ssh_dispatcher(cisco_xr['device_type']) net_connect = SSHClass(**cisco_xr) module.show_version = net_connect.send_command(show_ver_command) module.show_ip = net_connect.send_command(module.basic_command) module.router_prompt_initial = net_connect.router_prompt net_connect.enable() module.router_prompt = net_connect.router_prompt current_commit_history = net_connect.send_command(commit_history_cmd) # get the current 10 digit commit Label ID module.current_commit = current_commit_history.split('\n')[4].split()[1] module.config_mode = net_connect.config_mode() config_commands = ['logging monitor warning', 'logging buffered 30720100', 'logging console errors'] net_connect.send_config_set(config_commands, commit=True) new_commit_history = net_connect.send_command(commit_history_cmd) # get the new 10 digit commit Label ID module.new_commit = new_commit_history.split('\n')[4].split()[1] module.config_commands_output = net_connect.send_command("show run | inc logging") net_connect.disconnect()
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'vsr1000', 'router_prompt' : '<vsr1000>', 'interface_ip' : '192.168.112.11', 'config_mode' : '[vsr1000]', } show_ver_command = 'display version' multiple_line_command = 'display logbuffer' module.basic_command = 'display ip interface brief' SSHClass = netmiko.ssh_dispatcher(hp_comware['device_type']) net_connect = SSHClass(**hp_comware) module.show_version = net_connect.send_command(show_ver_command) module.multiple_line_output = net_connect.send_command(multiple_line_command, delay_factor=2) module.show_ip = net_connect.send_command(module.basic_command) module.base_prompt = net_connect.base_prompt # Enter config mode module.config_mode = net_connect.config_mode() # Exit config mode module.exit_config_mode = net_connect.exit_config_mode() # Send a set of config commands config_commands = ['vlan 3000', 'name 3000-test'] net_connect.send_config_set(config_commands) # Verify config changes module.config_commands_output = net_connect.send_command('display vlan 3000') # Undo config changes net_connect.send_command('undo vlan 3000') net_connect.disconnect()
def worker_configuration(a_device, mp_queue): try: a_device['conf']['port'] except KeyError: a_device['conf']['port'] = 22 r_time = datetime.now() save_command = 'show running-config' identifier = '{ip}'.format(**a_device['conf']) return_data = {} SSHClass = netmiko.ssh_dispatcher(a_device['conf']['device_type']) try: #print 'Device: ' + a_device['conf']['device_type']; a_dev = a_device['conf'] net_connect = SSHClass(**a_dev) return_data[identifier] = {} return_data[identifier]['results'] = {} #print '\nPrompt: ' + net_connect.find_prompt() for command in a_device['commands']: #print '\nCommand: ' + command result = net_connect.send_command(command) #print '\nResult: ' + result return_data[identifier]['results'][command] = result if command == save_command: f = open('/home/Firewalls-Backup/' + identifier + '.txt', "w+") f.write(result) f.close() return_data[identifier]['error'] = (False, 'Success') net_connect.disconnect() except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier]['error'] = (True, e) # Add data to the queue (for parent process) mp_queue.put(return_data) return None mp_queue.put(return_data)
def worker_show_version(a_device, mp_queue): ''' Return a dictionary where the key is the device identifier Value is (success|fail(boolean), return_string) ''' try: a_device['port'] except KeyError: a_device['port'] = 22 ''' populate the device dictionary [ port ] field if not specified in the external file then set "identifier" for each in turn to be such a dictionary id '{2323}:{1111}' type(id) <type 'str'> ''' identifier = '{ip}:{port}'.format(**a_device) ''' return data is a DICT ''' return_data = {} show_ver_command = 'show arp' SSHClass = netmiko.ssh_dispatcher(a_device['device_type']) try: net_connect = SSHClass(**a_device) show_version = net_connect.send_command(show_ver_command) except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: return_data[identifier] = (False, e) # Add data to the queue (for parent process) mp_queue.put(return_data) return None return_data[identifier] = (True, show_version) mp_queue.put(return_data)
def main(): failed_devices = [] DEBUG = True parser = argparse.ArgumentParser(description='Cisco IOS/IOS-XE and NX-OS Interface description updater script - based on current CDP data on the network.\ Select a device type (ios or nxos) and the script will SSH into all given devices, parse CDP, and configure interface descriptions based on it.') parser.add_argument('-type', dest = 'type', action = 'store', choices = {'ios', 'nxos'}, help = 'Specify device type, IOS or NXOS', required = True) #parser.add_argument('--ios', help='Specify that the devices to parse are IOS devices', action='store_true', default=False) #parser.add_argument('--nxos', help='Specify that the devices to parse are Nexus devices', action='store_true', default=False) parser.add_argument('-l', '--log', help='Log file location', action='store', dest='log_file', type=str, default='C:\\TEMP\\cdp_parser_log.txt') #parser.add_argument('--log', help='Log file location', action='store', dest='log_file', type=str, default='C:\\TEMP\\cdp_parser_log.txt') parser.add_argument('-f', '--file', help='File with device IP or FQDN', action = 'store', dest = 'target_devices_input') args = parser.parse_args() # extract attributes from command line args dev_type = args.type logfile = args.log_file target_devices_input = args.target_devices_input # create logger logger = configure_logging(logfile) # provide creds dev_creds = dict(username=getpass.getuser(), password=getpass.getpass('Enter your password: '******'vna1er1-wan'] SSHClient = netmiko.ssh_dispatcher(device_type='cisco_ios') for a_device in device_list: # instantiate ssh object ###### device_obj = ssh_helper.sshHelper(host=a_device, **dev_creds) # connect to device try: device_obj = SSHClient(ip=a_device, **dev_creds) logger.info("Connecting to %s...", a_device) ###### device_obj.connect() except gaierror, e: logger.error('Failed to connect to: %s!. Continuing with the next device, if any...', a_device) failed_devices.append(a_device) continue logger.info("Collecting CDP data from %s", a_device) # send 'show cdp neighbor detail' ###### device_obj.chan.send('show cdp neighbor detail\n') output = device_obj.send_command('show cdp neighbor detail') # wait 2 seconds for command to finish time.sleep(1) # receive buffer ###### output = device_obj.read_data() # pass 'output' to cdp_parser, then pass that output # to generate_config. This will return a list of # Cisco IOS/NX-OS syntax that can iterated over and # send through the SSH session to update the description # on each device # if its IOS, then call the IOS parser if dev_type == 'ios': commands_to_send = generate_config(ios_cdp_parser(output)) # if its Nexus, then call the Nexus parser elif dev_type == 'nxos': commands_to_send = generate_config(nexus_cdp_parser(output)) else: logger.info('Error: Need to specify IOS or Nexus device class in order to the parser to work!!! Try again with the --ios or --nxos flags.') logger.info('Parsing complete - about to send description commands down the SSH channel') # send commands from list down SSH channel if DEBUG: print print "*" * 80 print pp(commands_to_send) print print "*" * 80 if not DEBUG: logger.info("Updating interface descriptions on %s...", a_device) # enter config mode ###### device_obj.chan.send('configure terminal' + '\n') device_obj.config_mode() # receive buffer ###### device_obj.read_data() for command in commands_to_send: # send commands down channel and append a new-line. # pause for .2 seconds after each entered command. device_obj.chan.send(command + '\n') time.sleep(.20) logger.info("Work finished on %s. Disconecting now.", a_device) device_obj.disconnect()
self.net_device.uptime_seconds = parse_uptime(self.uptime_str) print self.net_device.uptime_seconds self.net_device.save() if __name__ == '__main__': import netmiko import django from net_system.models import NetworkDevice django.setup() devices = NetworkDevice.objects.filter(device_name = 'VNA1DS1-SF') for device in devices: SSHClass = netmiko.ssh_dispatcher(str(device.device_class)[:-4]) ssh = SSHClass(ip=device.ip_address, username=device.credentials.username, password=device.credentials.password) output = ssh.send_command('show version | xml | exclude "]]>]]>"') inventory = NexusGatherInventory(device, output) inventory.find_os_version() inventory.find_serial_number() inventory.find_uptime()
if __name__ == '__main__': django.setup() prefix_re = re.compile(r'(\d+\.\d+\.\d+\.\d+/32)') net_device = NetworkDevice.objects.get(device_name='VNA1ER1-WAN') device_class, device_name, device_ip, device_username, device_password = net_device.device_class, net_device.device_name, \ net_device.ip_address, net_device.credentials.username, net_device.credentials.password # even though we already have the creds, we need to import this # django object so that we can save it on each device creds = Credentials.objects.get(id=1) SSHClient = netmiko.ssh_dispatcher(device_type=device_class[:-4]) ssh = SSHClient(ip=device_name, username=device_username, password=device_password) output = ssh.send_command("show ip bgp | inc .8/32") outlines = output.splitlines() # grab the prefix from the show bgp output base_prefixes = [prefix_re.search(line).group(1) for line in outlines] # remove the /32 from the preifx and split each prefix on the dot # to perform operations on each octet later all_nodes = [prefix[:-3].split('.') for prefix in base_prefixes] #dev_dict = defaultdict(list) dev_list = [] for branch in all_nodes: