def cpy(): start = time.time() with open('router.list') as f: ip_r = f.read().splitlines() with open('switch.list') as f: ip_s = f.read().splitlines() ip_add = ip_r + ip_s #On parcourt la liste d'IP for ip in ip_add: print("Sauvegarde de la configuration de l'équipement ayant l'adresse : "+ ip) equipment = { 'device_type': 'cisco_ios', 'ip': ip, 'username': username, 'password': password, } #On initialise la connexion Netmiko sur l'équipement cible net_connect = Netmiko(**equipment) #Envoi d'un cpy run start sur l'équipement,utilisation de deux arguments permettant la confirmation de sauvegarde output = net_connect.send_command_timing("copy run start", strip_command=False, strip_prompt=False) output = net_connect.send_command_timing("startup-config", strip_command=False, strip_prompt=False) if "confirm" in output: output += net_connect.send_command_timing("y", strip_prompt=False, strip_command=False) net_connect.disconnect() print("Configuration sauvegardée avec succés") duration(start)
def print_cmd(ip_addr, username, cmd): my_device = { 'host': ip_addr, 'username': username, 'password': getpass(), 'device_type': 'cisco_ios' } net_conn = Netmiko(**my_device) output = net_conn.send_command_timing(cmd) if 'Delete' in output: output += net_conn.send_command_timing('\n') if 'confirm' in output: output += net_conn.send_command_timing('\n') print(output) net_conn.disconnect()
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()
from __future__ import unicode_literals from netmiko import Netmiko from getpass import getpass password = getpass() csr1000v = { 'device_type': 'cisco_ios', 'username': '******', 'password': password, 'secret': password, 'ip': '192.168.8.128' } connection = Netmiko(**csr1000v) print connection.find_prompt() cmd = 'reload in 10' output = connection.send_command_timing(cmd) if 'confirm' in output: output += connection.send_command_timing('\n') connection.disconnect() print(output)
from getpass import getpass from netmiko import Netmiko password = getpass() device = { 'host': '192.168.122.74', 'username': '******', 'password': password, 'device_type': 'arista_eos' } net_connect = Netmiko(**device) filename = 'small_file.txt' cmd = 'delete flash:{}'.format(filename) output = net_connect.send_command_timing(cmd) if 'confirm' in output: output += connect_connect.send_command_timing('\n') print(output)
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass cisco1 = { "host": "cisco1.twb-tech.com", "username": "******", "password": getpass(), "device_type": "cisco_ios", } net_connect = Netmiko(**cisco1) command = "del flash:/test1.txt" print() print(net_connect.find_prompt()) output = net_connect.send_command_timing(command) if "confirm" in output: output += net_connect.send_command_timing( "y", strip_prompt=False, strip_command=False ) net_connect.disconnect() print(output) print()
class TermServ(object): def __init__(self, model, ip, cid, username=None, password=None, logger=None, desc=""): self.logger = logger or logging.getLogger() self.model = model self.ip = ip self.cid = cid self.desc = desc if self.model.lower() == "digi": self.username = username or "admin" self.password = password or "admin" self.base_cmd = "" self.base_prompt = "---->" self._connect = self._connect_digi self._show = self._show_digi self._kill = self._kill_digi elif self.model.lower() == "avocent": self.username = username or "root" self.password = password or "stratax120" self.base_cmd = "CLI" self.base_prompt = "cli>" self._connect = self._connect_avocent self._show = self._show_avocent self._kill = self._kill_avocent else: msg = "TODO: model={}".format(self.model) self.logger.log(msg, lvl=logging.WARNING) def _get_cids(self, cid): if cid is None: cids = [self.cid] elif isinstance(cid, list): cids = cid else: cids = [cid] return cids def do_op(self, op, cid=None): retval = False msg = "Failed to perform {}".format(op) try: if not self._connect(): msg = "Failed to connect" elif op == "show": retval = self._show() elif op == "kill": cids = self._get_cids(cid) retval = self._kill(cids) elif op == "show-kill": retval = self._show() cids = self._get_cids(cid) retval = self._kill(cids) except Exception as e: msg = "Failed to perform {}: {}".format(op, e) if not retval: self._log(msg, lvl=logging.ERROR) return retval def _log(self, msg, lvl=logging.INFO): if self.desc: prefix = "TS({}): ".format(self.desc) else: prefix = "TS: " msg2 = "{}{}".format(prefix, msg) self.logger.log(lvl, msg2) return msg2 def _send_escape(self, count=5): for _ in range(count): self.hndl.send_command("\x1B") def _connect_digi(self): self.hndl = Netmiko(self.ip, username=self.username, password=self.password, device_type="cisco_ios") self.hndl.send_command(self.base_cmd) self.hndl.base_prompt = self.hndl.find_prompt() self._log("============== INITIAL PROMPT =================") self._log(self.hndl.find_prompt()) self._log("===============================================") return self.hndl def _show_digi(self): self.hndl.send_command("6") output = self.hndl.send_command_timing("3") self.hndl.send_command("") self._log(output) return output def _kill_digi(self, ports): self._send_escape() if not isinstance(ports, list): ports = [ports] output = self.hndl.send_command("2") self._log(output) for port in ports: self.hndl.send_command(str(port)) self.hndl.send_command("a") output = self.hndl.send_command("1", expect_string="has been reset successfully") self._log("\n" + output) self.hndl.send_command("") self._send_escape(2) return True def _connect_avocent(self): self.hndl = Netmiko(self.ip, username=self.username, password=self.password, device_type="linux") if self.hndl: self.hndl.send_command("CLI", self.base_prompt) self.hndl.base_prompt = self.hndl.find_prompt() return self.hndl def _show_avocent(self): output = self.hndl.send_command("administration sessions list") self.hndl.send_command_timing("") self._log("\n" + output) return output def _kill_avocent(self, ports): for port in ports: self._log("------ Kill Session on {} ------".format(port)) output = self.hndl.send_command("administration sessions kill {}".format(port)) self._log(output) self.hndl.send_command_timing("") return True
'password': getpass(), 'device_type': 'cisco_ios', 'fast_cli': True, } # Record start time to measure execution speed of command with fast_cli enabled start_time = datetime.now() # Establish SSH connection to the network device using **kwargs to pull in details from dictionary net_connect = Netmiko(**cisco3_device) # commands to send to the router cmd = ['ip name-server 1.1.1.1', 'ip name-server 1.0.0.1', 'ip domain-lookup'] # Send command to router with fast_cli enabled output = net_connect.send_config_set(cmd) print(output) # Check if DNS lookups now working on router print(net_connect.send_command_timing('ping google.com')) # Disconnect from device net_connect.disconnect() # Record end time end_time = datetime.now() # Calculate total time taken and print to console total_time = end_time - start_time print('-' * 80) print('Total time taken was: ' + str(total_time)) print('-' * 80)
def main(argumentList): """ Main function that deploys list of commands to a list of devices and prints/parses/stores its output """ # global SHOULD_PARSE, SHOULD_PROGRESS, SHOULD_STORE, SHOULD_TIME, SHOULD_INFINITE try: cmd_options, cmd_values = getopt.getopt(argumentList, "hpbsoj:d:l:c:x:r:t:q:y:", ["help","parse","bar","store","overwrite",\ "json=","device_list=","device=","device_file_list=","command=","cmd_file_list=","repeat=","template=","query=","device_type="]) except getopt.GetoptError: exit_error("Invalid input option!") logging.basicConfig(filename='test.log', level=logging.DEBUG) logger = logging.getLogger("netmiko") sys_params = {} device_template = {} device_list = [] sys_params, device_list = prepare_device_data(cmd_options) print(sys_params) print(device_list) # Main loop iter = sys_params['repeat'] #iter=number of expected iterations citer = 0 #citer=current iteration sys_params['timestamps'].append(time.time()) while ((sys_params['time'] or sys_params['infinite']) or iter): count_ops = 0 #count_ops=current number of operation done (operation=command/device) citer += 1 for device in device_list: if (DEBUG_FLAG): pass else: #curr_device=device["device"] #print(curr_device) #net_device = Netmiko(**curr_device) net_device = Netmiko(**device["device"]) for cmd in device['commands']: output = "" count_ops += 1 if (DEBUG_FLAG): #output = output+os.linesep+net_device.send_command_timing(cmd) output = time.asctime() + os.linesep + cmd else: output = time.asctime() + os.linesep output += net_device.send_command_timing(cmd) if (sys_params['progress'] and sys_params['store']): #print (sys_params['total_ops'], count_ops) stats_output(citer, count_ops, sys_params) else: print(output) device["output"].append(output) if sys_params['store']: print("Sada snimam jednu iteraciju") store_output(device) #print(device["output"]) device["output"].clear() sys_params['timestamps'].append(time.time()) stats_output(citer, count_ops, sys_params, True) #while loop control mechanism if (sys_params['time']): time.sleep(float(sys_params['repeat'])) #count_ops=0 elif (not sys_params['infinite']): iter = iter - 1 else: pass
def deviceconnector(i, q): # This while loop runs indefinitely and grabs IP addresses from the queue and processes them # Loop will be blocked and wait if "ip = q.get()" is empty while True: ip = q.get() with print_lock: print('Th{}/{}: Acquired IP: {}'.format(i + 1, threads, ip)) #Create an error log file errorfile = open( 'valkyrie output/valkyrie errors ' + str(date.today()) + '.txt', 'a') # device_dict is copied over to net_connect device_dict = { 'host': ip, 'username': username, 'password': password, 'secret': secret, 'device_type': 'autodetect', 'banner_timeout': 60, 'conn_timeout': 60 # Gather session output logs - TESTING ONLY # , # 'session_log': 'session_output.txt' } # device type autodetect based on netmiko try: auto_device_dict = SSHDetect(**device_dict) device_os = auto_device_dict.autodetect() # Validate device type returned (Testing only) # print('===== {} =====\n===== {} ====='.format(device_os, auto_device_dict.potential_matches)) # Update device_dict device_type from 'autodetect' to the detected OS if device_os is None: print('Th{}/{}: {} returned unsupported device_type of {}\n'. format(i + 1, threads, device_dict['host'], device_os)) device_dict['device_type'] = 'autodetect' else: device_dict['device_type'] = device_os # Connect to the device, and print out auth or timeout errors net_connect = Netmiko(**device_dict) print('Th{}/{}: Connecting to: {} ({})'.format( i + 1, threads, net_connect.host, net_connect.device_type)) except NetMikoTimeoutException: with print_lock: print('Th{}/{}: ERROR: Connection to {} timed-out. \n'.format( i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: Connection timed-out. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break except (NetMikoAuthenticationException, AuthenticationException): with print_lock: print( 'Th{}/{}: ERROR: Authentication failed for {}. Stopping thread. \n' .format(i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: Authentication failed. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break except NoValidConnectionsError: with print_lock: print( 'Th{}/{}: ERROR: No Connections available for device {}. \n' .format(i + 1, threads, ip)) errorfile.write( '[{}] {} ERROR: No Connections available. \n'.format( datetime.now().strftime('%H:%M:%S'), ip)) q.task_done() break # Capture the output # TODO TextFSM to parse data # create two variables - one of hostname and the prompt level and another with just the hostname prompt = net_connect.find_prompt() hostname = prompt.rstrip('#>') print('Th{}/{}: Associated IP: {} with hostname: {}'.format( i + 1, threads, ip, hostname)) # TODO Write file to a optional, specified folder timenow = '{:%Y-%m-%d %H_%M_%S}'.format(datetime.now()) start = datetime.now() filename = (hostname + ' ' + ip + ' - valkyrie output {0}.txt') outputfile = open('valkyrie output/' + filename.format(timenow), 'w') print('Th{}/{}: Writing file name "{} {} - valkyrie output {}.txt"'. format(i + 1, threads, hostname, ip, format(timenow))) if device_os == 'cisco_ios': for cmd in commands: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_nxos': for cmd in commands_nexus: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_wlc': for cmd in commands_wlc: try: if re.match(r'\w', cmd): if cmd == 'show run-config': output = net_connect.send_command_timing( cmd.strip(), delay_factor=1, max_loops=1000) if 'Press Enter to continue' in output: output += net_connect.send_command_timing('\n') write_file(outputfile, prompt, cmd, output) else: output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) elif device_os == 'cisco_asa': for cmd in commands_asa: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) else: for cmd in commands_showtech: try: if re.match(r'\w', cmd): output = net_connect.send_command(cmd.strip(), delay_factor=1, max_loops=1000) write_file(outputfile, prompt, cmd, output) else: outputfile.write(prompt + cmd + '\n') except (NetMikoTimeoutException, EOFError, OSError) as e: exception_logging(e, i, threads, ip, hostname, cmd, prompt, outputfile, errorfile) net_connect = Netmiko(**device_dict) sleep(5) # Disconnect from device net_connect.disconnect() # Close the file outputfile.close() errorfile.close() # verify elapsed time per device end = datetime.now() print('Th{}/{}: Completed. Time elapsed: {}'.format( i + 1, threads, (end - start))) # Set the queue task as complete, thereby removing it from the queue indefinitely q.task_done()
from datetime import datetime from getpass import getpass from netmiko import Netmiko tftphost = raw_input("TFTP Server IP: ") ciscouser = raw_input("Login username: "******"host": line.rstrip("\n"), "username": ciscouser, "password": ciscopass, "device_type": "cisco_ios", } try: net_connect = Netmiko(**conn) except: print "unable to connect to " + line.rstrip("\n") else: timestamp = datetime.now().strftime('%Y%m%d%H%M%S') hostname = net_connect.find_prompt().split('#')[0] copytftp = "copy start tftp://" + tftphost + "/" + hostname + "-config-" + timestamp output = net_connect.send_command_timing(copytftp) while (':' in output) or ('?' in output): output = net_connect.send_command_timing("\n") net_connect.disconnect() print hostname + " configuration successfully backed up"
host = input("Enter host to connect to: ") password = getpass() device = { 'host': host, 'username': '******', 'password': password, 'device_type': 'cisco_ios', "secret": "cisco" } command = "copy run start\n" net_connect = Netmiko(**device) net_connect.enable() output = net_connect.send_command_timing(command, strip_prompt=False, strip_command=False) if 'Destination filename' in output: output += net_connect.send_command_timing('startup-config', strip_prompt=False, strip_command=False) else: raise ValueError("Expected confirm message in output") print() print('-' * 80) print(output) print('-' * 80) print()
from getpass import getpass password = getpass() cisco1 = { "device_type": "cisco_ios", "host": "cisco1.lasthop.io", "username": "******", "password": password } command = "del flash:/bf-test.txt" net_connect = Netmiko(**cisco1) output = net_connect.send_command_timing(command_string=command, strip_prompt=False, strip_command=False) if "Delete filename" in output: output += net_connect.send_command_timing(command_string="\n", strip_prompt=False, strip_command=False) if "confirm" in output: output += net_connect.send_command_timing(command_string="y", strip_prompt=False, strip_command=False) net_connect.disconnect() print(f"\n{output}\n")
def gns3_send_start_config_telnet(gns3_server, project_id, gns3_code_topology_data, global_delay_factor): print(""" ╔═╗┌┬┐┌─┐┌─┐ ╦╦ ╦ ┌─┐┌─┐┌┐┌┌┬┐ ┌─┐┌┬┐┌─┐┬─┐┌┬┐┬ ┬┌─┐ ┌─┐┌─┐┌┐┌┌─┐┬┌─┐ ╚═╗ │ ├┤ ├─┘ ║╚╗╔╝ └─┐├┤ │││ ││ └─┐ │ ├─┤├┬┘ │ │ │├─┘ │ │ ││││├┤ ││ ┬ ╚═╝ ┴ └─┘┴ ╩ ╚╝. └─┘└─┘┘└┘─┴┘ └─┘ ┴ ┴ ┴┴└─ ┴ └─┘┴ └─┘└─┘┘└┘└ ┴└─┘. """) gns3_host_ip = gns3_code_topology_data['gns3_host_ip'] START_CFGS_PATH = gns3_code_topology_data['START_CFGS_PATH'] list_start_config_nodes = [] for node in gns3_code_topology_data['gns3_startup_config_telnet']: name = node['name'] list_start_config_nodes.append(name) for node_name in list_start_config_nodes: print() print( 'Applying startup config to', node_name + ' from', '[' + gns3_code_topology_data['START_CFGS_PATH'] + node_name + ']') print() r_get_nodes = requests.get(gns3_server + '/v2/projects/' + str(project_id) + '/nodes') r_get_nodes_dict = r_get_nodes.json() for dictionary_node in r_get_nodes_dict: if dictionary_node['name'] == node_name: # For VPCS if dictionary_node['node_type'] == 'vpcs': device_type = 'generic_termserver_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } net_connect = Netmiko(**device) net_connect.send_config_from_file(config_file=config_path, exit_config_mode=False) net_connect.disconnect() continue # For VyOS. elif dictionary_node['port_name_format'] == 'eth{0}': device_type = 'generic_termserver_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } vyos = pexpect.spawn('telnet ' + gns3_host_ip + ' ' + str(telnet_port)) vyos.expect('') vyos.sendline('\n') vyos.expect('login: '******'vyos\n') vyos.expect('Password:'******'vyos') net_connect = Netmiko(**device) net_connect.send_config_from_file(config_file=config_path, exit_config_mode=False) net_connect.disconnect() continue # For JunOS. elif dictionary_node['port_name_format'] == 'ge-0/0/{0}': device_type = 'juniper_junos_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } juniper = pexpect.spawn('telnet ' + gns3_host_ip + ' ' + str(telnet_port)) juniper.expect('') juniper.sendline('\n') juniper.expect('login: '******'root\n') juniper.expect('') juniper.sendline('\n') juniper.expect('root@% ', timeout=120) juniper.sendline('cli') with open(config_path) as f: lines = f.read().splitlines() net_connect = Netmiko(**device) net_connect.config_mode() for line in lines: net_connect.send_command_timing(line) time.sleep(1) net_connect.disconnect() continue # For Cisco IOS and Cisco ASA. else: device_type = 'cisco_ios_telnet' config_path = os.path.abspath(START_CFGS_PATH + node_name) telnet_port = dictionary_node['console'] device = { "host": gns3_host_ip, "device_type": device_type, "port": telnet_port, "global_delay_factor": global_delay_factor } net_connect = Netmiko(**device) net_connect.enable() net_connect.send_config_from_file(config_file=config_path) net_connect.disconnect() continue print('Success -', node_name) print('=' * 100)
from netmiko import Netmiko from getpass import getpass #admin, admin123 password = getpass(prompt="Password : "******"delete flash:{}".format(filename) #send command timing -- Wait output = net_conn.send_command_timing(cmd) if 'confirm' in output: output+=net_conn.send_command_timing("\n") print(output) net_conn.disconnect() #allocate more time output = net_conn.send_command_timing("copy run start",delay_factor=2) #or can use ''' IOU1 = { 'host' : '192.168.160.131', 'username' : 'admin', 'password' : password, 'secret' : password, 'device_type' : 'cisco_ios',
from netmiko import Netmiko from getpass import getpass device = { 'host': 'cisco4.lasthop.io', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios', 'session_log': 'ping1a.txt', } net_connection = Netmiko(**device) print(net_connection.find_prompt()) output = net_connection.send_command_timing("ping") output1 = net_connection.send_command_timing("\n") output2 = net_connection.send_command_timing('8.8.8.8', strip_prompt=False, strip_command=False) output3 = net_connection.send_command_timing("\n") output4 = net_connection.send_command_timing("\n") output5 = net_connection.send_command_timing("\n") output6 = net_connection.send_command_timing('\n', strip_prompt=False, strip_command=False) print(output) print(output1) print(output2) print(output3) print(output4) print(output5)
#! /usr/bin/env python """ 3. Find a command on your device that has additional prompting. Use send_command_timing to send the command down the SSH channel. Capture the output and handle the additional prompting. """ from getpass import getpass from netmiko import Netmiko device = { "host": "sw01.test.domain", "username": "******", "password": getpass(), "device_type": "cisco_s300", } net_conn = Netmiko(**device) output = net_conn.send_command_timing("write memory") if "Overwrite file" in output: output += net_conn.send_command_timing("Y\n") net_conn.disconnect() print(output)
from netmiko import Netmiko from getpass import getpass #pwd = getpass() my_dev = { 'host': '10.99.236.231', 'username': '******', 'password': '', 'device_type': 'fortinet', } net_conn = Netmiko(**my_dev) cmd = 'exec reboot' out = net_conn.send_command_timing(cmd) print(out) ''' fg # exec reboot This operation will reboot the system ! Do you want to continue? (y/n)n ''' if 'continue' in out: out += net_conn.send_command_timing('y\n') print(out) net_conn.disconnect()
def ssh_exec_command(commands, host, user, pw, user_timeout, output_q): """ SSH to the device, sshsend commands, and capture the output Output: {'Host': '1.1.1.1', 'Hostname': 'Router', 'Interfaces': {'interface Gi1/1': ['int line 1', 'line 2'...]}} """ time.sleep(1) ssh_error = 'SSH Error' output = '' output_list = [] # one per device keys = ['Host', 'Hostname', 'Interfaces'] device_dict = {key: None for key in keys} Interfaces = {} output_dict = {} access_interface = False try: try: # Set up SSH session device = { 'device_type': 'cisco_ios', 'host': host, 'username': user, 'password': pw, } device_dict.update(Host=host) ssh = Netmiko(**device) print('') print('_____________________________________________________________') print('') print('Connection established to', host) print('_____________________________________________________________') time.sleep(5) # Get the router/switches prompt. This will be used later to see if the commands are done. deviceprompt = ssh.find_prompt() # NetMiko: find device prompt device_dict.update(Hostname=deviceprompt) ssh.send_command( 'terminal length 0\n' ) # print('COMPLETE: terminal length 0') # The string below doesn't work on slow or large stacks, so using send_command_timing instead ''' # The below doesn't work runningconfig = ssh.send_command( 'sh run | sec interface\n' , expect_string=r'#' ) ''' ####################################################### ###### COMMAND WE WANT TO LOOK AT THE OUTPUT FOR ###### ####################################################### runningconfig = ssh.send_command_timing( 'sh run | sec interface\n', delay_factor=10 # This number * 2 seconds ) ####################################################### ####################################################### runningconfig = runningconfig.splitlines() parse = CiscoConfParse(runningconfig) # Look for 'access' interfaces that do not have 'trunk' in their config for i in (parse.find_objects_wo_child(r'^interface', r'trunk')): intvalues = [] ################################################################# # What is the config line in the interface you are looking for? # accessvlan = 'switchport port-security' ################################################################# access_interface = i.has_child_with(accessvlan) if access_interface is True: for line in i.all_children: intvalues.append(line.text) Interfaces[i.text] = intvalues # {'int gi1/1: [conf line 1, line2 ...]} device_dict.update(Interfaces=Interfaces) # put interfaces in device's dict # If there's a qualifying interface, then dump it to a report. # Send output to the main program where it can be dumped to an output file try: if (len(device_dict['Interfaces']) != 0) or (device_dict['Interfaces'] is None): print('Adding this to report:', device_dict) output_q.put(device_dict) else: print(device_dict['Host'], 'has no qualifying interfaces for the given search. Not reporting this node.') except TypeError: print(device_dict['Host'], 'had a Script error, so there are probably no qualifying interfaces. Not reporting.') # Cleanup SSH finally: ssh.disconnect() except IndexError: pass except SSHException: print('SSH error on', host) except KeyboardInterrupt: print('\n Keyboard interrupt detected. Exiting thread.') try: ssh.disconnect() except Exception: pass except KeyboardInterrupt: print('\n Keyboard interrupt detected. Exiting thread.') try: ssh.disconnect() except Exception: pass finally: threadLimiter.release()
# Is based on Netmico script https://github.com/ktbyers/netmiko/tree/develop/examples/use_cases # # This script will run a command on a TRIGGER Cisco router to download routes from FTP and deploy them in to running-config # # To execute this script you need to install Netmico lib first. See https://github.com/ktbyers/netmiko#Installation # # Please make changes to the file with your settings # from netmiko import Netmiko from getpass import getpass cisco1 = { "host": "XXX.XXX.XXX.XXX", "username": "******", "password": "******", "device_type": "cisco_ios", } net_connect = Netmiko(**cisco1) command = "copy ftp://XXX.XXX.XXX.XXX/upload/cisco_commands.txt running-config" print() print(net_connect.find_prompt()) output = net_connect.send_command_timing(command) if "running-config" in output: output += net_connect.send_command_timing("running-config", strip_prompt=False, strip_command=False) net_connect.disconnect() print(output) print()
""" 3. Find a command on your device that has additional prompting. Use send_command_timing to send the command down the SSH channel. Capture the output and handle the additional prompting. """ 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) # Send ping command to device and capture output net_connection.send_command_timing('ping ipv4') # Handle additional prompting by sending IP address we want to ping output = net_connection.send_command_timing('8.8.8.8') # Print captured output print(output)
from netmiko import Netmiko from getpass import getpass device1 = { "host": 'cisco4.lasthop.io', "username": '******', "password": getpass(), "device_type": 'cisco_ios', } net_connect = Netmiko(**device1) print(net_connect.find_prompt()) output = net_connect.send_command_timing('ping', strip_prompt= False, strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False) output+= net_connect.send_command_timing('8.8.8.8', strip_prompt= False, strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False) output+= net_connect.send_command_timing('', strip_prompt= False,strip_command= False, delay_factor = 100) print(output)
from netmiko import Netmiko from getpass import getpass device1 = { "host": 'cisco4.lasthop.io', "username": '******', "password": getpass(), "device_type": 'cisco_ios', } net_connect = Netmiko(**device1) print(net_connect.find_prompt()) command = 'ping' output = [net_connect.send_command_timing(command), net_connect.send_command_timing("", strip_prompt=False, strip_command=False), net_connect.send_command_timing("8.8.8.8", strip_prompt=False, strip_command=False) net_connect.send_command_timing('',strip_prompt= False, strip_command= False), net_connect.send_command_timing('',strip_prompt= False, strip_command= False), net_connect.send_command_timing('',strip_prompt= False, strip_command= False), net_connect.send_command_timing('',strip_prompt= False, strip_command= False), net_connect.send_command_timing('',strip_prompt= False, strip_command= False, delay_factor =10)] print(output[-1]) net_connect.disconnect()
#!/usr/bin/env python3 """ Find a command on your device that has additional prompting. Use send_command_timing to send the command down the SSH channel. Capture the output and handle the additional prompting. """ from netmiko import Netmiko from getpass import getpass device = { 'host': '10.10.10.10', 'username': '******', 'password': getpass(), 'device_type': 'cisco_ios' } net_conn = Netmiko(**device) filename = "log.txt" cmd = "delete flash:{}".format(filename) print(cmd) output = net_conn.send_command_timing(cmd) if 'confirm' in output: output += net_conn.send_command_timing("\n") else: raise ValueError("No confirm message in output") print(output)
######################################### DO NOT CHANGE ########################################## ###################################### WORK on Hypervisor ######################################## if v_mode == 'all' or v_mode == "hypervisor": v_allservers = [esxi1, esxi2, esxi3, esxi4] for devices in v_allservers: # reset v_id v_id = v_idstart net_connect = Netmiko(**devices) while v_id <= v_idend: command1 = "esxcfg-vswitch --add-pg=" + v_networkname + str( v_id) + " vswitch-hx-vm-network" command2 = "esxcfg-vswitch -v " + str( v_id) + " -p " + v_networkname + str( v_id) + " vswitch-hx-vm-network" output = net_connect.send_command_timing(command1) output = net_connect.send_command_timing(command2) v_id = v_id + 1 net_connect.disconnect() ########################################## WORK on coreswitch ###################################### if v_mode == "all" or v_mode == "networking": net_connect = Netmiko(**coreswitch) # reset v_id v_id = v_idstart command1 = "conf t" output = net_connect.send_command_timing(command1) while v_id <= v_idend: command2 = "vlan " + str(v_id) command3 = "name " + v_networkname + str(v_id)
#!/usr/bin/env python from netmiko import Netmiko from getpass import getpass password = getpass() cisco1 = { 'host': 'cisco1.twb-tech.com', 'username': '******', 'password': password, 'device_type': 'cisco_ios', 'secret': password, } net_connect = Netmiko(**cisco1) print(net_connect.find_prompt()) net_connect.send_command_timing("disable") print(net_connect.find_prompt()) net_connect.enable() print(net_connect.find_prompt()) # Go into config mode net_connect.config_mode() print(net_connect.find_prompt()) net_connect.exit_config_mode() print(net_connect.find_prompt()) net_connect.disconnect()
print("Requesition fail") for host in req_host: ip = host["interfaces"][0]["ip"] host_name = host["host"] try: hostname = host_name+"-"+ip+"-"+utc+".cfg" print(">Start Mikrotik - Hostname {}".format(host_name)) router = { "host": ip, "port": <port>, "username": "******", "password": "******", "device_type": "mikrotik_routeros"} net_connect = Netmiko(**router) output = net_connect.send_command_timing("export terse") filename = "<folder-path>"+hostname file = open(filename, 'w') file.write(output + "\n") file.close() net_connect.disconnect() os.system( 'zabbix_sender -z <url-zabbix> -p <port> -s {} -k <variable-zabbix> -o Success'.format(host_name)) print("--------------------------------------------------------") except Exception as e: os.system( 'zabbix_sender -z <url-zabbix> -p <port> -s {} -k <variable-zabbix> -o Failure'.format(host_name)) print("Hostname:{} com o IP: {} deu o erro: {}".format( host_name, ip, str(e))) print("--------------------------------------------------------")
from netmiko import Netmiko username = '******' password = '******' hostname = 'cisco4.lasthop.io' device = { 'host':hostname, 'username':username, 'password':password, 'device_type':'cisco_ios', } conn = Netmiko(**device) print(conn.find_prompt()) command = 'ping' output = conn.send_command_timing(command, strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) output += conn.send_command_timing('8.8.8.8', strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) output += conn.send_command_timing('\n', strip_prompt=False, strip_command=False) conn.disconnect() print(output)
''' 3. Find a command on your device that has additional prompting. Use send_command_timing to send the command down the SSH channel. Capture the output and handle the additional prompting. ''' from netmiko import Netmiko from getpass import getpass command = 'no partition testP id 1' password = getpass() my_device = { 'host': '10.128.64.69', 'username': '******', 'password': password, 'device_type': 'a10' } dev_conn = Netmiko(**my_device) dev_conn.config_mode() print('Prompt for device {} is: {}'.format(my_device['host'], dev_conn.find_prompt())) com_output = dev_conn.send_command_timing(command) if 'Remove this partition' in com_output: com_output += dev_conn.send_command_timing('y\n') print('*' * 80) print('Output of "{}" command on "{}"'.format(command, my_device['host'])) print('*' * 80) print('{}'.format(com_output)) print('*' * 80)
from getpass import getpass try: host = raw_input("Enter host to connect to: ") except NameError: host = input("Enter host to connect to: ") password = getpass() device = { 'host': host, 'username': '******', 'password': password, 'device_type': 'cisco_ios', } filename = 'smallfile' command = 'delete flash:{}'.format(filename) net_connect = Netmiko(**device) output = net_connect.send_command_timing(command, strip_prompt=False, strip_command=False) if 'confirm' in output: # I don't confirm the file delete. output += net_connect.send_command_timing('n', strip_prompt=False, strip_command=False) else: raise ValueError("Expected confirm message in output") print() print('-' * 80) print(output) print('-' * 80) print()
password = getpass() R1 = { 'host': '192.168.0.51', 'username': '******', 'password': password, 'device_type': 'cisco_ios' } filename = 'test' command = 'delete unix:{}'.format(filename) net_conn = Netmiko(**R1) output = net_conn.send_command_timing(command) if 'Delete filename' in output: output += net_conn.send_command_timing('\n') if 'confirm' in output: output += net_conn.send_command_timing('\n') net_conn.disconnect() print() print('-' * 80) print(output) print('-' * 80) print()