コード例 #1
0
ファイル: fex_config.py プロジェクト: ychao1970/opennxos
    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)
コード例 #2
0
def test_request(arg=None):
    try:
        cli("guestshell run pwd")
        return arg
    except:
        time.sleep(11)
        return arg
コード例 #3
0
def test_request(arg=None):
    try:
        cli("guestshell run pwd")
        return arg
    except:
        time.sleep(11)
        return arg
コード例 #4
0
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)
コード例 #5
0
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)
コード例 #6
0
ファイル: change.py プロジェクト: ShaunGomez/NX-OS-Toolkit
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))
コード例 #7
0
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)
コード例 #8
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
コード例 #9
0
ファイル: ignite_poap.py プロジェクト: salvoventura/ignite
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()
コード例 #10
0
 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")
コード例 #11
0
 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
コード例 #12
0
 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")
コード例 #13
0
 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")
コード例 #14
0
 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
コード例 #15
0
 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")
コード例 #16
0
 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
コード例 #17
0
 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
コード例 #18
0
 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
コード例 #19
0
 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
コード例 #20
0
 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
コード例 #21
0
 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
コード例 #22
0
 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
コード例 #23
0
ファイル: test_cli.py プロジェクト: ant31/python-prj-template
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
コード例 #24
0
 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
コード例 #25
0
 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
コード例 #26
0
 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
コード例 #27
0
ファイル: ignite_poap.py プロジェクト: javaos74/ignite
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()
コード例 #28
0
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
コード例 #29
0
 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
コード例 #30
0
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
コード例 #31
0
 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
コード例 #32
0
 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
コード例 #33
0
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
コード例 #34
0
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
コード例 #35
0
    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
コード例 #36
0
ファイル: bootstrap_image.py プロジェクト: datacenter/ignite
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
コード例 #37
0
 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)
コード例 #38
0
ファイル: fex_config.py プロジェクト: ychao1970/opennxos
    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
コード例 #39
0
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)
コード例 #40
0
    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)
コード例 #41
0
    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
コード例 #42
0
    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)
コード例 #43
0
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
コード例 #44
0
ファイル: poap-sn.py プロジェクト: chrisbog/Cisco-POAP
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)
コード例 #45
0
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
コード例 #46
0
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()
コード例 #47
0
ファイル: vlan_config.py プロジェクト: ychao1970/opennxos
def show_vlan(params):
    cmd_str = cmd_vlan_show % (params.vlan)

    print cmd_str
    return_xml = cli(cmd_str)
    print return_xml
    return True
コード例 #48
0
ファイル: sw_mgmt.py プロジェクト: casspencer/nexus9000
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
コード例 #49
0
ファイル: vlan_config.py プロジェクト: casspencer/nexus9000
def show_vlan(params):
    cmd_str = cmd_vlan_show % (params.vlan)

    print cmd_str
    return_xml = cli(cmd_str)
    print return_xml
    return True
コード例 #50
0
ファイル: change.py プロジェクト: ShaunGomez/NX-OS-Toolkit
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)
コード例 #51
0
ファイル: ignite_poap.py プロジェクト: senglobe/ignite
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()
コード例 #52
0
ファイル: l2_vlan_mgmt.py プロジェクト: casspencer/nexus9000
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
コード例 #53
0
 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
コード例 #54
0
ファイル: ignite_poap.py プロジェクト: senglobe/ignite
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()