def find_lldp_neighbor(interface):
	# LLDP rule: the lowest interface ID with an IP address is used as management interface (loopback are excluded)
	command = comware.CLI('display lldp neighbor-information interface ' + interface + ' verbose', False)
	output = command.get_output()
	neighbor = ['none', 'none']
	if len(output) != 1:
		# extracts the LLDP peer name
		for s in output:
			if s.find('System name') != -1:
				neighbor[0] = s.split()[3]
		# extracts the LLDP peer IP management address
		for s in output:
			if s.find('Management address') != -1:
				# keeps only the line with the management IP address
				if '.' in s.split()[3]:
					neighbor[1] = s.split()[3]
	return neighbor
Beispiel #2
0
def config(argument):
    if argument == "deploy":
        result = comware.CLI('display lldp neighbor-information verbose', False).get_output()
        port = ''
        for line in result:
            if 'LLDP neighbor-information of port' in line:
                start = line.rindex('[') + 1
                end = line.rindex(']', start)
                port = line[start:end]
            if 'System description  : ArubaOS' in line:
                print 'AP found at port ' + port
                brief = comware.CLI('display interface ' + port + ' brief', False).get_output()
                if not 'ARUBA-AP' in str(brief):
                    if ap_config_part1:
                        print 'Applying defined AP Configuration to port...'
                        comware.CLI('system-view ; interface ' + port + ' ; ' + ap_config_part1 +' ; return ; ', False)
                    if ap_config_part2:
                        comware.CLI('system-view ; interface ' + port + ' ; ' + ap_config_part2 +' ; return ; ', False)
                    comware.CLI('system-view ; interface ' + port + ' ; description ARUBA-AP ; return ; ', False)
                else:
				    print 'AP Configuration Already Applied to ' + port + ' Nothing to do here.'

    elif argument == "remove":
        result = comware.CLI('display interface brief', False).get_output()
        port = ''
        for line in result:
            if 'DOWN' in line and 'ARUBA-AP' in line:
                start = line.rindex('GE') + 2
                end = line.rindex('GE') + 8
                port = 'GigabitEthernet' + line[start:end]
                if default_config_part1:
                    print 'AP at ' + port + ' is down, applying defined default configuration to port...'
                    comware.CLI('system-view ; interface ' + port + ' ; ' + default_config_part1 + ' ; return ; ', False)
                if default_config_part2:
                    comware.CLI('system-view ; interface ' + port + ' ; ' + default_config_part2 + ' ; return ; ', False)

    else:
        print   "\nEnter the right arguments!" \
                "\n   -> ap_config.py deploy" \
                "\n   -> ap_config.py remove"
Beispiel #3
0
def startupCfg():
  global local_path, config_local_name
  result = None
  dest = "%s%s" %(local_path, config_local_name)
  write2Log("\nstartup saved-configuration %s begin" %dest)
  print "INFO: Startup Saved-configuration Start"
  comd = "startup saved-configuration %s main" % dest
  try:
    result = comware.CLI(comd, False)
    if result == None:
      write2Log("\nstartup saved-configuration %s failed" % dest)
      print "\n#### startup saved-configuration %s failed####" % dest
      return False
  except Exception as inst:
    write2Log("\nstartup %s exception: %s" % (dest, inst))
    print "\n#### startup %s exception: %s####" % (dest, inst)
    return False
  write2Log("\nstartup saved-configuration %s success" % dest)
  print "INFO: Completed Startup Saved-configuration"
  return True
def deployConfig(output_list):
    failures = 0
    fail_list = []
    for i in output_list:
        print "\nDeploying Configuration....\n"
        try:
            comware.CLI(i)
            print "\nInterface configuration successful\n"
        except SystemError as s:
            try:
                failures += 1
                fail_list.append(i)
                print "\nA part of the interface configuration failed, please check your csv-file or switch-config\n"
                raw_input(
                    "Press Enter to continue or CTRL-D to abort the deployment"
                )
            except EOFError:
                sys.exit("\nQuiting script!\n")
            except KeyboardInterrupt:
                sys.exit("\nQuiting script!\n")
    return failures, fail_list
Beispiel #5
0
def SwitchInput():
    sys.stdout.write("\r%d%%" % 0)
    sys.stdout.flush()
    #### Get Current IRF Member
    get_memberid = comware.CLI('display irf link', False).get_output()
    for line in get_memberid:
        if 'Member' in line:
            s1 = line.rindex('Member') + 7
            e1 = len(line)
            memberid = line[s1:e1]
    sys.stdout.write("\r%d%%" % 25)
    sys.stdout.flush()
    #### Get SwitchModel
    get_model = comware.CLI('display int ten brief', False).get_output()
    for line in get_model:
        if '/0/28' in line:
            model = "24 Ports"
        if '/0/52' in line:
            model = "48 Ports"
    sys.stdout.write("\r%d%%" % 50)
    sys.stdout.flush()
    #### Get Mac-address
    get_mac_address = comware.CLI('dis device manuinfo | in MAC_ADDRESS',
                                  False).get_output()
    for line in get_mac_address:
        if 'MAC_ADDRESS' in line:
            s2 = line.rindex('MAC_ADDRESS') + 23
            e2 = len(line)
            mac_address = line[s2:e2]
    #### Get Switch Software Version
    get_sw_version = comware.CLI('display version | in Software',
                                 False).get_output()
    sw_version = get_sw_version[1]
    sys.stdout.write("\r%d%%" % 75)
    sys.stdout.flush()
    #### Get PoE Software Version
    comware.CLI('system ; poe enable pse ' + str(poe_pse_numbers[memberid]),
                False).get_output()
    get_poe_version = comware.CLI('display poe pse | in Software',
                                  False).get_output()
    for line in get_poe_version:
        if 'Software' in line:
            s3 = line.rindex('Software') + 31
            e3 = len(line)
            poe_version = line[s3:e3]
    sys.stdout.write("\r%d%%\n" % 100)
    sys.stdout.flush()
    return memberid, model, mac_address, sw_version, poe_version
Beispiel #6
0
def get_config_port_ip():
    # Extract GigabitEthernet and IP port mapping from administrator Description
    output = comware.CLI('dis interface GigabitEthernet brief description',
                         False).get_output()
    ip = re.compile(
        r"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",
        re.VERBOSE)
    int = re.compile(r"GE[1-9]/[0-9]/[0-9]{1,2}", re.I)
    tab = []
    for i in output:
        n = ip.search(i)
        m = int.search(i)
        if n and m:
            tab.append(n.group(0))
            m = m.group(0).replace("GE", "GigabitEthernet")
            tab.append(m)
        else:
            continue
    # Convert list to dictionnairy
    result = dict(tab[i:i + 2] for i in range(0, len(tab), 2))
    return result
Beispiel #7
0
def main(argv):
    count = 0
    gateway = 'NULL0'
    if len(sys.argv) < 2:
        print 'routegen.py -c <count> -g <gateway>'
        sys.exit()            
    try:
        opts, args = getopt.getopt(argv,"hc:g:",["count=","gateway="])
    except getopt.GetoptError:
        print 'routegen.py -c <count> -g <gateway>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'routegen.py -c <count> -g <gateway>'
            sys.exit()
        elif opt in ("-c", "--count"):
            try:
                count = int(arg)
            except ValueError:
                print 'Count needs to be a number'
                sys.exit()
        elif opt in ("-g", "--gateway"):
            gateway = arg
    
    routestatic = 'ip route-static {0} 32 NULL0'
    command = 'system-view ; '
    print 'Generating routes'
    for i in range(count):
        n1 = str(10)
        n2 = str(random.randrange(1, 254, 1))
        n3 = str(random.randrange(1, 254, 1))
        n4 = str(random.randrange(1, 254, 1))
        ip = n1 + '.' + n2 + '.' + n3 + '.' + n4
        command = command + routestatic.format(ip) + ' ; '
    
    print 'Installing routes'
    comware.CLI(command, False)
def SwitchInput():
    sys.stdout.write("\r%d%%" % 0)
    sys.stdout.flush()
    #### Enable local logging: flash:/logfile/logfile.log
    comware.CLI(
        'system ; info-center logfile frequency 1 ; info-center source SHELL logfile level debugging ; info-center source CFGMAN logfile level debugging',
        False)
    #### Get Current IRF Member
    memberid = (comware.CLI('display irf link', False).get_output())[1][7]
    sys.stdout.write("\r%d%%" % 20)
    sys.stdout.flush()
    #### Get SwitchModel
    model = "48 Ports" if "/0/48" in str(
        comware.CLI('display int brief', False).get_output()) else "24 Ports"
    sys.stdout.write("\r%d%%" % 40)
    sys.stdout.flush()
    #### Get Mac-address
    mac_address = comware.CLI('dis device manuinfo | in MAC_ADDRESS',
                              False).get_output()[1][23:37]
    sys.stdout.write("\r%d%%" % 60)
    sys.stdout.flush()
    #### Get Switch Software Version
    sw_version = comware.CLI('display version | in Software',
                             False).get_output()[1]
    sys.stdout.write("\r%d%%" % 80)
    sys.stdout.flush()
    #### Get PoE Software Version
    try:
        comware.CLI('system ; int gig' + memberid + '/0/1 ; poe enable ',
                    False)
        poe_version = comware.CLI('display poe pse | in Software',
                                  False).get_output()[1][36:40]
    except SystemError:
        poe_version = 'N/A'
    sys.stdout.write("\r%d%%\n" % 100)
    sys.stdout.flush()
    return memberid, model, mac_address, sw_version, poe_version
Beispiel #9
0
def configureSwitch():
    switchMacAddress = comware.CLI(
        "disp irf | i MAC").get_output()[1][-14:].replace("-", "")
    filename2 = 'flash:/varMatrix.json'
    fin2 = open(filename2, 'r')
    switchList = json.loads(fin2.read())
    fin2.close()
    #    #print(switchList)
    for switch in switchList:
        if switch == switchMacAddress:
            try:
                comware.CLI("sys ; irf member 2 renumber " +
                            switchList[switch]['IRF'])
            except SystemError:
                pass
            try:
                comware.CLI("sys ; irf member 3 renumber " +
                            switchList[switch]['IRF'])
            except SystemError:
                pass
            try:
                comware.CLI("sys ; irf member 1 renumber " +
                            switchList[switch]['IRF'])
            except SystemError:
                pass
            try:
                comware.CLI("copy ftp://james:demo@" +
                            switchList[switch]['tftpServer'] +
                            "/comware/tftpboot/" +
                            switchList[switch]['firmwareBackup'] + " .")


#    #            comware.CLI("ftp " + switchList[switch]['tftpServer'] + " get " + switchList[switch]['firmwareBackup'])
            except SystemError:
                pass
            comware.CLI("delete /unreserved *.bin")
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 1 b")
            except SystemError:
                pass
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 2 b")
            except SystemError:
                pass
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 3 b")
            except SystemError:
                pass
            try:
                comware.CLI("copy ftp://james:demo@" +
                            switchList[switch]['tftpServer'] +
                            "/comware/tftpboot/" +
                            switchList[switch]['firmwareMain'] + " .")
    #            comware.CLI("ftp " + switchList[switch]['tftpServer'] + " get " + switchList[switch]['firmwareMain'])
            except SystemError:
                pass
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 1 m")
            except SystemError:
                pass
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 2 m")
            except SystemError:
                pass
            try:
                comware.CLI("boot-loader file flash:/" +
                            switchList[switch]['firmwareBackup'] + " s 3 m")
            except SystemError:
                pass
            comware.CLI("delete /unreserved *.ipe")
            filename3 = 'flash:/startup.cfg'
            fin3 = open(filename3, 'w')
            filename = 'flash:/template.txt'
            fin = open(filename, 'r')
            data = fin.readlines()
            print switch
            for i in data:
                j = i.replace('{{', '""" + ').replace('}}', ' + """')
                if '[' in j:
                    fin3.write(
                        eval('"""' +
                             j.replace('"', "'").replace("'''", '"""') +
                             '"""'))
                else:
                    fin3.write(j)
            fin.close()
            fin3.close()
        else:
            pass

    comware.CLI('startup saved-configuration startup.cfg backup')
    comware.CLI('startup saved-configuration startup.cfg main')
    try:
        comware.CLI("delete /unreserved *.txt")
        comware.CLI("delete /unreserved *.json")
        comware.CLI("delete /unreserved *.py")
        comware.CLI("delete /unreserved *.pyc")
    except SystemError:
        pass
    try:
        comware.CLI("sys ; public-key local create rsa")
        comware.CLI("ping 8.8.8.8")
    except SystemError:
        pass
    try:
        comware.CLI('reboot force')
    except SystemError:
        pass
Beispiel #10
0
# This script can be used for Virtual Router demonstrations to set-up EVI tunnel
# when needed

__author__ = 'Chuck Dilts'

import comware
import time

comware.CLI('system-view ;evi site-id 1 ; evi designated-vlan 10 ;return ')
time.sleep(1)
comware.CLI(
    'system-view ; interface Tunnel1 mode evi ; evi arp-suppression enable ; evi extend-vlan 10 ; source LoopBack0 ; evi network-id 100 ; evi neighbor-discovery client enable 3.3.3.1 ; return '
)
time.sleep(1)
comware.CLI(
    'system-view ; interface GigabitEthernet2/0 ; evi enable ; return ')
print 'EVI has been added'
def Reboot():
    print('reboot force')
    comware.CLI('reboot force')
    quit()
Beispiel #12
0
# This script can be used for Virtual Router demonstrations to remove EVI tunnel
# when no longer needed

''' Copyright 2016 Hewlett Packard Enterprise Development LP.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.'''


__author__ = 'Chuck Dilts'

import comware


comware.CLI('system-view ; undo int tun 1 ; undo evi site-id ; undo evi designated-vlan ; return ')
comware.CLI('system-view ; interface GigabitEthernet2/0 ; undo evi enable ; return ')
print 'EVI has been removed' 




def SwitchInput():
    sys.stdout.write("\r%d%%" % 0)
    sys.stdout.flush()
    #### Enable logging: flash:/logfile/logfile.log
    comware.CLI(
        'system ; info-center logfile frequency 1 ; info-center source SHELL logfile level debugging ; info-center source SNMP logbuffer level debugging',
        False)
    #### Get Current IRF Member
    get_memberid = comware.CLI('display irf link', False).get_output()
    for line in get_memberid:
        if 'Member' in line:
            s1 = line.rindex('Member') + 7
            e1 = len(line)
            memberid = line[s1:e1]
    sys.stdout.write("\r%d%%" % 25)
    sys.stdout.flush()
    #### Get SwitchModel
    get_model = comware.CLI('display int ten brief', False).get_output()
    for line in get_model:
        if '/0/28' in line:
            model = "24 Ports"
        if '/0/52' in line:
            model = "48 Ports"
    sys.stdout.write("\r%d%%" % 50)
    sys.stdout.flush()
    #### Get Mac-address
    get_mac_address = comware.CLI('dis device manuinfo | in MAC_ADDRESS',
                                  False).get_output()
    for line in get_mac_address:
        if 'MAC_ADDRESS' in line:
            s2 = line.rindex('MAC_ADDRESS') + 23
            e2 = len(line)
            mac_address = line[s2:e2]
    #### Get Switch Software Version
    get_sw_version = comware.CLI('display version | in Software',
                                 False).get_output()
    sw_version = get_sw_version[1]
    sys.stdout.write("\r%d%%" % 75)
    sys.stdout.flush()
    #### Get PoE Software Version
    try:
        comware.CLI(
            'system ; poe enable pse ' + str(poe_pse_numbers[memberid]),
            False).get_output()
    except SystemError:
        poe_version = 'N/A'
    try:
        comware.CLI('system ; int gig' + memberid + '/0/1 ; poe enable ',
                    False).get_output()
    except SystemError:
        poe_version = 'N/A'
    try:
        get_poe_version = comware.CLI('display poe pse | in Software',
                                      False).get_output()
        for line in get_poe_version:
            if 'Software' in line:
                s3 = line.rindex('Software') + 31
                e3 = len(line)
                poe_version = line[s3:e3]
    except SystemError:
        poe_version = 'N/A'
    sys.stdout.write("\r%d%%\n" % 100)
    sys.stdout.flush()
    return memberid, model, mac_address, sw_version, poe_version
Beispiel #14
0
def getSerialNumber(): 
  result = comware.CLI('screen-length disable ; display device manuinfo | in DEVICE_SERIAL_NUMBER ; ', False).get_output()
  return result[2].split(":")[1].strip()
Beispiel #15
0
def list_live_ip(ip):
    # Ping IP list
    for i in ip.keys():
        cmd = comware.CLI('ping %s %s' % (ping_opt, i), False)
    return 'none'
def Reboot():
    comware.CLI('reboot force')
    quit()
Beispiel #17
0
def etss_range(etssrange):
    hosts = []
    block = etssrange.split('.')
    for x, y in enumerate(block):
        if '-' in y:
            blockrange = y.split('-')
            for z in range(int(blockrange[0]), int(blockrange[1])+1):
                ipaddr = '.'.join(block[:x] + [str(z)] + block[x+1:])
                hosts += etss_range(ipaddr)
            break
    else:
        hosts.append(etssrange)
    return hosts


ip = sys.argv[1]
target_ip = etss_range(ip)
ping_opt = '-c 1'


for i in target_ip:
    cmd = comware.CLI('ping %s %s' % (ping_opt, i), False)
    output = cmd.get_output()
    a = re.search('([0-9\.]+)% packet loss', output[5])
    if float(a.group(1)) == 0.0:
        print('%s - %s' % (i, 'UP'))
    else:
        print('%s - %s' % (i, 'DOWN'))


Beispiel #18
0
def StartMenu(memberid, model, mac_address, sw_version, poe_version):
    checkbox1 = ''
    checkbox2 = ''
    checkbox3 = ''
    checkbox4 = ''
    checkbox5 = ''
    set_memberid = ''
    Menu = True
    while Menu:
        print "\nCurrent Switch Information:"
        print "  Current Switch Model         " + str(model)
        print "  Current MAC-Address          " + str(mac_address)
        print "  Current Software Version     " + str(sw_version)
        print "  Current PoE Version          " + str(poe_version)
        print "  Current Member ID            " + str(memberid)
        print "  Newly chosen Member ID       " + str(set_memberid)
        print "\nFiles Ready for installation:"
        print "  Switch Software File         " + str(sysfile)
        print "  Switch PoE Software File     " + str(poefile)
        print "\n\n%-50s %-1s %-1s %-1s" % ("1.Update Switch Firmware", "[",
                                            checkbox1, "]")
        print "%-50s %-1s %-1s %-1s" % ("2.Update PoE Firmware", "[",
                                        checkbox2, "]")
        print "%-50s %-1s %-1s %-1s" % ("3.Change IRF MemberID Only", "[",
                                        checkbox3, "]")
        print "%-50s %-1s %-1s %-1s" % (
            "4.Change IRF MemberID and set IRF-Port-config", "[", checkbox4,
            "]")
        print "%-50s %-1s %-1s %-1s" % ("5.Trigger iMC for deployment", "[",
                                        checkbox5, "]")
        print "%-50s " % ("6.Run selection")
        print "%-50s " % ("7.Restart Automatic Configuration")
        print "%-50s " % ("8.Exit/Quit and reboot")
        ans = raw_input("\nWhat would you like to do? ")
        if ans == "1":
            checkbox1 = "X"
        elif ans == "2":
            checkbox2 = "X"
        elif ans == "3":
            set_memberid = raw_input("Enter new Member-ID: ")
            checkbox3 = "X"
        elif ans == "4":
            set_memberid = raw_input("Enter new Member-ID: ")
            checkbox3 = "X"
            checkbox4 = "X"
            checkbox5 = ""
        elif ans == "5":
            checkbox4 = ""
            checkbox5 = "X"
        elif ans == "6":
            Menu = False
        elif ans == "7":
            print "\nQuiting script...\n"
            sys.exit()
        elif ans == "8":
            print "\nQuiting script and rebooting...\n"
            comware.CLI("reboot force")
            sys.exit()
        else:
            print("\n Not Valid Choice Try again")
    return checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, set_memberid