def main(): for device in rtr_list: rtr_conn = ConnectHandler(**device) prompt = rtr_conn.find_prompt() rtr_conn.config_mode() output = rtr_conn.send_config_from_file(config_file='4_8_cfg.txt') print output
def main(): ip_addr = '50.76.53.27' port_rtr1 = 22 port_rtr2 = 8022 username = '******' password = '******' #password = getpass() pynet1 = { 'device_type': 'cisco_ios', 'ip': ip_addr, 'username': username, 'password': password, 'port': port_rtr1, } pynet_rtr1 = ConnectHandler(**pynet1) pynet_rtr1.find_prompt() print "we are getting into config mode" pynet_rtr1.config_mode() if pynet_rtr1.check_config_mode(): print "yes, we are in config mode" else: print "sometthing is wrong, we are not in config mode!"
def main(): password = getpass() py_router_2 = { 'device_type':'cisco_ios', 'ip':'50.76.53.27', 'username':'******', 'password':password, 'port':8022, } rtr2 = ConnectHandler(**py_router_2) rtr2.config_mode() output = rtr2.check_config_mode() print "RTR Config mode is %s" % output if (output is True): #config_command = ['loggin buffered 5555'] #output = rtr2.send_config_set(config_command) output = rtr2.send_config_from_file(config_file='config_file.txt') print "Changes send to router.\n %s" % output rtr2.exit_config_mode() else: print "Could not get to config mode.\n"
def main(): #password = getpass() password = '******' # Define libraries for devices we will connect to pynet1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 22, } pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } srx = { 'device_type': 'juniper', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 9822, } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() outp = pynet_rtr2.find_prompt() print outp outp2 = pynet_rtr2.check_config_mode() print 'Config mode status is ' + str(outp2)
def main(): username = '******' password = '******' pynet1 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': username, 'password': password, 'port': 22, } pynet2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': username, 'password': password, 'port': 8022, } juniper_srx = { 'device_type': 'juniper', 'ip': '50.76.53.27', 'username': username, 'password': password, 'secret': '', 'port': 9822, } pynet_rtr2 = ConnectHandler( **pynet2 ) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode() : print "We are in config mode for pynet rtr2" else: print "No config mode for pynet rtr2"
def main(): rlist = [pynet1, pynet2] for router in rlist: rtr = ConnectHandler(**router) rtr.config_mode() rtr.send_config_from_file(config_file='configfile.txt') rtr.exit_config_mode()
def main(): '''Main function, opens connection, enters config mode and verifies''' pynet_rtr1 = ConnectHandler(**device_list.RTR1) pynet_rtr1.config_mode() if pynet_rtr1.check_config_mode(): print "We are in Config mode" else: print "We are NOT in Config mode"
def main(): password = getpass pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): print "You are in config mode.\n" else: print "Config mode failed.\n"
def main(): """ se Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode). """ pynet_rtr1 = ConnectHandler(**PYNET1) pynet_rtr1.config_mode() router_mode(pynet_rtr1)
def main(): '''Main function, opens connection, enters config mode, changes logging and verifies''' pynet_rtr2 = ConnectHandler(**RTR2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): pynet_rtr2.send_command("logging buffered 16384") pynet_rtr2.exit_config_mode() output = pynet_rtr2.send_command("show run | include logging buff") print output else: print "We are NOT in Config mode"
def main(): ''' Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode). ''' pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() output = pynet_rtr2.check_config_mode() print print 'Checking to see if we are in config mode:' print output print
def main(): ''' Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2. ''' pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() config_commands = ['logging buffered 102400'] output = pynet_rtr2.send_config_set(config_commands) print print output print
def main(): ''' Logs into each router and executes commands cmd and ver ''' print '=' *80 ssh_conn = ConnectHandler(**device) ssh_conn.config_mode() ssh_conn.send_command(cmd) output = ssh_conn.send_command(ver) prompt = ssh_conn.find_prompt() print '\n %s from %s \n %s' %(cmd, prompt, output) print print '=' *80
def main(): password = getpass() for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password net_connect2 = ConnectHandler(**pynet2) net_connect2.config_mode() print "Config mode:{}".format(net_connect2.check_config_mode()) print "Current prompt: {}".format(net_connect2.find_prompt())
def main(): pynet2 = { 'device_type': 'cisco_ios', 'ip' : '50.76.53.27', 'username' : 'pyclass', 'port' : 8022, 'password' : '88newclass' } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): print "We're in config mode" pynet_rtr2.send_command("logging buffered 33333") else: print "Nope, We're NOT in config mode"
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' net_connect = ConnectHandler(**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 main(): # Definition of rtr2. rtr2 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': '******', 'port': 8022, } # Log into router. net_connect = ConnectHandler(**rtr2) # Check current logging buffer size. output = net_connect.send_command("show run | inc buffered") print print "Initial logging buffer size: " + output # Enter config mode, change logging buffer size, exit config mode. output = net_connect.config_mode() output = net_connect.send_command("logging buffer 64000") output = net_connect.exit_config_mode() # Check logging buffer size again. output = net_connect.send_command("show run | inc buffered") print "Final logging buffer size: " + output print
def setup_module(module): module.EXPECTED_RESPONSES = { 'base_prompt' : 'openstack-rb5', 'config_mode' : '(config)', } net_connect = ConnectHandler(**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 main(): ''' Connects to router and switches to config mode ''' pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.enable() pynet_rtr2.config_mode() ''' Checks to see if you are in enable mode and prints results to screen ''' if pynet_rtr2.check_config_mode() is True: output = pynet_rtr2.find_prompt() print output else: print 'You are NOT in config mode'
def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'n7k1#', 'base_prompt' : 'n7k1', 'interface_ip' : '10.3.3.245', 'config_mode' : '(config)' } show_ver_command = 'show version' module.basic_command = 'show ip int brief' net_connect = ConnectHandler(**cisco_nxos) 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 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 main(): ''' Using Netmiko enter into configuration mode on a network device. Verify that you are currently in configuration mode. ''' password = getpass() for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password net_connect2 = ConnectHandler(**pynet2) net_connect2.config_mode() print "\n>>>>" print "Checking pynet-rtr2 is in configuration mode." print "Config mode check: {}".format(net_connect2.check_config_mode()) print "Current prompt: {}".format(net_connect2.find_prompt()) print ">>>>\n"
def main(): device_list = getConfig() for device in device_list: print "Please input password for: " + device.get('rtr_name') device['password']=getpass() device.pop("rtr_name",None) conn=ConnectHandler(**device) conn.config_mode() if (conn.check_config_mode): print "In config" conn.exit_config_mode() print "Arp table\n" + conn.send_command("sh arp") if ('cisco_ios' in device.get('device_type')): config_commands = ["do show run | i buffered","logging buffered 12000","do sh run | i buffered"] output = conn.send_config_set(config_commands) print output output = conn.send_config_from_file(config_file='config_file.txt') print output
def main(): pynet2 = { 'device_type': 'cisco_ios', 'ip' : '50.76.53.27', 'username' : 'pyclass', 'port' : 8022, 'password' : '88newclass' } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() if pynet_rtr2.check_config_mode(): print "We're in config mode" else: print "Nope, We're NOT in config mode" print pynet_rtr2.find_prompt() pynet_rtr2.exit_config_mode() print pynet_rtr2.find_prompt()
def main(): password = getpass() py_router_2 = { 'device_type':'cisco_ios', 'ip':'50.76.53.27', 'username':'******', 'password':password, 'port':8022, } rtr2 = ConnectHandler(**py_router_2) rtr2.config_mode() output = rtr2.check_config_mode() print "RTR Config mode is %s" % output rtr2.exit_config_mode()
def main(): ''' Use Netmiko to enter into configuration mode on pynet-rtr2. Also use Netmiko to verify your state (i.e. that you are currently in configuration mode). ''' ip_address = raw_input("Please enter IP: ") password = getpass() pynet_rtr2['ip'] = ip_address pynet_rtr2['password'] = password ssh_conn = ConnectHandler(**pynet_rtr2) ssh_conn.config_mode() if ssh_conn.check_config_mode(): print "In config mode"
def main(): password = getpass() pynet_rtr1 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 22} pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022} for ssh in pynet_rtr1, pynet_rtr2: ssh_connection = ConnectHandler(**ssh) ssh_connection.config_mode() ssh_connection.send_config_from_file(config_file='commands_file.txt') output = ssh_connection.send_command('show run | inc logging') hostname = ssh_connection.send_command('show run | inc hostname pynet').split() print '*' * 10 + " New logging configurations for Cisco router %s " % hostname[1] + '*' * 10 print output print '*' * 76
def main(): password = getpass() for a_dict in (pynet1, pynet2, juniper_srx): a_dict['password'] = password net_connect2 = ConnectHandler(**pynet2) net_connect2.config_mode() net_connect2.send_command("logging buffered 21110") net_connect2.send_command("end") output = net_connect2.send_command("show run | i logging") print output
def main(): password = getpass() pynet_rtr2 = { "device_type": "cisco_ios", "ip": "50.76.53.27", "username": "******", "password": password, "port": 8022, } ssh_connection = ConnectHandler(**pynet_rtr2) ssh_connection.config_mode() logging_command = ["logging buffered 20031"] ssh_connection.send_config_set(logging_command) output = ssh_connection.send_command("show run | inc logging buffered") outp = output.split() print "The new size of logging buffered is %s" % outp[2]
def main(): ''' Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2 ''' ip_address = raw_input("Enter IP address: ") password = getpass() pynet_rtr2['ip'] = ip_address pynet_rtr2['password'] = password ssh_conn = ConnectHandler(**pynet_rtr2) ssh_conn.config_mode() if ssh_conn.check_config_mode: ssh_conn.send_command('logging buffered 999999') ssh_conn.exit_config_mode() output = ssh_conn.send_command('show run | in logging') print output
def main(): ''' Using Netmiko enter into configuration mode on a network device. Verify that you are currently in configuration mode. ''' ip_addr = raw_input("Enter IP Address: ") password = getpass() for a_dict in (pynet1, pynet2, juniper_srx): a_dict['ip'] = ip_addr a_dict['password'] = password pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() print "\n>>>>" print "Checking pynet-rtr2 is in configuration mode" print "Config mode check: {}".format(pynet_rtr2.check_config_mode()) print "Current prompt: {}".format(pynet_rtr2.find_prompt()) print ">>>>\n"
#!/usr/bin/env python from __future__ import print_function from netmiko import ConnectHandler pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': '******', 'port': 22 } net_connect = ConnectHandler(**pynet2) net_connect.config_mode() if net_connect.check_config_mode() is True: print(net_connect.find_prompt()) net_connect.exit_config_mode() net_connect.disconnect()
def connect_ssh(device_dict, commands_set, cmd_exec_logic, fileno=None): ''' Connect to device and execute command list !!! tested for cisco_ios!!! Arg: devices: parameters of device (dict) queue: list of result commands_set: list of commands cmd_exec_logic: logic of execution ''' # We need to copy dict in list of command (create new object), otherwise we will get last commands set (result) for all nodes (change same object of commands) if not fileno == None: sys.stdin = os.fdopen(fileno) commands = copy.deepcopy(commands_set) queue = {} nodename = device_dict.get('nodename') del (device_dict['nodename']) print("%s[%s]%s Connection to device %s" % (bcolors.HEADER, nodename, bcolors.ENDC, device_dict['ip'])) logging.info("Connection to device %s" % device_dict['ip']) try: ssh = ConnectHandler(**device_dict) except Exception as e: logging.debug('\nConnect failed! {}'.format(e)) print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Connect failed! {1}'. format(nodename, e)) logging.info("Stop executing commands") print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Stop executing commands' .format(nodename)) failed_dic = [{'cmdname': 'Err', 'output': str(e), 'search': ''}] queue[nodename] = failed_dic return queue ssh.enable() for cmd_index, command in enumerate(commands): logging.debug('\n $command=:\n{} '.format(pformat(command))) #Checking command if command.get('command') == None: logging.debug( '\nSomething wrong in command syntax\'s! Incoming config for current command:\n{} ' .format(pformat(command.get('command')))) print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Something wrong in command syntax\'s! Incoming config for current command:\n{1} ' .format(nodename, pformat(command.get('command')))) logging.info("Stop executing commands") print( '\n\033[95m[{0}]\033[0m [\033[91mErr\033[0m] Stop executing commands' .format(nodename)) failed_dic = [{ 'cmdname': 'Err', 'output': 'Something wrong in command syntax', 'search': '' }] queue[nodename] = failed_dic return queue cmd = '' cmd_list = [] cmd_var_search = [] #build-in variables cmd_var_search = re.findall('\{\}', command.get('command')) command['command'] = re.sub('\{nodename\}', nodename, command.get('command')) command['command'] = re.sub('\{nodeip\}', device_dict['ip'], command.get('command')) command['command'] = re.sub('\{datetime\}', time.strftime("%Y%m%d%H%M%S"), command.get('command')) command['command'] = re.sub('\{date\}', time.strftime("%Y%m%d"), command.get('command')) command['search'] = re.sub('\{nodename\}', nodename, command.get('search')) command['search'] = re.sub('\{nodeip\}', device_dict['ip'], command.get('search')) command['search'] = re.sub('\{datetime\}', time.strftime("%Y%m%d%H%M%S"), command.get('search')) command['search'] = re.sub('\{date\}', time.strftime("%Y%m%d"), command.get('search')) command['device_type'] = device_dict['device_type'] if command.get('delay_factor') == '': logging.debug("set def delay_factor") command['delay_factor'] = '1' if cmd_var_search: result = re.findall(commands[cmd_index - 1].get('search'), commands[cmd_index - 1].get('output')) if result: cmd_parrent = command.get('command') for var_index, var in enumerate(result): cmd = cmd_parrent.format(var) if var_index == 0: commands[cmd_index]['command'] = cmd else: cmd_dic = {} cmd_dic = command.copy() cmd_dic['command'] = cmd cmd_dic['cmdname'] = cmd_dic.get( 'cmdname') + '(' + str(var_index) + ')' commands.insert(cmd_index + var_index, cmd_dic) logging.debug('\nNew command list:\n' + pformat(commands)) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break cmd_varlist_search = [] cmd_varlist_search = re.findall('\{\$\S+\}', command.get('command')) if cmd_varlist_search: table = get_result(commands[cmd_index - 1]) #check if result is list and not empty if len(table) >= 2 and type(table) == list: cmd_parrent = command.get('command') for varline_index, varline in enumerate(table): if varline_index == 0: continue new_cmd = cmd_parrent for var_index, var in enumerate(varline): if var_index == 0: continue new_cmd = re.sub('\{\$' + table[0][var_index] + '\}', var, new_cmd) if varline_index == 1: commands[cmd_index]['command'] = new_cmd else: cmd_dic = {} cmd_dic = command.copy() cmd_dic['command'] = new_cmd cmd_dic['cmdname'] = cmd_dic.get( 'cmdname') + '(' + str(varline_index) + ')' commands.insert(cmd_index + varline_index, cmd_dic) logging.debug('\nNew command list:\n' + pformat(commands)) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break print("%s[%s]%s Try to execute command: %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info("Try to execute command: %s on device: %s:" % (command.get('command'), device_dict['ip'])) cmd = command.get('command') if command.get('cmd_type') == 'usr_req': usr_req = raw_input('{}[{}]{} {}{}{}'.format( bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, command.get('command'), bcolors.ENDC)) commands[cmd_index + 1]['search'] = re.sub( '\{usr_req\}', usr_req, commands[cmd_index + 1]['search']) commands[cmd_index]['output'] = usr_req commands[cmd_index]['search'] = usr_req commands[cmd_index]['search_type'] = 'simple' if command.get('cmd_type') == 'choose_req': print('{}[{}]{} {}{}{}'.format(bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, command.get('command'), bcolors.ENDC)) table = get_result(commands[cmd_index - 1]) if len(table) >= 2: print(tabulate(table, headers='firstrow', tablefmt="pipe")) while True: usr_input = raw_input( '{}[{}]{} {}Enter number of line:{}'.format( bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, bcolors.ENDC)) try: usr_input = int(usr_input) except: print( '{}[{}]{} {}Entered not number of line, please enter number{}' .format(bcolors.HEADER, nodename, bcolors.ENDC, bcolors.WARNING, bcolors.ENDC)) continue if usr_input in range(0, len(table) - 1): break else: print('{}Enter number of line in range {}{}'.format( bcolors.WARNING, range(0, len(table) - 1), bcolors.ENDC)) var_dict = dict(zip(table[0], table[usr_input + 1])) for var in var_dict: if var == 'N': continue commands[cmd_index + 1]['command'] = re.sub( '\{' + str(var) + '\}', var_dict.get(var), commands[cmd_index + 1]['command']) command['output'] = str(usr_input) else: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break if command.get('command') == 'timeout': print("%s[%s]%s Start timeout of executing script: %s" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('delay_factor'))) time.sleep(int(command.get('delay_factor'))) command['output'] = 'Timeout: %ssec' % ( command.get('delay_factor')) print("%s[%s]%s Continue executing script" % ( bcolors.HEADER, nodename, bcolors.ENDC, )) if command.get('command') == 'enter': cmd = '\n' if command.get( 'cmd_type') == 'conf_tpl' and not command.get('command') == '': command['command'] = parce_node_conf_template(nodename, command) command['cmd_type'] = 'conf_set' if command.get('cmd_type') == 'conf_enter': command['output'] = ssh.config_mode() elif command.get('cmd_type') == 'conf_exit': command['output'] = ssh.exit_config_mode() elif command.get('cmd_type') == 'conf_set': cmd_list = command.get('command').split(',') #for debug #print ('Find prompt is %s' % (ssh.find_prompt())) #prompt = ssh.send_command('\n', strip_prompt = False, strip_command = False, expect_string = '.*', auto_find_prompt=False) #print ('Current prompt is %s' % (prompt)) ssh.set_base_prompt() command['output'] = ssh.send_config_set( cmd_list, strip_prompt=False, strip_command=False, delay_factor=int(command.get( 'delay_factor'))) #.encode('ascii').decode('utf-8') elif command.get('cmd_type') == 'os_exec': cmd = re.sub('\<\>', check_output(commands[cmd_index - 1]), command.get('command')) #result = re.findall(commands[cmd_index-1].get('search'), commands[cmd_index-1].get('output')) #cmd = re.sub('\<\>', tabulate(result, headers=re.findall('P<(\w+)>', commands[cmd_index-1].get('search')), tablefmt='html'), command.get('command')) cmd = re.sub('\{command\}', commands[cmd_index - 1].get('command'), cmd) cmd = re.sub('\{nodename\}', nodename, cmd) cmd = re.sub('\{ip\}', device_dict['ip'], cmd) cmd = re.sub('\n', '\n\r', cmd) #print (cmd) command['output'] = sp.check_output(cmd, shell=True) elif command.get('output') == None: #print (ssh.find_prompt()) #print command.get('expect') current_prompt = '.*' if not command.get('expect'): try: current_prompt = ssh.find_prompt() logging.debug('Current prompt is %s' % (ssh.find_prompt())) except Exception as e: logging.debug('\nUnable to find prompt! {}'.format(e)) #print('\n[{0}] Unable to find prompt! {1}'.format(nodename, e)) expect_prompt = get_expect_string(command, current_prompt, device_dict['device_type']) if expect_prompt == "": try: command['output'] = ssh.send_command( cmd, strip_prompt=False, strip_command=False, delay_factor=int(command.get('delay_factor'))) #. except Exception as e: logging.debug('\nError {}'.format(e)) print('\n{}[{}]{} Error {}'.format( bcolors.HEADER, nodename, bcolors.ENDC, e)) break else: expect_prompt = command.get('expect') logging.debug('Expect prompt = %s' % (expect_prompt)) try: command['output'] = ssh.send_command( cmd, strip_prompt=False, strip_command=False, delay_factor=int(command.get('delay_factor')), expect_string=expect_prompt, auto_find_prompt=False) #.encode('ascii').decode('utf-8') except Exception as e: logging.debug('\nError! {}'.format(e)) print('\n{}[{}]{} Error {}'.format(bcolors.HEADER, nodename, bcolors.ENDC, e)) break logging.info("Checking executing commands logic:") if cmd_exec_logic.get('cmd_exec_err_logic') or cmd_exec_logic.get( 'cmd_exec_searchfail_logic'): print('{}[{}]{} Check command {} for error'.format( bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'))) result = chech_fail_exec(command, cmd_exec_logic) if result: logging.info("Stop executing commands") print( "%s[%s]%s [\033[91mErr\033[0m] Stop executing commands list on command %s on device: %s:" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) logging.info( "Stop executing commands list on command %s on device: %s:" % (command.get('command'), device_dict['ip'])) break logging.info("Command: %s on device: %s executed successfully" % (command.get('command'), device_dict['ip'])) if command.get('cmd_type') == 'conf_set': print( "%s[%s]%s Command: \n%s\n on device: %s executed successfully" % (bcolors.HEADER, nodename, bcolors.ENDC, re.sub(',', '\n', command.get('command')), device_dict['ip'])) else: print( "%s[%s]%s Command: %s on device: %s executed successfully" % (bcolors.HEADER, nodename, bcolors.ENDC, command.get('command'), device_dict['ip'])) #add report logic, split search_type if len(command.get('search_type').split(',')) > 1: command['search_type'] = command.get('search_type').split(',')[0] command['last_val'] = 'last' queue[nodename] = commands logging.debug('\nEnd working whith node, result:\n{} '.format( pformat(queue))) try: if not fileno == None: os.close(fileno) except Exception as e: logging.debug('\nClose failed! {}'.format(e)) return queue
class CiscoDevice: def __init__(self): device_type = ui.get_device_type_window() self.host = ui.get_device_window() username, password, secret = ui.get_credentials_window(self.host) self.device = { 'device_type': device_type, 'host': self.host, 'username': username, 'password': password, 'secret': secret } def __enter__(self): self.remote_conn = ConnectHandler(**self.device) return self def version(self): """Execute show version command.""" print(f"Version information for: {self.device['host']}") print('~' * 100) print(self.remote_conn.send_command('show version')) @property def clock(self): """Returns the time and date on the device.""" print(f"Fetching time information from {self.device['host']}") self.remote_conn.enable() clock_str = self.remote_conn.send_command('show clock').replace('*', '').strip() self.remote_conn.config_mode() clock = datetime.strptime(clock_str, '%H:%M:%S.%f %Z %a %b %d %Y') clock_utc = pytz.utc.localize(clock) return clock_utc.strftime('%H:%M:%S %Z %a %b %d %Y') @clock.setter def clock(self, datetime_obj): """ Sets the clock of the device using Netmiko. :param (datetime_obj): an instance of the datetime.datetime class """ if isinstance(datetime_obj, datetime): equipment_date_raw = self.remote_conn.send_command('show clock') \ .replace('*', '').strip() equipment_date = datetime.strptime( equipment_date_raw, '%H:%M:%S.%f %Z %a %b %d %Y' ) timedelta = abs((equipment_date - datetime_obj).total_seconds()) if timedelta > 30: date = datetime_obj.strftime('%H:%M:%S %d %b %Y') print(f"{self.device['host']} - \ Clock Offset: {timedelta} seconds. \ Setting clock: {date}" ) self.remote_conn.enable() self.remote_conn.send_command(f'clock set {date}') else: print(f"{self.device['host']} - {equipment_date_raw} - Clock OK") else: raise ValueError('Must assign a datetime object.') @property def hostname(self): """Returns the hostname of the device.""" print(f"Fetching hostname information from {self.device['host']}") name = self.remote_conn.find_prompt().replace('#', '') return name @hostname.setter def hostname(self, name): """ Sets the hostname of the device. :param name: (str) must contain at least one alphabet or '-' or '_' character """ if search('[a-zA-z_-]', name): print(f'Setting hostname {name} to {self.host}') self.remote_conn.send_command(f'hostname {name}') print(self.remote_conn.find_prompt()) else: raise ValueError("Hostname should contain at least one alphabet or '-' or '_' character") def get_users(self): """Returns a list of configured users.""" print(f"Fetching users information from {self.device['host']}") self.remote_conn.enable() users_str = self.remote_conn.send_command('show running-config | include username').split('\n') user_list = [] for line in users_str: user_list.append(line.split()[1]) return user_list def add_user(self): username, password, privilege = ui.add_user_window(self.host, self.get_current_user_privilege()) if self.remote_conn.check_enable_mode(): self.remote_conn.config_mode() self.remote_conn.send_command(f'username {username} privilege {privilege} password {password}') def delete_user(self): user_list = self.get_users() user = ui.delete_user_window(self.host, user_list) self.remote_conn.config_mode() self.remote_conn.send_command(f'no username {user}') @property def domain(self): """Returns the domain name configured on the device.""" print(f"Fetching domain information from {self.device['host']}") domain_name = self.remote_conn.send_command('show running-config | include domain').split()[-1] return domain_name @domain.setter def domain(self, domain_name): """ Sets the domain-name of the device. :param domain_name: (str) domain name of the device """ self.remote_conn.send_command(f"ip domain-name {domain_name}") def get_current_user_privilege(self): self.remote_conn.enable() privilege = int(self.remote_conn.send_command('show privilege').split()[-1]) return privilege def save_configuration(self): choice = ui.save_configuration_window() if choice: self.remote_conn.enable() self.remote_conn.send_command('write memory') def __exit__(self, *args): self.remote_conn.disconnect()
def main(): try: hostname = raw_input("Enter remote host to test: ") username = raw_input("Enter remote username: "******"Enter remote host to test: ") username = input("Enter remote username: "******"username": username, "use_keys": True, "ip": hostname, "device_type": "ovs_linux", "key_file": "/home/{}/.ssh/test_rsa".format(username), "verbose": False, } net_connect = ConnectHandler(**linux_test) print() print(net_connect.find_prompt()) # Test enable mode print() print("***** Testing enable mode *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_enable_mode() print("Out of enable mode") print(net_connect.find_prompt()) # Test config mode print() print("***** Testing config mode *****") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: in config mode") else: print("Fail...") print(net_connect.find_prompt()) net_connect.exit_config_mode() print("Out of config mode") print(net_connect.find_prompt()) # Test config mode (when already at root prompt) print() print("***** Testing config mode when already root *****") net_connect.enable() if net_connect.check_enable_mode(): print("Success: in enable mode") else: print("Fail...") print(net_connect.find_prompt()) print("Test config_mode while already at root prompt") net_connect.config_mode() if net_connect.check_config_mode(): print("Success: still at root prompt") else: print("Fail...") net_connect.exit_config_mode() # Should do nothing net_connect.exit_enable_mode() print("Out of config/enable mode") print(net_connect.find_prompt()) # Send config commands print() print("***** Testing send_config_set *****") print(net_connect.find_prompt()) output = net_connect.send_config_set(["ls -al"]) print(output) print()
device = { "host": "cisco4.lasthop.io", "username": "******", "password": password, "device_type": "cisco_ios", "secret": password, "session_log": "my_output.txt" } net_connect = ConnectHandler(**device) prompt = net_connect.find_prompt() print(prompt) prompt = net_connect.config_mode() print(prompt) prompt = net_connect.exit_config_mode() print(prompt) net_connect.write_channel("disable\n") time.sleep(2) prompt = net_connect.read_channel() print(prompt) prompt = net_connect.enable() print(prompt) '''
'device_type': 'cisco_ios', 'ip': '192.168.32.200', 'username': '******', 'password': '******', 'port': 22, 'secret': 'cisco123', # no username admin pri 15 // # enable secret cisco123 'verbose': True, } # connection123 = object, ** = dictionary used to call function connection123 = ConnectHandler(**cisco_device) prompt = connection123.find_prompt() print(prompt) if '>' in prompt: connection123.enable() # mode = connection123.check_enable_mode() # print(mode) output = connection123.send_command('show ip int br') print(output) mode = connection123.check_config_mode() # print(mode) if not mode: connection123.config_mode() # mode = connection123.check_config_mode() # print(mode) output = connection123.send_command('username joy password python123') output = connection123.send_command('do show run | i user') print(output)
import time net_device = { "host": 'cisco4.lasthop.io', "username": '******', "password": '******', "secret": '88newclass', "device_type": 'cisco_ios', "session_log":'my_cmd_logs.txt' } start_time = datetime.now() device = ConnectHandler(**net_device) print(device.find_prompt()) output = device.config_mode() print(device.find_prompt()) output = device.exit_config_mode() print(device.find_prompt()) print(device.write_channel('disable\n')) time.sleep(2) print(device.read_channel()) print(device.find_prompt()) print(device.enable()) print(device.find_prompt()) #pprint(output) device.disconnect() finish = datetime.now()
from netmiko import ConnectHandler import time cisco4 = { "host":" cisco4.lasthop.io", "username": "******", "password": "******", "secret": "88newclass", "device_type": "cisco_ios", "session_log": "week2_exercise6_log.txt", } cisco4_connect = ConnectHandler(**cisco4) print(cisco4_connect.find_prompt()) cisco4_connect.config_mode() print(cisco4_connect.find_prompt()) cisco4_connect.exit_config_mode() print(cisco4_connect.find_prompt()) print("\nExit privileged exec (disable), Current Prompt: ") cisco4_connect.write_channel("disable\n") time.sleep(2) output = cisco4_connect.read_channel() print(output) print("\nRe-enter enable mode, Current Prompt: ") cisco4_connect.enable() print(cisco4_connect.find_prompt()) cisco4_connect.disconnect() print()
device1 = { "host": "cisco4.lasthop.io", "username": "******", "password": "******", "secret": "88newclass", "device_type": "cisco_ios", "session_log": "my_session.txt" } net_connect = ConnectHandler(**device1) output = net_connect.find_prompt() print(output) output = net_connect.config_mode() print(output) output = net_connect.find_prompt() print(output) output = net_connect.exit_config_mode() print(output) output = net_connect.find_prompt() print(output) output = net_connect.write_channel('disable \n') print(output) time.sleep(2)
def main(): net_connect = ConnectHandler(**pynet.rtr1) print "Entering config mode..." print net_connect.config_mode() print "In config mode: " + str(net_connect.check_config_mode()) print "Current Prompt: " + net_connect.find_prompt()
class IOSDevice(BaseDevice): def __init__(self, host, username, password, secret='', port=22, **kwargs): super(IOSDevice, self).__init__(host, username, password, vendor='cisco', device_type=IOS_SSH_DEVICE_TYPE) self.native = None self.host = host self.username = username self.password = password self.secret = secret self.port = int(port) self._connected = False self.open() def open(self): if self._connected: try: self.native.find_prompt() except: self._connected = False if not self._connected: self.native = ConnectHandler(device_type='cisco_ios', ip=self.host, username=self.username, password=self.password, port=self.port, secret=self.secret, verbose=False) self._connected = True def close(self): if self._connected: self.native.disconnect() self._connected = False def _enter_config(self): self._enable() self.native.config_mode() def _enable(self): self.native.exit_config_mode() if not self.native.check_enable_mode(): self.native.enable() def _send_command(self, command, expect=False, expect_string=''): if expect: if expect_string: response = self.native.send_command_expect(command, expect_string=expect_string) else: response = self.native.send_command_expect(command) else: response = self.native.send_command_timing(command) if '% ' in response or 'Error:' in response: raise CommandError(command, response) return response def config(self, command): self._enter_config() self._send_command(command) self.native.exit_config_mode() def config_list(self, commands): self._enter_config() entered_commands = [] for command in commands: entered_commands.append(command) try: self._send_command(command) except CommandError as e: raise CommandListError( entered_commands, command, e.cli_error_msg) self.native.exit_config_mode() def show(self, command, expect=False, expect_string=''): self._enable() return self._send_command(command, expect=expect, expect_string=expect_string) def show_list(self, commands): self._enable() responses = [] entered_commands = [] for command in commands: entered_commands.append(command) try: responses.append(self._send_command(command)) except CommandError as e: raise CommandListError( entered_commands, command, e.cli_error_msg) return responses def save(self, filename='startup-config'): command = 'copy running-config %s' % filename # Changed to send_command_timing to not require a direct prompt return. self.native.send_command_timing(command) # If the user has enabled 'file prompt quiet' which dose not require any confirmation or feedback. This will send return without requiring an OK. # Send a return to pass the [OK]? message - Incease delay_factor for looking for response. self.native.send_command_timing('\n',delay_factor=2) # Confirm that we have a valid prompt again before returning. self.native.find_prompt() return True def _file_copy_instance(self, src, dest=None, file_system='flash:'): if dest is None: dest = os.path.basename(src) fc = FileTransfer(self.native, src, dest, file_system=file_system) return fc def file_copy_remote_exists(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() if fc.check_file_exists() and fc.compare_md5(): return True return False def file_copy(self, src, dest=None, file_system='flash:'): fc = self._file_copy_instance(src, dest, file_system=file_system) self._enable() # if not self.fc.verify_space_available(): # raise FileTransferError('Not enough space available.') try: fc.enable_scp() fc.establish_scp_conn() fc.transfer_file() except: raise FileTransferError finally: fc.close_scp_chan() def reboot(self, timer=0, confirm=False): if confirm: def handler(signum, frame): raise RebootSignal('Interrupting after reload') signal.signal(signal.SIGALRM, handler) signal.alarm(10) try: if timer > 0: first_response = self.show('reload in %d' % timer) else: first_response = self.show('reload') if 'System configuration' in first_response: self.native.send_command_timing('no') self.native.send_command_timing('\n') except RebootSignal: signal.alarm(0) signal.alarm(0) else: print('Need to confirm reboot with confirm=True') def _is_catalyst(self): return self.facts['model'].startswith('WS-') def set_boot_options(self, image_name, **vendor_specifics): if self._is_catalyst(): self.config('boot system flash:/%s' % image_name) else: self.config_list(['no boot system', 'boot system flash %s' % image_name]) def get_boot_options(self): if self._is_catalyst(): show_boot_out = self.show('show boot') boot_path_regex = r'BOOT path-list\s+:\s+(\S+)' boot_path = re.search(boot_path_regex, show_boot_out).group(1) boot_image = boot_path.replace('flash:/', '') return dict(sys=boot_image) else: show_boot_out = self.show('show run | inc boot') boot_path_regex = r'boot system flash (\S+)' match = re.search(boot_path_regex, show_boot_out) if match: boot_image = match.group(1) else: boot_image = None return dict(sys=boot_image) def backup_running_config(self, filename): with open(filename, 'w') as f: f.write(self.running_config) def _uptime_components(self, uptime_full_string): match_days = re.search(r'(\d+) days?', uptime_full_string) match_hours = re.search(r'(\d+) hours?', uptime_full_string) match_minutes = re.search(r'(\d+) minutes?', uptime_full_string) days = int(match_days.group(1)) if match_days else 0 hours = int(match_hours.group(1)) if match_hours else 0 minutes = int(match_minutes.group(1)) if match_minutes else 0 return days, hours, minutes def _uptime_to_string(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) return '%02d:%02d:%02d:00' % (days, hours, minutes) def _uptime_to_seconds(self, uptime_full_string): days, hours, minutes = self._uptime_components(uptime_full_string) seconds = days * 24 * 60 * 60 seconds += hours * 60 * 60 seconds += minutes * 60 return seconds def _interfaces_detailed_list(self): ip_int_br_out = self.show('show ip int br') ip_int_br_data = get_structured_data('cisco_ios_show_ip_int_brief.template', ip_int_br_out) return ip_int_br_data def _show_vlan(self): show_vlan_out = self.show('show vlan') show_vlan_data = get_structured_data('cisco_ios_show_vlan.template', show_vlan_out) return show_vlan_data def _raw_version_data(self): show_version_out = self.show('show version') try: version_data = get_structured_data('cisco_ios_show_version.template', show_version_out)[0] return version_data except IndexError: return {} def rollback(self, rollback_to): try: self.show('configure replace flash:%s force' % rollback_to) except CommandError: raise RollbackError('Rollback unsuccessful. %s may not exist.' % rollback_to) def checkpoint(self, checkpoint_file): self.save(filename=checkpoint_file) @property def facts(self): if hasattr(self, '_facts'): return self._facts facts = {} facts['vendor'] = self.vendor version_data = self._raw_version_data() show_version_facts = convert_dict_by_key(version_data, ios_key_maps.BASIC_FACTS_KM) facts.update(show_version_facts) uptime_full_string = version_data['uptime'] facts['uptime'] = self._uptime_to_seconds(uptime_full_string) facts['uptime_string'] = self._uptime_to_string(uptime_full_string) facts['fqdn'] = 'N/A' facts['interfaces'] = list(x['intf'] for x in self._interfaces_detailed_list()) if show_version_facts['model'].startswith('WS'): facts['vlans'] = list(str(x['vlan_id']) for x in self._show_vlan()) else: facts['vlans'] = [] # ios-specific facts ios_facts = facts[IOS_SSH_DEVICE_TYPE] = {} ios_facts['config_register'] = version_data['config_register'] self._facts = facts return facts @property def running_config(self): return self.show('show running-config', expect=True) @property def startup_config(self): return self.show('show startup-config')
if __name__ == "__main__": verbose = True username = raw_input("Username: "******"Password: "******"crtlist") devlist = [d.rstrip() for d in f.readlines()] f.close() for dev in devlist: nc = ConnectHandler(device_type='juniper', ip=dev, username=username, password=password, verbose=verbose) # into config mode nc.config_mode() nc.send_command('delete forwarding-options apply-groups dhcp') nc.send_command('delete routing-instances apply-groups dhcp') print nc.send_command('show | compare') nc.send_command('rollback 0') #print "committing..." #nc.commit() nc.exit_config_mode() print "exiting" nc.disconnect()
class NetmikoSSH(object): """Contains methods for managing and using SSH connections for Network Devices using Netmiko""" __MAX_RECV_BUF = 10 * 1024 * 1024 __existing_connections = {} def __init__(self): self._session = None self._node = None self._device = {} @staticmethod def _node_hash(node, port): """Get IP address and port hash from node dictionary. :param node: Node in topology. :param port: :type node: dict :return: IP address and port for the specified node. :rtype: int """ return hash(frozenset([node['mgmt_ip'], port])) @staticmethod def _get_device_type(node): device_os = node['os'] if str(device_os) in os_netmiko_map.keys(): return os_netmiko_map[str(device_os)] return None def net_connect(self, node): """Connect to node using Netmiko's inbuilt libraries. :param node: The node to disconnect from. :type node: dict """ self._node = node ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: self._session = NetmikoSSH.__existing_connections[node_hash] logger.debug('reusing ssh: {0}'.format(self._session)) else: start = time() self._device = { 'device_type': NetmikoSSH._get_device_type(node), 'ip': node['mgmt_ip'], 'username': node['username'], 'password': node['password'], 'port': ssh_port } self._session = ConnectHandler(**self._device) NetmikoSSH.__existing_connections[node_hash] = self._session logger.trace('connect took {} seconds'.format(time() - start)) logger.debug('new connection: {0}'.format(self._session)) logger.debug('Connections: {0}'.format( str(NetmikoSSH.__existing_connections))) def net_disconnect(self, node): """Close SSH connection to the node. :param node: The node to disconnect from. :type node: dict """ ssh_port = Topology.get_ssh_port_from_node(node) node_hash = NetmikoSSH._node_hash(node, ssh_port) if node_hash in NetmikoSSH.__existing_connections: logger.debug('Disconnecting peer: {}, {}'.format( node['name'], ssh_port)) ssh = NetmikoSSH.__existing_connections.pop(node_hash) self._session.disconnect() def _reconnect(self): """Close the SSH connection and open it again.""" node = self._node self.net_disconnect(node) self.net_connect(node) def config_mode(self): """Enter into config mode """ self.net_connect(self._node) self._session.config_mode() def check_config_mode(self): """ Check if session is currently in config mode""" self.net_connect(self._node) return self._session.check_config_mode() def exit_config_mode(self): """Exit config mode""" self.net_connect(self._node) self._session.exit_config_mode() def clear_buffer(self): """ Clear logging buffer """ self.net_connect(self._node) self._session.clear_buffer() def enable(self): """ Enter Enable Mode""" self.net_connect(self._node) self._session.enable() def exit_enable_mode(self): """ Exit enable mode """ self.net_connect(self._node) self._session.exit_enable_mode() def find_prompt(self): """Return the current router prompt""" self.net_connect(self._node) self._session.find_prompt() def send_command(self, cmd): """Send command down the SSH channel and return output back :param cmd :type cmd: str """ if cmd is None: raise TypeError('Command parameter is None') if len(cmd) == 0: raise ValueError('Empty command parameter') self.net_connect(self._node) return self._session.send_command(cmd) def send_config_set(self, config_cmds): """Send a set of configuration commands to remote device :param config_cmds :type config_cmds: str """ if config_cmds is None: raise TypeError('Config Cmds parameter is None') self.net_connect(self._node) print "Netmiko NODE !!!\n\n" print self._node return self._session.send_config_set(config_cmds) def send_config_from_file(self, cfg_file): """Send a set of configuration commands loaded from a file :param cfg_file :type cfg_file: file """ if not os.path.isfile(cfg_file): raise TypeError('Config file does not exist') self.net_connect(self._node) self._session.send_config_from_file(cfg_file)
import time host_cisco4 = { "host": 'cisco4.lasthop.io', "username": '******', "password": getpass(), "secret": getpass(), "device_type": 'cisco_ios', #"fast_cli": True, "session_log": './session_logs/session_log_cisco4.txt', } host_connect = ConnectHandler(**host_cisco4) print(host_connect.find_prompt()) host_connect.config_mode() print(host_connect.find_prompt()) host_connect.exit_config_mode() print(host_connect.find_prompt()) host_connect.write_channel("disable\n") time.sleep(2) print(host_connect.read_channel()) host_connect.enable() print(host_connect.find_prompt()) host_connect.disconnect()
'device_type': 'cisco_ios', #device type from https://github.com/ktbyers/netmiko/blob/master/netmiko/ssh_dispatcher.py 'host': '10.1.1.10', 'username': '******', 'password': '******', 'port': 22, # optional, default 22 'secret': 'cisco', # this is the enable password 'verbose': True # optional, default False } connection = ConnectHandler(**cisco_device) # getting the router's prompt prompt = connection.find_prompt() if '>' in prompt: connection.enable() # entering the enable mode output = connection.send_command('sh run') print(output) if not connection.check_config_mode( ): # returns True if it's already in the global config mode connection.config_mode() # entering the global config mode # print(connection.check_config_mode()) connection.send_command('username u3 secret cisco') connection.exit_config_mode() # exiting the global config mode print(connection.check_config_mode()) print('Closing connection') connection.disconnect()
''' Multiple commands can be executed on a device from a list or from a file''' from netmiko import ConnectHandler cisco_device = { 'device_type': 'cisco_ios', 'ip':'10.1.1.10', 'username':'******', 'password': '******', 'port':'22', 'secret':'cisco' } #List of commands commands = ['int loopback 3', 'ip address 3.3.3.3 255.255.255.255','exit'] connection = ConnectHandler(**cisco_device) connection.enable() connection.config_mode() output = connection.send_config_set(commands) print (output) connection.send_command_expect('wr') connection.disconnect()
def execute_acl(module): data = module.params.copy() del data['lists'] connect = ConnectHandler(**data) acl_config = connect.send_command('show running-config access-list') connect.config_mode() has_changed = 0 has_not_changed = 0 for acl in module.params['lists']: cmd = connect.send_command(acl) regex = re.search('(error|warning)', cmd, re.IGNORECASE) ace = acl.split() if ace[0] == 'no': del ace[0] no_acl = ' '.join(ace) if no_acl in acl_config: if regex: result = { "Status": "Something went wrong with this ACL:" + " " + str(acl) } module.fail_json(msg=result) has_changed += 1 else: has_not_changed += 1 elif ace[0] == 'access-list': if acl not in acl_config: if regex: result = { "Status": "Something went wrong with this ACL:" + " " + str(acl) } module.fail_json(msg=result) has_changed += 1 else: has_not_changed += 1 if has_changed > 0: connect.send_command('write memory') result = { "status": "Changed some access-lists(s)," + " " + "running-config saved" } module.exit_json(changed=has_changed, meta=result) elif (has_not_changed > 0 and has_not_changed == len(module.params['lists']) and has_changed == 0): result = {"status": "Nothing to change"} module.exit_json(changed=False, meta=result) else: result = { "status": "Something went really wrong" + " " + "running-config has not been saved", "cmd": acl } module.fail_json(msg=result)
'device_type': 'juniper', 'ip': '50.76.53.27', 'username': '******', 'password': '******', 'port': 9822 } rtr2 = ConnectHandler(**pynetrtr2) # passes in dictionary key values into the function output = rtr2.find_prompt() print output output = rtr2.send_command('show run | in logging') print output output = rtr2.config_mode() print output output = rtr2.check_config_mode() print output output = rtr2.send_command('logging buffered 32769') print output output = rtr2.send_command('end') print output output = rtr2.send_command('show run | in logging') print output
def ConfigurationTest(ip, Device_Type_Num=0, User_Pass_Num=0, Passowrd_Enable_Num=0): global num_New # so we can edit it in this Function # def ConfigurationTest(ip,Device_Type_Num= 0,User_Pass_Num= 0): if ConfigurationTest_Boolen == 1: return ConfigurationTest_Boolen == 1 # If increment of Num is out of range for User_Pass_Num and Device_Type_Num return 1 elif User_Pass_Num >= len(Username_Device): print(f"Username Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Device_Type_Num >= len(Device_Type): print(f"Connection type Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 elif Passowrd_Enable_Num >= len(Passowrd_Device_Enable): print(f"Enable Pass Not in Range For IP\t{ip}\n") return ConfigurationTest_Boolen == 1 # If increment of Num is in range for User_Pass_Num and Device_Type_Num contune else: iosv_l2 = { 'device_type': str(Device_Type[Device_Type_Num] ), ##### Type of connection SSH/Telnet 'ip': str(ip), 'username': Username_Device[User_Pass_Num], 'password': Passowrd_Device[User_Pass_Num], 'global_delay_factor': 15, # if there is authentication problem allow this # 'secret':'cs' 'secret': Passowrd_Device_Enable[Passowrd_Enable_Num], # 'timeout':10 'session_timeout': 10 # if there is authentication problem allow this } try: # time.sleep(3) Conf_Variables = [ ] # To check if any faliure on the configuration after sending it net_connect = ConnectHandler(**iosv_l2) # print(net_connect.find_prompt()) ############ function to check output to send any confirmation message as pass or confirmation of yes or no def SpecialConfirmation(command, message, reply): net_connect.config_mode() #To enter config mode print("SpecialConfirmation Config") try: if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First Write Telnet") net_connect.remote_conn.write(str(command) + '\n') else: net_connect.remote_conn.sendall(str(command) + '\n') except: print("Exception For Sendall ") print("SpecialConfirmation Before Sleep") time.sleep(3) print("SpecialConfirmation after Sleep") if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("First READ Telnet") output = net_connect.remote_conn.read_very_eager().decode( "utf-8", "ignore") else: output = net_connect.remote_conn.recv(65535).decode( 'utf-8') ReplyAppend = '' print("SpecialConfirmation output") print(output) try: if str(message) in output: for i in range(0, (len(reply))): ReplyAppend += str(reply[i]) + '\n' if Device_Type[Device_Type_Num] == "cisco_ios_telnet": print("SECOND Telnet") net_connect.remote_conn.write(ReplyAppend) output = net_connect.remote_conn.read_very_eager( ).decode("utf-8", "ignore") else: net_connect.remote_conn.sendall(ReplyAppend) output = net_connect.remote_conn.recv( 65535).decode('utf-8') print(output) except: print("Confirmation Exception Error") return output print("Entered Device Successfully \t" + ip + "\n") ###################################################################### ################ Here Is The Cisco Configuration #################### ###################################################################### print("check enable mode for " + str(ip)) if not net_connect.check_enable_mode(): net_connect.enable() print("entered enable mode for " + str(ip)) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After exiting config to perform show commands " + str(ip)) print("After checking config to perform show commands " + str(ip)) ###################################################################### print("Terminal length \n") ## Try this First Configuration_Output = "" Configuration_Output = net_connect.send_command_timing( "termin len 0" + '\n\n') # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n' ,strip_prompt=False,strip_command=False) ################### for ARP ############################################################### ###################################################################### # Configuration_Output_ID2=net_connect.send_command_timing("show ip arp vrf ID2 "+'\n\n' ,strip_prompt=False,strip_command=False) # Configuration_Output_ID254=net_connect.send_command_timing("show ip arp vrf ID254 "+'\n\n' ,strip_prompt=False,strip_command=False) ###################################################################### # Configuration_Output=net_connect.send_command_timing("termin len 0"+'\n\n',delay_factor=5) # Configuration_Output=net_connect.send_command_timing("show run "+'\n\n' ,delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch=net_connect.send_command_timing("show fex "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors detail "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Switch+=net_connect.send_command_timing("show interfaces status "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show inter desc "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Router=net_connect.send_command_timing("show ip ospf neighbor "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show version "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) # Configuration_Output+=net_connect.send_command_timing("show cdp neighbors "+'\n\n',delay_factor=5,strip_prompt=False,strip_command=False) ########################################################################################################### ############################ Use TEXTFSM Template to get Show version ############################ ########################################################################################################### try: # Show_Version_TEXTFSM_List=net_connect.send_command_timing("show version "+'\n\n' ,strip_prompt=False,strip_command=False, use_textfsm=True, textfsm_template="/home/khayat/Textfsm_Templates/cisco_ios_show_version.textfsm") # Test_Expect=net_connect.send_command("show ip inte br "+'\n\n' ,strip_prompt=False,strip_command=False) # print ("\t\tTest_Expect") # print (Test_Expect) Show_Version_TEXTFSM_List = net_connect.send_command_timing( "show version " + '\n\n', strip_prompt=False, strip_command=False, use_textfsm=True) Show_Version_TEXTFSM_Dict = Show_Version_TEXTFSM_List[ 0] # this is because the output is in list then in Dict # print (type(Show_Version_TEXTFSM_List)) # print ((Show_Version_TEXTFSM_List)) # print (type(Show_Version_TEXTFSM_Dict)) # print ((Show_Version_TEXTFSM_Dict)) # print ("\n\n\n") # print ("\t\tConfiguration_Output_TEXTFSM") # for k,v in Show_Version_TEXTFSM_Dict.items() : # print (f"{k} :: {v}") if Show_Version_TEXTFSM_Dict["hardware"]: Hardware_IP = "\t\t" + str( Show_Version_TEXTFSM_Dict["hardware"] [0]) + f" {ip}___" + str( Show_Version_TEXTFSM_Dict["hostname"]) All_Hardware_Module_List.append(Hardware_IP) else: Hardware_IP_Empty_List.append(ip + " Hardware Empty") Hostname_Output = ip + ".__" + str( Show_Version_TEXTFSM_Dict["hostname"]) Worked_IPs_Old.append(ip) except Exception as e: print('Exception in show version\t' + ip) FailedIps.append(ip + " Exception in show version") IPs_ForIteration.append(ip) ########################################################################################################### # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n') # Configuration_Output+=net_connect.send_command_timing("show ip inte br "+'\n\n',strip_prompt=False,strip_command=False) print(f"This is after getting SHOW for IP\t{ip}") # Hostname_Output=net_connect.send_command("show run | i hostname"+'\n\n',delay_factor=5) ########################################################################################################### ################## Get each interfaces status using Script ################################################## ########################################################################################################### # List_Of_Inter=net_connect.send_command_timing("show interface status "+'\n\n') # # print ("\t\tList_Of_Inter") # List_of_Lines= Get_All_Inter(List_Of_Inter) # print ("\t\tList_of_Lines\n") # print (List_of_Lines) # print ("\t\tGet_Ports_Status") # Returned_List=Get_Ports_Status(List_of_Lines) # for i in Returned_List : # print (f"key\t{i}\tValue\t{Returned_List.get(i)} ") # ########################################################################################################### # ################## Get each interfaces IP using Script ################################################## # ########################################################################################################### # IPs_All_Interfaces=net_connect.send_command_timing("show ip interface br "+'\n\n') # Inter_IPs= Get_Interfaces_IP(IPs_All_Interfaces) # for x in Inter_IPs : # if x[-1] =="up" and x[-2]=="up" : # print (x) # print (x[1]) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if not net_connect.check_config_mode(): net_connect.config_mode() print("After entering config " + str(ip)) print("After checking config to perform configuration commands " + str(ip)) ###################################################################### ################ Set list of configuration ########################### ###################################################################### # List_cmd=[f"inte {Returned_List["disabled"][0]}","no shutd","ip add 192.168.100.100 255.255.255.0"] # print ("Returned_List[disabled][0]") # print (Returned_List.get("disabled")[0]) # Temp=str(Returned_List.get("disabled")[0]) # List_cmd=[f"inte {Temp}","no shutd"] # Output_Setting_Inter=net_connect.send_config_set(config_commands=List_cmd) # print ("Output_Setting_Inter") # print (Output_Setting_Inter) ################################################################## ########### Check if in config mode or not to exit config mode ################################################################## if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After exiting config " + str(ip)) print("After checking config for CDP command\t" + str(ip)) ########################################################################################################### ################## Add new IPs from CDP Command ################################################## ########################################################################################################### ############################################################################### ######################## Using Script for cdp neighbors to get New IPs ############################################################################### # CDP_ALL=net_connect.send_command_timing("show cdp neighbors detail | i IP address: "+'\n\n') # print ("\t\tGet_CDP_Neighbors") # num_New = list(num_New) + list(Get_CDP_Neighbors (CDP_ALL , num)) ############################################################################### ######################## Using TextFSM for cdp neighbors ############################################################################### try: Show_CDP_Details_TEXTFSM_List = net_connect.send_command_timing( "show cdp neighbors detail " + '\n\n', strip_prompt=False, strip_command=False, use_textfsm=True) for n in Show_CDP_Details_TEXTFSM_List: Show_CDP_Details_TEXTFSM_Dict = n # this is because the output is in list then in Dict # print (type(Show_CDP_Details_TEXTFSM_List)) # print (Show_CDP_Details_TEXTFSM_List) # print (type(Show_CDP_Details_TEXTFSM_Dict)) # print (Show_CDP_Details_TEXTFSM_Dict) # print (type(Show_CDP_Details_TEXTFSM_Dict["management_ip"])) # print (Show_CDP_Details_TEXTFSM_Dict["management_ip"]) if "172." in Show_CDP_Details_TEXTFSM_Dict[ "management_ip"]: if Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in num and Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in num_New and Show_CDP_Details_TEXTFSM_Dict[ "management_ip"] not in Worked_IPs_Old: num_New.append( Show_CDP_Details_TEXTFSM_Dict["management_ip"]) except Exception as e: print('Exception in show cdp neighbors \t' + ip) FailedIps.append(ip + " Exception in show cdp neighbors ") IPs_ForIteration.append(ip) ########################################################################################################### ################ Example on confirmation message Function ########################################################################################################### # if ip =="192.168.233.13": # print (str (SpecialConfirmation("crypto key generate rsa general-keys" ,"modulus" ,"1024"))) ########################################################################################################### ########################################################################################################### if net_connect.check_config_mode(): net_connect.exit_config_mode() print("After last check config " + str(ip)) ################################################################################ ####################### Test Ping For Rang Of IP ############################## ################################################################################ # Active_ping_ip=[] # InActive_ping_ip=[] # Sub_Ip_ping="2.0.32." # for x in range(1,255) : # print (x) # Ip_ping=Sub_Ip_ping+str(x) # ping_result=net_connect.send_command_timing("ping "+Ip_ping+'\n\n' ,strip_prompt=False,strip_command=False) # # print (ping_result) # # ping_is_successful(ping_result) # # print (ping_is_successful(ping_result)) # # print (type(ping_is_successful(ping_result))) # if ping_is_successful(ping_result) : # Active_ping_ip.append(Ip_ping) # else : # InActive_ping_ip.append(Ip_ping) # print ("Active_ping_ip") # for x in Active_ping_ip : # print (x) # print ("\n\n\nInActive_ping_ip") # for x in InActive_ping_ip : # print (x) ############### Append Configuration Variables to Global Variable ########## # Conf_Variables.append(Hostname_Output) # print (Configuration_Output) # Conf_Variables.append(Configuration_Output) ############### Search in Configuration if any command error and return its IP ################ for y in Conf_Variables: if "% Invalid input detected at '^' marker." in y: FailedIps.append(ip + " Invalid input") ######################################################################################################### Hostname_Output_list.append(Hostname_Output) test = Configuration_Switch test += Configuration_Output test += Configuration_Router Configuration_Output_list.append(test) Configuration_Output_ID2_list.append(Configuration_Output_ID2) Configuration_Output_ID254_list.append(Configuration_Output_ID254) ############### SAVE Output IN FILES ####################### Global_Output.append(Hostname_Output) print("Exiting " + str(ip)) net_connect.disconnect() print("After Exiting " + str(ip)) ################### Exception ################################### except (NetMikoAuthenticationException ) as netmikoAuthenticationException: # print ('Authentication Failure\t' + ip) print( str(User_Pass_Num) + " " + str(Username_Device[User_Pass_Num]) + " failed Authentication\t" + ip) ################ Print error from msg from the main Lib print( f"netmikoAuthenticationException : {netmikoAuthenticationException}\n" ) User_Pass_Num += 1 # If it tried all users and pass and failed add it to failedIps if User_Pass_Num >= len(Username_Device): FailedIps.append(ip + " Authentication Error ") IPs_ForIteration.append(ip) # if User_Pass_Num < len(Username_Device) : # print("this is Authentication "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) # Recursive function return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (ValueError): print(str(Passowrd_Enable_Num) + "\tEnable Authentication\t" + ip) Passowrd_Enable_Num += 1 if Passowrd_Enable_Num >= len(Passowrd_Device_Enable): FailedIps.append(ip + " Enable Authentication Error ") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except socket_error as socket_err: ################ Print error from msg from the main Lib print( f"Socket Error: \n{socket_err}\t for IP {ip} trying another type of Connection\n" ) print("Continue") if '111' in f"Type {socket_err}": Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Socket or connection type Error") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) if '113' in f"Type {socket_err}": FailedIps.append(ip + " No route to the host") IPs_ForIteration.append(ip) return ConfigurationTest_Boolen == 1 FailedIps.append(ip + " Socket or connection type Error") IPs_ForIteration.append(ip) return ConfigurationTest_Boolen == 1 except (NetMikoTimeoutException) as netmikoTimeoutException: # print ('Timeout Failure\t' + ip) print(str(Device_Type_Num) + "\tTimeoutException\t" + ip) ################ Print error from msg from the main Lib print(f"netmikoTimeoutException : \n{netmikoTimeoutException}\n") Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " Timeout Error") IPs_ForIteration.append(ip) # if Device_Type_Num < len(Device_Type) : # print("this is Timeout "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) # except (paramiko.ssh_exception.SSHException) as sshException : except (SSHException) as sshException: # print ('SSH Failure\t' + ip) print(str(Device_Type_Num) + "\tSSHException\t" + ip + "\n") ################ Print error from msg from the main Lib print( f"Unable to establish SSH connection: \n{sshException}\t for IP {ip}\n" ) Device_Type_Num += 1 if Device_Type_Num >= len(Device_Type): FailedIps.append(ip + " SSHException Error ") IPs_ForIteration.append(ip) # if Device_Type_Num < len(Device_Type) : # print("this is SSHException "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (ValueError): print( str(Passowrd_Enable_Num) + " " + str(Passowrd_Device_Enable[Passowrd_Enable_Num]) + " Failed Enable Authentication\t" + ip) Passowrd_Enable_Num += 1 if Passowrd_Enable_Num >= len(Passowrd_Device_Enable): FailedIps.append(ip + " Enable Authentication Error ") IPs_ForIteration.append(ip) return ConfigurationTest(ip, Device_Type_Num, User_Pass_Num, Passowrd_Enable_Num) except (EOFError) as eof_Error: ################ Print error from msg from the main Lib print(f"eof_Error : \n{eof_Error}\n") # print ('End of File wihle attempting device\t' +ip) FailedIps.append(ip + " EOFError") IPs_ForIteration.append(ip) # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) return ConfigurationTest_Boolen == 1 ################################################################### ######### if you want to show error , comment next lines if you want to show which Ips have error remove comment ############## ################################################################### # except Exception as e: # # print ('End of File wihle attempting device\t' +ip) # FailedIps.append(ip+" Exception as e") # # print("this is EOFError "+str(ip)+" Device_Type "+str(Device_Type[Device_Type_Num])+" Username_Device " +str(Username_Device[User_Pass_Num])+" Passowrd_Device " +str(Passowrd_Device[User_Pass_Num])) # return ConfigurationTest_Boolen==1 #################################################################### return ConfigurationTest_Boolen == 1
from getpass import getpass from datetime import datetime import time password = getpass(prompt="Bitte Passwort eingeben : ") cisco_ios4 = {"host": "cisco4.lasthop.io", "username": "******", "password": password, "device_type": "cisco_ios", "session_log": "my_session.txt", "secret": password} ios_connect = ConnectHandler(**cisco_ios4) print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.config_mode() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.exit_config_mode() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.write_channel("disable\n") print("Current prompt :" + str(ios_connect.find_prompt())) time.sleep(2) output = ios_connect.read_channel() print(output) ios_connect.enable() print("Current prompt :" + str(ios_connect.find_prompt())) ios_connect.disconnect()
def backups(username, password, secret, customer, tftp_ip): with open(customer, mode='r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: hostname = row['SysName'] device_type = row['device_type'] ip = row['IP_Address'] switch = { 'device_type': device_type, 'ip': ip, 'username': username, 'password': password, 'secret': secret, 'verbose': False, } net_connect = ConnectHandler(**switch) # Insert enables et al here net_connect.enable() # Temporary variable, need raw input later change_number = "1" # Then command strings net_connect.send_command( 'send log "Starting change ticket {}"'.format(change_number)) iphost = net_connect.send_command("sh run | inc ip host tftp") archive = net_connect.send_command("sh run | inc archive") kronpolicy = net_connect.send_command( "sh run | inc kron policy-list BACKUP-CONFIG") kronoccur = net_connect.send_command( "sh run | inc kron occurrence DAILY-CONFIG-BACKUP") print "\n\n>>>>>>>>> Device {0} <<<<<<<<<\n".format(row['SysName']) if iphost == "": net_connect.config_mode() ipcommand = "ip host tftp " + str(tftp_ip) net_connect.send_command_expect(ipcommand) print "Configured TFTP IP to " + str(tftp_ip) else: print "TFTP IP is already configured to " + str(iphost) if archive == "": config_archive = [ 'archive', 'path tftp://tftp/$h/$h', 'write-memory', 'exit' ] net_connect.send_config_set(config_archive) print "Archive now configured." else: print "Archive already configured." if kronpolicy == "": config_kronp = [ 'kron policy-list BACKUP-CONFIG', 'cli write memory', 'exit' ] net_connect.send_config_set(config_kronp) print "Kron Policy BACKUP-CONFIG now configured." else: print "Kron Policy BACKUP-CONFIG already configured." if kronoccur == "": config_krono = [ 'kron occurrence DAILY-CONFIG-BACKUP at 0:05 recurring', 'policy-list BACKUP-CONFIG', 'exit' ] net_connect.send_config_set(config_krono) print "Kron Occurrence DAILY-CONFIG-BACKUP now configured." else: print "Kron Occurrence DAILY-CONFIG-BACKUP already configured." net_connect.send_command_expect('write memory') print "Memory Saved." net_connect.send_command( 'send log "Completing change ticket {}"'.format(change_number)) print "\n>>>>>>>>> End <<<<<<<<<" # Disconnect from this session net_connect.disconnect()
from netmiko import ConnectHandler from getpass import getpass password = getpass() NB_3850_8 = { 'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': '******', 'password': password, 'port': 8022, } nick_3850 = ConnectHandler(**NB_3850_8) nick_3850.find_prompt() nick_3850.exit_config_mode() nick_3850.config_mode() output = nick_3850.check_config_mode() print 'In configuration mode:', output
def run_module(): ''' define the available arguments/parameters that a user can pass to the module ''' module_args = dict(hostname=dict(required=True, type='str'), username=dict(fallback=(env_fallback, ['AD_USERNAME'])), password=dict(fallback=(env_fallback, ['AD_PASSWORD']), no_log=True), timeout=dict(required=False, type='int', default=30), lines=dict(required=True, type='list'), confirm=dict(required=False, type='int', default=2)) ''' ''' result = dict(changed=False, message="") module = AnsibleModule(argument_spec=module_args, supports_check_mode=False) hostname = str(module.params['hostname']) username = str(module.params['username']) password = str(module.params['password']) timeout = int(module.params['timeout']) lines = list(module.params['lines']) confirm = int(module.params['confirm']) device_dict = { 'device_type': 'juniper_junos', 'ip': hostname, 'username': username, 'password': password, 'global_delay_factor': 4 } #Connect to the device try: Net_Connect = ConnectHandler(**device_dict) except: module.fail_json(msg="Could not connect to: {}".format(hostname)) #Enter configuration mode try: output = Net_Connect.config_mode() except: module.fail_json( msg="Could not enter configuration mode on {}".format(hostname)) #Send commands to device try: for line in lines: output = Net_Connect.send_command(line, auto_find_prompt=False) except: module.fail_json(msg="Could not sent commands to: {}".format(hostname)) #Check if there were any changes into the device #try: # output = Net_Connect.send_command('show configuration | compare',expect_string='') # if output!='\n': # result['changed']=True # result['msg']=str(output) #except: # module.fail_json(msg="Could not check changes on : {}".format(hostname)) #Send commit confirmed try: output = Net_Connect.send_command( 'commit confirmed {}'.format(confirm), expect_string='', auto_find_prompt=False) except: module.fail_json( msg="Could commit confirmed the configuration to: {}, {}".format( hostname, output)) #Exit config mode #try: # output=Net_Connect.send_command('exit',expect_string='') #except: # module.fail_json(msg="Could not exit the configure mode in : {}".format(hostname)) #Closing the connection #Net_Connect.disconnect() #time.sleep(30) #Confirm the commit to the device try: # Net_Connect=ConnectHandler(**device_dict) # output = Net_Connect.config_mode() output = Net_Connect.send_command('commit', auto_find_prompt=False) result['changed'] = True result['message'] = str(output) output = Net_Connect.send_command('exit', expect_string='', auto_find_prompt=False) Net_Connect.disconnect() except: module.fail_json( msg= "Could not confirm the commit to: {}, rollback will be performed in less than: {}" .format(hostname, confirm)) # in the event of a successful module execution, you will want to # simple AnsibleModule.exit_json(), passing the key/value results module.exit_json(**result)
from netmiko import ConnectHandler pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': '******', } pynet_rtr2 = ConnectHandler(**pynet2) pynet_rtr2.config_mode() pynet_rtr2.check_config_mode() pynet_rtr2.exit_config_mode() pynet_rtr2.disconnect()
'ip': ip, 'username': username, 'password': password } connection = ConnectHandler(**cisco_switch) interface_output = connection.send_command('show ip interface brief') #print(interface_output) for line in interface_output: if 'up' in line: print(line) print('--------adding AAA commands to the device ------') commands = [ 'aaa authentication login default group radius local-case', 'aaa authentication login vty group radius local-case', 'aaa authorization exec default group radius local if-authenticated', 'aaa accounting system default start-stop group radius', 'ip radius source-interface Vlan1301', 'radius-server host 192.168.1.10 auth-port 1645 acct-port 1646', 'radius-server key cisco', 'line vty 0 4', 'login authentication vty' ] configoutput = connection.config_mode() if 'Invalid input' in configoutput: print(configoutput) configoutput = connection.send_config_set(commands) if 'Invalid input' in configoutput: print(configoutput) print('------------------done------------------')
from netmiko import ConnectHandler with open('commands_file.txt') as f: commands_list = f.read().splitlines() with open('devices_file.txt') as f: devices_list = f.read().splitlines() for devices in devices_list: print 'Connecting to device" ' + devices ip_address_of_device = devices eos_device = { 'device_type': 'arista_eos', 'ip': ip_address_of_device, 'username': '******', 'password': '******' } print "HELLO" net_connect = ConnectHandler(**eos_device) enable = net_connect.enable() conft = net_connect.config_mode() output = net_connect.send_config_set(commands_list) print output
class EdgeosDriver(NetworkDriver): """Napalm driver for skeleton.""" def __init__(self, hostname, username, password, timeout=60, optional_args=None): """NAPALM Edgeos Handler.""" if optional_args is None: optional_args = {} self.hostname = hostname self.username = username self.password = password self.timeout = timeout self.port = optional_args.get('port', 22) self.candidate_cfg = optional_args.get('candidate_cfg', '/config/candidate') self.device = None self.config_replace = False def open(self): """Open a connection to the device.""" self.device = ConnectHandler( device_type='vyos', host=self.hostname, username=self.username, password=self.password, timeout=self.timeout, port=self.port ) def close(self): """Close the connection to the device.""" self.device.disconnect() def load_replace_candidate(self, filename=None, config=None): self.config_replace = True error_marker = 'Failed to parse specified config file' if config: raise NotImplementedError if not filename: raise ReplaceConfigException("filename empty") self.scp_file(source_file=filename, dest_file=self.candidate_cfg) self.device.config_mode() cmd = 'load {}'.format(self.candidate_cfg) output = self.device.send_command(cmd, expect_string='#') if error_marker in output: self.discard_config() raise ReplaceConfigException(output) def load_merge_candidate(self, filename=None, config=None): raise NotImplementedError def commit_config(self, save=True): self.config_replace = False error_marker = 'Failed to generate committed config' output = self.device.send_command('commit', expect_string='#', delay_factor=.1) if error_marker in output: self.discard_config() raise ReplaceConfigException(output) if save: self.device.send_command('save', expect_string='#') self.device.send_command('exit', expect_string='$') def discard_config(self): self.config_replace = False self.device.send_command('exit discard', expect_string='$') def compare_config(self): if not self.config_replace: raise CommandErrorException("compare_config called to early") diff = self.device.send_command('compare', expect_string="#").strip() diff = '\n'.join(diff.splitlines()[:-1]) if diff == 'No changes between working and active configurations': return '' return diff def scp_file(self, source_file, dest_file): try: scp_transfer = SCPConn(self.device) scp_transfer.scp_put_file(source_file, dest_file) except: raise ConnectionException("SCP transfer to remote device failed")
'username': '******', 'password': '******', 'port': 22, } pynet2 = { 'device_type': 'cisco_ios', 'ip': '184.105.247.71', 'username': '******', 'password': '******', 'port': 22, } srx = { 'device_type': 'juniper', 'ip': '184.105.247.76', 'username': '******', 'password': '******', 'secret': '', 'port': 22, } print 'Connect to pynet1' pynet_rtr1 = ConnectHandler(**pynet1) print 'enter config mode' pynet_rtr1.config_mode() print 'am i in config mode?' print pynet_rtr1.check_config_mode()
#!/usr/bin/env python '''Script uses Netmiko to connect to router and enter config mode''' #### import statements from netmiko import ConnectHandler from device_list import ROUTER_LIST #### functions # main function (this is the main execution code for your program) def main(): '''Main function, opens connection, enters config mode, changes logging and verifies''' for a_device in ROUTER_LIST: a_connection = ConnectHandler(**a_device) a_connection.config_mode() if a_connection.check_config_mode(): a_connection.send_config_from_file(config_file='some_commands.txt') a_connection.exit_config_mode() output = a_connection.send_command("show run | include logging") print output else: print "We are NOT in Config mode" if __name__ == "__main__": # program execution starts here main() # first action is to call main function
# ------------------------------------ # net_connect.find_prompt() # ------------------------------------ # # ------ show command ---------------- # # ------------------------------------ # output = device.send_command('show version') print output; # -------------------------------------------- # # ------ send config command - one by one ---- # # -------------------------------------------- # device.config_mode() device.send_command('interface fast1/0') device.send_command('ip addr 10.10.10.10 255.255.255.0') device.exit_config_mode() # --------------------------------------------- # # ------ send config command - multiple ------- # # --------------------------------------------- # commands = ['interface fa1/0', 'no shut'] device.send_config_set(commands) # --------------------------------------------- # # ------ send command to multiple devices ----- # # --------------------------------------------- #