def send_show_command(device_list, show_command): result_dict = {} for device in device_list: try: ssh = netmiko.ConnectHandler(**device) ssh.enable() result = str(ssh.send_command(show_command)) result_dict.update({device['ip']: result}) except: print("unable to connect to {}".format(device['ip'])) return (result_dict)
def go_get_info_from_devices(ip): try: net_connect = netmiko.ConnectHandler(device_type='cisco_ios', ip=ip, username=username, password=password) tmp_device_info = net_connect.send_command_expect('show run') return tmp_device_info except: cant_ssh = "Can't SSH to " + ip to_doc("results.txt", cant_ssh) return "Can't SSH to this"
def send_show_command(device, command): result = {} with open(device) as f: devices = yaml.load(f) for d in devices['routers']: try: conn = netmiko.ConnectHandler(**d) output = conn.send_command(command) result[d['ip']] = output except netmiko.ssh_exception.NetMikoAuthenticationException: print('Not connect to {}. Authentication failed'.format(d['ip'])) return result
def send_show(device, show): ip = device['ip'] logging.info(start_msg.format(datetime.now().time(), ip)) #if ip == '192.168.100.1': time.sleep(5) try: with netmiko.ConnectHandler(**device) as ssh: ssh.enable() logging.info(recieved_msg.format(datetime.now().time(), ip)) result = ssh.send_command(show) return {ip: result} except NetMikoAuthenticationException as err: logging.warning(err)
def netmiko_connection(parameters, commands): for device in parameters: hostname = device.pop('hostname') connect = netmiko.ConnectHandler(**device) device_result = ['{0} {1} {0}'.format('', hostname)] for comm in commands: command_result = connect.send_command(comm) device_result.append(command_result) connect.disconnect() yield device_result
def send_commands_from_file(device, script): result = {} try: with netmiko.ConnectHandler(**device) as ssh: ssh.enable() sent = ssh.send_config_from_file(script) result[device['ip']] = sent return result except netmiko.NetMikoAuthenticationException: return ('Bad creds on {}'.format(device['ip'])) except netmiko.NetMikoTimeoutException: return ('Connection timeout to {}'.format(device['ip']))
def connectSSH(serverName): ''' Connects to a server via SSH :param serverName: Server ID :return: Netmiko Session ''' session = netmiko.ConnectHandler( device_type='cisco_ios', ip=db.serverList[serverName]['ip'], username=db.serverList[serverName]['userSSH'], password=db.serverList[serverName]['passSSH']) return session
def send_and_parse_show_command(device_dict, command, templates_path): logging.info(f'Connecting to {device_dict["ip"]}...') with netmiko.ConnectHandler(**device_dict) as ssh: ssh.enable() prompt = ssh.find_prompt()[:-1] command_output = ssh.send_command(command) cli_table = clitable.CliTable('index', templates_path) attributes_dict = {'Command':command} cli_table.ParseCmd(command_output, attributes_dict) res_lst = [list(row) for row in cli_table] header_lst = list(cli_table.header) return {prompt:[(dict(zip(header_lst, fsm_el))) for fsm_el in res_lst]}
def try_enable_password(self, devicedata, secret): devicedata['secret'] = secret devicedata['timeout'] = 2 try: device = netmiko.ConnectHandler(**devicedata) device.enable() except: return False, devicedata else: return True, devicedata
def go_get_info_from_devices(ip): try: net_connect = netmiko.ConnectHandler(device_type='cisco_ios', ip=ip, username=username, password=password) tmp_device_info = net_connect.send_command_expect('show int') tmp_device_info = tmp_device_info + net_connect.send_command_expect( 'show processes cpu | i CPU') return tmp_device_info except: return "Can't SSH to this"
def command(device): """Execute show run command using Netmiko.""" try: connection = netmiko.ConnectHandler(ip=device, device_type="cisco_ios", username=user, password=pwd) print() print("#" * 80) print(connection.send_command_expect("show run")) print("#" * 80) print() connection.disconnect() except (netmiko.NetMikoTimeoutException, netmiko.NetMikoAuthenticationException,) as e: print(e)
def send_show_command(device, command): try: with netmiko.ConnectHandler(**device) as ssh: print('Connecting to:', device['ip']) ssh.enable() result = ssh.send_command(command) return result except netmiko.NetMikoAuthenticationException as err: print("Oops, we've got an exception here!", err) except netmiko.ssh_exception.NetMikoTimeoutException as err: print("Oops, we've got an exception here!", err)
def main(args): '''Acquire necessary input options, execute show arp on multiple routers, process per CLI args.''' # Benchmark prog_start = datetime.datetime.now() print 'Program start time: {}\n'.format(prog_start) parser = argparse.ArgumentParser( description='Execute show arp on specified routers') parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-d', '--datafile', help='specify YAML file to read router info from', default=ROUTER_FILE) parser.add_argument('-p', '--port', help='specify ssh port (default is 22)') parser.add_argument( '--prompt', action='store_true', help='prompt for router info (do not try to read in from file)', default=False) parser.add_argument('-v', '--verbose', action='store_true', help='display verbose output', default=False) args = parser.parse_args() # Initialize data structures if not args.prompt: myrouters = yaml_input(args.datafile, args.verbose) if myrouters == {}: myrouters = [{}] else: myrouters = [{}] for router in myrouters: check_input(router, args.port, args.verbose) cmd = 'show arp' for router in myrouters: router_conn = netmiko.ConnectHandler(**router) output = router_conn.send_command(cmd) print '{} on [{}:{}]:\n{}\n'.format(cmd, router['ip'], router['port'], output) router_conn.disconnect() # Benchmark prog_end = datetime.datetime.now() print 'Program end time: {}'.format(prog_end) prog_time = prog_end - prog_start print 'Elapsed time: {}'.format(prog_time)
def send_command_to_device(dev, command_list): ip = dev['ip'] logging.info(f'Connect to {ip}...') with netmiko.ConnectHandler(**dev) as ssh: ssh.enable() result = '' for command in command_list: res = ssh.send_command(command, strip_command=False, strip_prompt=False).split('\n') host = res.pop() res[0] = host + res[0] result += '\n'.join(res) + '\n' logging.info(f'Received all commands from {ip}') return result
def connectToSSH(deviceType, host, creds): # Try to connect to the host try: ssh = nm.ConnectHandler(device_type=deviceType, ip=host, username=creds.un, password=creds.pw) #except nm.AuthenticationException: # return "%s skipped - authentication error\n" % (host) except: return "%s skipped - connection timeout\n" % (host) # Returns active SSH session to host return ssh
def connection_to_dev(device, command): try: with netmiko.ConnectHandler(**device, verbose=True) as ssh: print('>>>try connect to host', device['ip']) #print ('prompt:',ssh.find_prompt()) ssh.send_command('disable clipaging') result = ssh.send_command(command) ssh.send_command('enable clipaging') if 'Incomplete' in result: print('Error in command') return result except: print('>>>netmiko_return_error', device['ip'])
def send_show_command(dic, comm): ip = dic['ip'] print(f'Connecting to device {ip}') try: with netmiko.ConnectHandler(**dic) as ssh: ssh.enable() result = ssh.send_command(comm) return print(result) except netmiko.ssh_exception.NetmikoAuthenticationException as err: print(err)
def enable_device_login(self, devicedata): priv = False device = netmiko.ConnectHandler(**devicedata) response = device.send_command('show privilege') privreg = '(?P<priv>\d+)' match = re.search(privreg, response) if match.group( 'priv' ) == '15': #to check what is the privilege level logged into using the username and password priv = True return priv, devicedata
def SENDCOMMANDAWS(device): print "Connecting to %s" % (device) net_connect = netmiko.ConnectHandler(**device) output = net_connect.find_prompt() print output for command in select_command_list: print "Sending command %s" % (command) output = net_connect.send_command_expect(command) print(output) time.sleep(4) output = net_connect.find_prompt() print(output) net_connect.disconnect()
def send_show_command(DEVICE_PARAMS, COMMAND): try: with netmiko.ConnectHandler(**DEVICE_PARAMS) as ssh: ssh.enable() result = [] prompt = '\n' + ssh.find_prompt() + COMMAND + '\n' output = prompt + ssh.send_command(COMMAND) result.append(output) return '\n'.join(result) except paramiko.ssh_exception.AuthenticationException as e: return e except netmiko.ssh_exception.NetMikoTimeoutException as e: return e
def _establish(self): if self.config['password']: self.config['use_keys'] = False else: self.config['use_keys'] = True self.config['allow_agent'] = True try: return netmiko.ConnectHandler(**self.config) except Exception as error: raise NetcliError( f'ERROR: Unable to connect to device: {str(error)}')
def send_show_command(device_params): print('Opening connection to IP: {}'.format(device_params['ip'])) conn = netmiko.ConnectHandler(**device_params) conn.enable() result = None while True: try: command = yield result result = conn.send_command(command) except GeneratorExit: conn.disconnect() print('Connection closed') break
def send_show(device, show): start_msg = '===> {} Connection: {}' received_msg = '<=== {} Received: {}' ip = device['host'] logging.info(start_msg.format(datetime.now().time(), ip)) if ip == '192.168.100.1': time.sleep(5) with netmiko.ConnectHandler(**device) as ssh: ssh.enable() result = ssh.send_command(show) logging.info(received_msg.format(datetime.now().time(), ip)) return result
def send_command(device, command_list): try: with netmiko.ConnectHandler(**device) as ssh: ssh.enable() if type(command_list) is list: result ='' for command in command_list: result += ssh.find_prompt() + ssh.send_command(command, strip_command=False) + '\n' if type(command_list) is str: result= ssh.find_prompt() + ssh.send_command(command_list, strip_command=False) + '\n' return result except netmiko.NetMikoAuthenticationException as err: return err
def send_show_command_to_devices(device, command): start_msg = '===> {} Connection: {}' received_msg = '<=== {} Received: {}' ip = device['host'] if commands.get(device['host']): command = commands[device['host']] logging.info(start_msg.format(datetime.now().time(), ip)) with netmiko.ConnectHandler(**device) as ssh: ssh.enable() result = ssh.send_command(strip_command=False, command_string=command) logging.info(received_msg.format(datetime.now().time(), ip)) return result
def send_show(device, show): start_msg = "===> {} Connection: {}" received_msg = "<=== {} Received: {}" host = device["host"] logging.info(start_msg.format(datetime.now().time(), host)) if host == "192.168.100.1": time.sleep(5) with netmiko.ConnectHandler(**device) as ssh: ssh.enable() result = ssh.send_command(show) logging.info(received_msg.format(datetime.now().time(), host)) return result
def get_info(self, commands): # Getting show output # List of commands as input output = {} with netmiko.ConnectHandler(ip=self.mgmt_ip, device_type=self.dev_type, username=self.username, password=self.password, secret=self.en_password) as connection: connection.enable() for command in commands: output[command] = connection.send_command(command) return output
def __init__(self, username, password, ip_address, secret): param = { 'ip': ip_address, 'username': username, 'password': password, 'device_type': 'cisco_ios', 'secret': secret } try: self.handler = netmiko.ConnectHandler(**param) self.hostname = self.handler.find_prompt()[:-1] except Exception as e: print(f"Can't init device handler: {e}")
def send_show(device, command, parse_textfsm=True): with netmiko.ConnectHandler(**device) as ssh: ssh.enable() prompt = ssh.find_prompt() output = ssh.send_command(command) output = f"{prompt}{command}\n{output}" if parse_textfsm: parsed_data = parse_output_textfsm( output, {"Command": command, "Vendor": device["device_type"]} ) if parsed_data: return parsed_data return output
def check_connection(self): try: print('Trying to connect to ', self.mgmt_ip) netmiko.ConnectHandler(ip=self.mgmt_ip, device_type=self.dev_type, username=self.username, password=self.password) except Exception as e: print('ERROR! ', str(e)) return False else: print('Success!') return True