def fex_config(self, params): try: cmd = "config terminal" + ' ' + ";" + ' ' + 'interface' + ' ' + params.interface_type + params.interface_number + ' ' + ";" + ' ' + "switchport" + ' ' + ";" "switchport mode fex-fabric" + ' ' + ";" + ' ' + "fex associate" + ' ' + params.fex_number + ' ' + ";" + ' ' cli(cmd)
def test_request(arg=None): try: cli("guestshell run pwd") return arg except: time.sleep(11) return arg
def get_ip2mac_map(ips_to_check=[]): for each_ip in ips_to_check: cli("ping " + each_ip) ip_adj_counter_list = ["ip-addr-out", "mac"] mac_add_dyn_counter_list = ["disp_port", "disp_mac_addr"] sh_ip_adj_output=json.loads(clid("show ip adj")) sh_mac_add_dyn_output=json.loads(clid("show mac address-table dynamic")) ip_port_table = "{ \"IP Port Map\": [" first_line = True for each_ip in ips_to_check: for each_ip_mac in sh_ip_adj_output["TABLE_vrf"]["ROW_vrf"]["TABLE_afi"]["ROW_afi"]["TABLE_adj"]["ROW_adj"]: if each_ip == each_ip_mac["ip-addr-out"]: for each_mac_line in sh_mac_add_dyn_output["TABLE_mac_address"]["ROW_mac_address"]: if each_mac_line["disp_mac_addr"] == each_ip_mac["mac"]: port_name = each_mac_line["disp_port"].replace("ernet","") if first_line <> True: ip_port_table = ip_port_table + ",{\"Port\":\"" + port_name + "\"" else: ip_port_table = ip_port_table + "{\"Port\":\"" + port_name + "\"" first_line = False ip_port_table = ip_port_table + ",\"IP\":\"" + each_ip_mac["ip-addr-out"] + "\"}" ip_port_table = ip_port_table + "]}" return json.loads(ip_port_table)
def check_version(): desired_9k_ver = 'nxos.7.1.3.1.bin' desired_6k_ver = 'nxos.7.0.3.I3.1.bin' current_ver_data = show_dev_version() current_ver_raw = current_ver_data['Bootfile'] current_ver = current_ver_raw.strip('bootflash:///') current_model_raw = current_ver_data['Model'] current_model = current_model_raw.split(' ')[0] # current_model = 'Nexus6000' if desired_6k_ver == current_ver and current_model == 'Nexus6000': print 'Current 6K version is acceptable, moving to next step.' upgrade_check = False elif desired_6k_ver != current_ver and current_model =='Nexus6000': print 'Current 6K version requires upgrading, beginning version upgrade process.' upgrade_check = True elif desired_9k_ver == current_ver and current_model == 'Nexus9000': print 'Current 9K version is acceptable, moving to next step.' upgrade_check = False elif desired_9k_ver != current_ver and current_model == 'Nexus9000': print 'Current 9K version requires upgrading, beginning version upgrade process.' upgrade_check = True if upgrade_check == True: try: cli('copy bootflash:/testcode/imagetest.bin bootflash:imagetest.bin') print 'Copying System Image...' except: print 'Oh Poop! Something went wrong, probably Brents fault' exit(0)
def save_state(fname, change_id): commands = [ 'dir', 'show version', 'show license usage', 'show module', 'show inventory', 'show environment', 'show processes cpu history', 'show system resources', 'show system uptime', 'show feature', 'show cfs peers', 'show cfs application', 'show cfs status', 'show cfs lock', 'show copp status', 'show ip route', 'show ip arp', 'show mac address-table dynamic', 'show ip interface brief', 'show interface', 'show interface status', 'show cdp neighbors', 'show spanning-tree', 'show spanning-tree root', ] print color_blue + "Saving the following output to bootflash:{0}/{1}".format(change_id, fname) for command in commands: print color_normal + command cli(command + ' >> bootflash:{0}/{1}'.format(change_id, fname))
def check_version(): desired_9k_ver = 'nxos.7.1.3.1.bin' desired_6k_ver = 'nxos.7.0.3.I3.1.bin' current_ver_data = show_dev_version() current_ver_raw = current_ver_data['Bootfile'] current_ver = current_ver_raw.strip('bootflash:///') current_model_raw = current_ver_data['Model'] current_model = current_model_raw.split(' ')[0] # current_model = 'Nexus6000' if desired_6k_ver == current_ver and current_model == 'Nexus6000': print 'Current 6K version is acceptable, moving to next step.' upgrade_check = False elif desired_6k_ver != current_ver and current_model == 'Nexus6000': print 'Current 6K version requires upgrading, beginning version upgrade process.' upgrade_check = True elif desired_9k_ver == current_ver and current_model == 'Nexus9000': print 'Current 9K version is acceptable, moving to next step.' upgrade_check = False elif desired_9k_ver != current_ver and current_model == 'Nexus9000': print 'Current 9K version requires upgrading, beginning version upgrade process.' upgrade_check = True if upgrade_check == True: try: cli('copy bootflash:/testcode/imagetest.bin bootflash:imagetest.bin' ) print 'Copying System Image...' except: print 'Oh Poop! Something went wrong, probably Brents fault' exit(0)
def main(argv): if (len(argv)) != 2: print("Not enough arguments") return if argv[0]: process = argv[0] if argv[1]: mem_lim = argv[1] ptp_mem = cisco.nxcli.nxcli(str='sh proc mem | i '+process) for m in ptp_mem: if process in str(m): print(process) mem_line = m msplit = mem_line.split() mem = int(msplit[3]) print(mem) pid = get_pid(process) pid = pid.replace("'",'') print(pid) if mem != 0: if int(mem) > int(mem_lim): print("KILLING PROCESS") #cisco.nxcli.nxcli(str='syslog priority notifications msg for '+process+' mem: '+mem +' and cpu ' + cpu, do_print=False) cisco.nxcli.nxcli(str='syslog priority notifications msg Killing '+str(process)+' mem: '+str(mem), do_print=False) cli('run bash sudo kill -6 '+pid) return return
def do_it(): global hostname url = "http://" + hostname + ":" + port + "/api/ignite/" poap_log("Started the execution at do_it function") #poap_log(cli("show module")) #poap_log(cli("show interface status")) interface_list = json.loads(clid("show interface status")) no_shut_intf = "conf t " poap_log(str(no_shut_intf)) for interface in interface_list['TABLE_interface']['ROW_interface']: no_shut_intf = no_shut_intf + " ; interface " + interface[ 'interface'] + " ; no shut" poap_log(str(no_shut_intf)) cli(no_shut_intf) poap_log(str(cli("show interface ethernet 1/1-32 status"))) poap_log(str(cli("show interface mgmt0 status"))) poap_log("Unshut all the interfaces") #sleep fro CDP refresh time + 1 second time.sleep( int( cli("show cdp global | grep Refresh | awk '{print $4}'").strip( '\n')) + 1) cdp_json = parse_cdp_nei_ignite() response = urllib2.Request(url, cdp_json, {'Content-Type': 'application/json'}) f = urllib2.urlopen(response) resp_json = f.read() resp_data = json.loads(resp_json) poap_log(str(resp_data)) global host global username global password host = str(resp_data['imageserver']) username = str(resp_data['image_username']) password = str(resp_data['image_password']) global system_image_src global system_image_dst_tmp global new_image_name new_image_name = resp_data['imagename'] system_image_dst_tmp = "%s%s/%s" % (image_dir_dst, ".new", new_image_name) system_image_src = "%s/%s" % (image_dir_src, new_image_name) get_system_image() host = hostname username = str(resp_data['config_username']) password = str(resp_data['config_password']) global config_file_src config_file_src = str(resp_data['config_file_loc']) + str( resp_data['config_filename']) get_config()
def disable(self): """Disables the guestshell""" disable_cmd = 'guestshell disable' try: cli(disable_cmd) return True except: logger.error("Something went wrong while disabling guestshell")
def change_ndb_perm(self, guest_path): """Proc to change the directory permission through guestshell""" perm_cmd = 'guestshell run chmod -Rf 777 ' + guest_path try: cli(perm_cmd) return True except: return False
def reboot(self): """Rebooting the guestshell""" reboot_cmd = 'guestshell reboot' try: cli(reboot_cmd) return True except: logger.error("Something went wrong while rebooting guestshell")
def start_ndb(self, path): """Starting the NDB""" start_cmd = 'guestshell run ' + path + '/embedded/i5/make-systemctl-env.sh' try: cli(start_cmd) return True except: return False
def gs_copy_ndb(self, from_path, to_path): """Proc to copy file from one location to another""" copy_cmd = 'guestshell run cp -Rf ' + from_path + " " + to_path + "/" try: cli(copy_cmd) return True except: return False
def set_cpu(self, cpu_value): """Set the cpu value for guestshell""" cpu_cmd = 'guestshell resize cpu ' + str(cpu_value) try: cli(cpu_cmd) return True except: logger.error("Something went wrong while configuring cpu for guestshell+") return False
def set_nxapi_vrf(self): """Configures vrf to be used for nxapi communication""" vrf_cmd = 'configure terminal ; nxapi use-vrf management ; copy running-config startup-config' try: cli(vrf_cmd) return True except: logger.error("Something went wrong while keeping nxapi to listen to network namespace") return False
def enable_nxapi_feature(self): """Enables feature nxapi""" nxapi_cmd = 'configure terminal ; feature nxapi' try: cli(nxapi_cmd) return True except: logger.error("Something went wrong while enabling feature NX-API") return False
def test_cli_help(monkeypatch, capsys, cli_parser): monkeypatch.setattr("sys.argv", ["py.test", "--help"]) with raises(SystemExit) as exc: cli() out, err = capsys.readouterr() cli_parser.print_help() out_help, err_help = capsys.readouterr() assert exc.value.code == 0 assert out == out_help
def set_disk(self, disk_value): """Set the cpu value for guestshell""" disk_cmd = 'guestshell resize rootfs ' + str(disk_value) try: cli(disk_cmd) return True except: logger.error("Something went wrong while configuring bootflash for guestshell+") return False
def set_memory(self, memory_value): """Set the cpu value for guestshell""" memory_cmd = 'guestshell resize memory ' + str(memory_value) try: cli(memory_cmd) return True except: logger.error("Something went wrong while configuring memory for guestshell+") return False
def do_it(): global hostname url = "http://" + hostname + ":" + port + "/api/ignite/" poap_log("Started the execution at do_it function") #poap_log(cli("show module")) #poap_log(cli("show interface status")) interface_list=json.loads(clid("show interface status")) no_shut_intf="conf t " poap_log(str(no_shut_intf)) for interface in interface_list['TABLE_interface']['ROW_interface']: no_shut_intf=no_shut_intf+" ; interface "+interface['interface']+" ; no shut" poap_log(str(no_shut_intf)) cli(no_shut_intf) poap_log(str(cli("show interface ethernet 1/1-32 status"))) poap_log(str(cli("show interface mgmt0 status"))) poap_log("Unshut all the interfaces") #sleep fro CDP refresh time + 1 second time.sleep(int(cli("show cdp global | grep Refresh | awk '{print $4}'").strip('\n'))+ 1) cdp_json = parse_cdp_nei_ignite() response = urllib2.Request(url,cdp_json,{'Content-Type':'application/json'}) f = urllib2.urlopen(response) resp_json = f.read() resp_data = json.loads(resp_json) poap_log(str(resp_data)) global host global username global password host = str(resp_data['imageserver']) username = str(resp_data['image_username']) password = str(resp_data['image_password']) global system_image_src global system_image_dst_tmp global new_image_name new_image_name = resp_data['imagename'] system_image_dst_tmp = "%s%s/%s" % (image_dir_dst, ".new", new_image_name ) system_image_src = "%s/%s" % (image_dir_src, new_image_name ) get_system_image() host = hostname username = str(resp_data['config_username']) password = str(resp_data['config_password']) global config_file_src config_file_src = str(resp_data['config_file_loc'])+str(resp_data['config_filename']) get_config()
def set_bootvar(): boot = cli('config t ; boot nxos bootflash:/imagetest.bin ; end') print 'Setting boot variable to NXOS Image.... ' print 'Saving configuration...' save = cli('copy run start') print 'Save complete.' return set_bootvar
def enable_bash_shell(self): """Enables feature nxapi""" bash_cmd = 'configure terminal ; feature bash-shell' try: cli(bash_cmd) return True except: logger.error( "Something went wrong while enabling feature bash-shell") return False
def enable(self, pkg_name=None): """Enables the guestshell""" enable_cmd = 'guestshell enable' if pkg_name: enable_cmd = 'guestshell enable package ' + pkg_name try: cli(enable_cmd) return True except: logger.error("Something went wrong while enabling guestshell") return False
def rm_rf(filename): filename_u = "/" + filename.replace(":", "/") if not os.path.exists(filename_u): syslog("rm_rf: file does not exist- %s" % filename) return True try: cli("delete %s" % filename) syslog("Deleted") return True except: syslog("Could not delete") return False
def getIPv6Neighbor(if_name): timeout = 10 command = "show ipv6 neighbor %s" % if_name for _ in range(timeout): cli("ping6 multicast ff02::1 source-interface %s count 1 timeout 1" % if_name) results = json_clid( command)["TABLE_vrf"]["ROW_vrf"]["TABLE_afi"]["ROW_afi"] if "TABLE_adj" in results: return results["TABLE_adj"]["ROW_adj"]["ipv6-addr"] return None
def updateinterface(self, data): #print data for key,value in data.iteritems(): if (key == 'intf_id'): cmd1 = "interface" + ' ' + value desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id'] msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id'] cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc cli(cmd) print "\n" print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
def rm_rf(filename): filename_u = "/" + filename.replace(":", "/") if not os.path.exists(filename_u): syslog("rm_rf: file does not exist- %s" %filename) return True try: cli("delete %s" % filename) syslog("Deleted") return True except: syslog("Could not delete") return False
def execute_command(self, new_info, old_info=None): if self.t_d == 'threshold': for i in new_info: if new_info[i] >= self.value: show = cli(self.command) #collect info self.__save_output(show) elif self.t_d == 'discrepancy': for i in new_info: new_value = new_info[i] old_value = old_info[i] if new_value - old_value >= self.value: show = cli(self.command) #collect info self.__save_output(show)
def fex_update(self, stat): if ((stat == 'disabled') or (stat == 'installed')) : cli('config terminal ; feature-set fex') FEX_Config.currentstat = "FEX is now enabled " print FEX_Config.currentstat if (stat == 'uninstalled') : cmd = "conf t" + ' ' + " ;" + ' ' + "install feature-set fex" + ' ' + ";" + ' ' + "feature-set fex" cli(cmd) FEX_Config.currentstat = "FEX is installed and enabled" print FEX_Config.currentstat
def add_description(mac_info): for mac_port in mac_info: # 인터페이스(mac_port) 수만큼 반복해서 동작 mac_list = mac_info.get(mac_port) # 인터페이스 MAC 주소 리스트 조회 mac_addr = "" if len(mac_list) > 1: # MAC 주소가 여러 개일 때 i = 0 print "*" * 30 print "Num", "MAC Address" print "=" * 30 while i < len(mac_list): # MAC 주소 리스트를 출력 print i, mac_list[i] i = i + 1 print "%s 의 MAC Address가 1개 이상입니다." % mac_port select = input("중복된 내용 중 상세 내용에 입력하고자 하는 MAC을 선택하세요 : ") mac_addr = mac_list[select] # 선택한 MAC 주소를 mac_addr 변수에 지정 else: mac_addr = mac_list[0] mac = mac_addr[0:7] # MAC 주소 중 앞의 7자리 추출 mac = mac.replace(".", "").upper() # MAC 주소 중 .(dot)을 제거 # 웹 페이지에서 데이터 추출하는 코드 try: conn = httplib.HTTPConnection("aruljohn.com") # 해당 웹 페이지에 접속 conn.request("GET", "/mac/%s" % mac) # /mac/<MAC 6자리>를 url에 추가 res = conn.getresponse() # 웹페이지의 HTML 소스를 받음 data = res.read() description = "*auto* " oui = "%s:%s:%s" % (mac[0:2], mac[2:4], mac[4:6] ) # OUI -> 00:00:00 형식의 MAC search_word = "<tr><td>%s</td><td>" % oui # OUI의 앞뒤 태그를 포함해서 찾기 index = data.find(search_word) + len( search_word) # OUI 뒤에 제조사 정보가 있음 if index >= 0: vender = data[index:data.find("</td>", index)].strip( ) # 앞뒤의 HTML 태그를 제거 # 제조사 정보를 찾으면 설명 항목에 입력할 데이터를 작성합니다. description = "*auto* %s - %s" % (vender, mac_addr) # configure terminal 모드에서 설명 항목에 수정하는 명령을 수행합니다. cmd = "configure terminal ; interface %s ; " % mac_port cmd = cmd + "description %s" % description cli(cmd) except IOError as e: print "%s(%s)의 정보는 조회할 수 없습니다." % (mac_port, mac_addr)
def updateinterface(self, data): for key,value in data.iteritems(): if (key == 'intf_id'): cmd1 = "interface" + ' ' + value desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id'] msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id'] cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc cli(cmd) print "\n" print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg if (data['capability']): print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : " for i in data['capability']: print str(i)
def updateinterface(self, data): #print data for key, value in data.iteritems(): if (key == 'intf_id'): cmd1 = "interface" + ' ' + value desc = "description" + ' ' + "Connected to device" + ' ' + data[ 'device_id'] + ' ' + "on" + ' ' + data['port_id'] msg = "Connected to device" + ' ' + data[ 'device_id'] + ' ' + "on" + ' ' + data['port_id'] cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc cli(cmd) print "\n" print "Interface" + ' ' + data[ 'intf_id'] + ' ' + "description is updated as : " + ' ' + msg
def create_config_commands(): config_commands = "conf t ; " output = json.loads(cli("show interface status | json")) for interface in output["TABLE_interface"]["ROW_interface"]: int_state = interface["state"] int_name = interface["interface"] if not args.notconnect and not args.sfp: if ((int_state in no_sfp_target_state) or (int_state in notconnect_target_state)): config_commands += int_command.format(interface["interface"], non_routed_vlan) interfaces.append(int_name) elif args.notconnect and int_state in notconnect_target_state: config_commands += int_command.format(interface["interface"], non_routed_vlan) interface.append(int_name) elif args.sfp and int_state in no_sfp_target_state: config_commands += int_command.format(interface["interface"], non_routed_vlan) interface.append(int_name) if config_commands.endswith("; "): config_commands = config_commands[:-2] if len(config_commands) > 0: return config_commands else: return None
def set_config_file_src_serial_number (): global config_file_src serial_num = cli('show inventory chassis | grep SN:').rstrip().split(" ")[-1] poap_log("INFO: Serial Number: %s" % serial_num) config_file_src = "%s.%s" % (config_file_src, serial_num) poap_log("INFO: Selected config filename (serial_number) : %s" % config_file_src)
def tcode(func, argstr, code): "assert func exits with code" try: tmp = cli(func) tmp(argstr.split()) except SystemExit as e: assert e.code == code
def main(): try: interface_type = sys.argv[1] except: interface_type = "cli" print("Connecting to server...") s = connect(SERVER_ADDRESS) if s == None: return print("Connected to server") #Everything from here out uses the server try: # print("Running gui") # g = gui(s) # g.mainloop() if interface_type == "gui": print("Staring gui") interface = gui(s) else: print("Starting cli") interface = cli(s) interface.run() except: s.close()
def show_vlan(params): cmd_str = cmd_vlan_show % (params.vlan) print cmd_str return_xml = cli(cmd_str) print return_xml return True
def copy_image_file(params): print 'copy tftp://'+ params.tftp_address + '/' + params.image_filename +\ ' bootflash:// vrf management' return_xml = cli('copy tftp://'+ params.tftp_address + '/' +\ params.image_filename + ' bootflash:// vrf management') print return_xml
def send_email(fname, user_id): print color_green + "Sending e-mail to {0}@navyfederal.org".format(user_id) + " this may take a moment..." email = cli("show file {0} | email subject {1}_show_ouput {2}@navyfederal.org".format(fname, fname, user_id)) if email == "Error in sending email\n": print color_red + "Email did not send. Please check if email if configured." print color_normal + """ If email settings are configured try resending via cli "show file {0} | email subject {1}_show_ouput {2}@navyfederal.org" """.format(fname, fname, user_id)
def verify_freespace (): freespace = int(cli("dir bootflash: | last 3 | grep free | sed 's/[^0-9]*//g'").strip('\n')) freespace = freespace / 1024 poap_log("INFO: free space is %s kB" % freespace ) if required_space > freespace: poap_log("ERR : Not enough space to copy the config, kickstart image and system image, aborting!") abort_cleanup_exit()
def show_interface(params): cmd_str = "" if params.int_type == "ethernet": cmd_str += cmd_show_interface % (params.int_type, "%s/%s" % (params.slot, params.port)) elif params.int_type == "port-channel": cmd_str += cmd_show_interface % (params.int_type, params.port_channel_id) print cmd_str return_xml = cli(cmd_str) print return_xml
def get_vs_info(self): """Collect the virtual service cpu/memory/disk size""" self.vs_data = None vs_memory_cmd = 'show virtual-service global | json' try: self.vs_data = cli(vs_memory_cmd) self.vs_data = json.loads(self.vs_data) except: logger.error("Something went wrong while fetching switch memory") return self.vs_data
def do_it(): global hostname url = "http://" + hostname + ":8888/api/poap/" poap_log("Started the execution at do_it function") #poap_log(cli("show module")) #poap_log(cli("show interface status")) interface_list=json.loads(clid("show interface status")) no_shut_intf="conf t " poap_log(str(no_shut_intf)) for interface in interface_list['TABLE_interface']['ROW_interface']: no_shut_intf=no_shut_intf+" ; interface "+interface['interface']+" ; no shut" poap_log(str(no_shut_intf)) cli(no_shut_intf) poap_log(str(cli("show interface ethernet 1/1-10 status"))) poap_log(str(cli("show interface mgmt0 status"))) poap_log("Unshut all the interfaces") cdp_json = parse_cdp_nei_ignite() response = urllib2.Request(url,cdp_json,{'Content-Type':'application/json'}) f = urllib2.urlopen(response) resp_json = f.read() resp_data = json.loads(resp_json) poap_log(str(resp_data)) imageserver = str(resp_data['imageserver']) host2 = hostname hostname = imageserver get_system_image() hostname = host2 global username global password username = str(resp_data['config_username']) password = str(resp_data['config_password']) global config_file_src config_file_src = str(resp_data['config_file_loc'])+str(resp_data['config_filename']) get_config()