def main(): handle = UcsHandle("10.0.0.201", "ucspe", "ucspe", secure=False) handle.login() ## Query Based on Class Name print("\n\n=== Query Based on Class Name") blades = handle.query_classid("computeBlade") for blade in blades: print(blade.dn, blade.name, blade.model) ## Query Class Name with filter print("\n\n=== Query Based on Class Name with Filter equal to") filter = "(model, 'UCSB-EX-M4-1', type='eq')" blades = handle.query_classid("computeBlade", filter_str=filter) for blade in blades: print(blade.dn, blade.name, blade.model) print("\n\n=== Query Based on Class Name with Filter not-equal to") filter = "(model,'UCSB-EX-M4-1',type='ne')" blades = handle.query_classid("computeBlade", filter_str=filter) for blade in blades: print(blade.dn, blade.name, blade.model) ## Query Directly the DN of an Object print("\n\n=== Query Based on Distinguished Name") blade = handle.query_dn(blades[0].dn) print(blade) handle.logout()
def add_vlan_to_vnic_template(): """ Add VLAN to VNIC Template """ handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() my_vlan = handle.query_classid("fabricVlan", filter_str='(id,"301")') my_templ = handle.query_classid("vnicLanConnTempl", filter_str='(name,"Trunk_B")') VnicEtherIf(parent_mo_or_dn=my_templ[0], default_net=my_vlan[0].default_net, name=my_vlan[0].name) handle.add_mo(my_templ[0], True) handle.commit()
def update_usrlbl(usrlbl): """ Update object usrlbl, ComputeBlade,ComputeRackUnit, LsServer""" handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() usrlbl_classes = ['computeblade', 'computerackunit', 'lsserver'] for usrlbl_class in usrlbl_classes: compute_mos = handle.query_classid(usrlbl_class) for compute_mo in compute_mos: if '/blade-' in compute_mo.dn: print('blade', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl elif '/rackunit-' in compute_mo.dn: print('rack', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl elif '/ls-' in compute_mo.dn: print('service profile', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl handle.add_mo(compute_mo, modify_present=True) handle.commit()
def change_lable(ucsm_ip, user, password): handle = UcsHandle(ucsm_ip, user, password) handle.login() print "\n-----------모든 블레이드 서버의 이름. 변경 전---------------" blades = handle.query_classid(class_id="computeBlade") for blade in blades: print "Blade-" + blade.slot_id + " Lable:-" + blade.usr_lbl blade.usr_lbl = "Ironman" + blade.slot_id # 블레이드 이름 + 번호 handle.set_mo(blade) handle.commit() print "\n-----------모든 블레이드 서버의 이름. 변경 후---------------" blades = handle.query_classid(class_id="computeBlade") for blade in blades: print "Blade-" + blade.slot_id + " Lable:-" + blade.usr_lbl handle.logout()
def main(): handle = UcsHandle("192.168.254.200","ucspe","ucspe", secure=False) handle.login() # Query Blades that are unassociated print("\n\n=== Query Based on Class Name with Filter equal to") filter = "(oper_state,'unassociated',type='eq')".format(BLADE_MODEL) blades = handle.query_classid("computeBlade",filter_str=filter) print("***Found {} Blades".format(len(blades))) # Error Check for available blades if len(blades) < NUM_SP: error = "There are only {} blades left to associate, and you asked for {} Servers to be generated".format(len(blades),NUM_SP) raise NameError(error) # Setup Variable for SP Templates to be deployed dn_set = DnSet() for i in range(1, NUM_SP+1): dn = Dn() sp_name = "SP{}".format(str(i)) dn.attr_set("value", sp_name) dn_set.child_add(dn) # Build XML Object to submit to the API templates = ls_instantiate_n_named_template( cookie=handle.cookie, dn="org-root/ls-globotemplate", in_target_org="org-root", in_error_on_existing="false", in_name_set=dn_set ) # Send XML Object to xml process handler sp_list = handle.process_xml_elem(templates) # Loop through each created sp, and associate them to blades i = 0 while i < len(sp_list): sp = sp_list[i] blade = blades[i] # Print SP and Blade Combination print(sp.dn,blade.dn) # Get Binding Object mo = LsBinding( parent_mo_or_dn=sp.dn, pn_dn=blade.dn, restrict_migration="no" ) # Add MO Binding Object to handler handle.add_mo(mo,modify_present=True) i=i+1 # Bundle the SP Associates handle.commit()
def get_ucs_ntp_settings(ucs_list, ucs_username, user_passwd): timestamps_all=[] for ucs in ucs_list: handle = UcsHandle(ip=ucs, username=ucs_username, password=user_passwd) handle.login() mo_dn = handle.query_dn("sys") ucs_current_time=mo_dn.current_time utc_current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f1') utc_current_time = utc_current_time[:-4] t1 = datetime.strptime(ucs_current_time, "%Y-%m-%dT%H:%M:%S.%f") t2 = datetime.strptime(utc_current_time, "%Y-%m-%dT%H:%M:%S.%f") diff = t1 - t2 ntp_dn = handle.query_classid("commNtpProvider") mgmt_ip_a = handle.query_dn("sys/switch-A") fi_ip = mgmt_ip_a.oob_if_ip netmask = mgmt_ip_a.oob_if_mask if len(ntp_dn) > 0: ntp_servers = [ n.name for n in ntp_dn ] network=ipaddress.ip_network('{}/{}'.format(fi_ip,netmask),strict=False) correct_ntp=ipaddress.ip_address(ntp_servers[0]) in ipaddress.ip_network(network) else: ntp_servers = ['no ntp'] # create temp list to add to a list of lists timestamp_per_site = [] timestamp_per_site.extend([handle.ip, utc_current_time, ucs_current_time, abs(diff.total_seconds()), ntp_servers[0], correct_ntp]) timestamps_all.append(timestamp_per_site) print("=> logged out of {}".format(handle.ip)) handle.logout() if platform.system() != ('Windows'): os.system('clear') else: os.system( 'cls' ) headers=['site', 'utc timestamp', 'ucs timestamp', 'offset', 'ntp server', 'correct'] print(tabulate(timestamps_all, headers=headers, tablefmt=table_output))
def remove_ucs_bios_policy(): """ Remove UCS BIOS Policy """ handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() mo_bios_policies = handle.query_classid("BiosVProfile") for mo_bios_policy in mo_bios_policies: if mo_bios_policy.name == "test-bios-prof": handle.remove_mo(mo_bios_policy) handle.commit()
def get_sp_from_domain(domain): # Create a connection handle handle = UcsHandle(domain['ip'], domain['username'], domain['password']) # Login to the server handle.login() # Get all service profiles query = handle.query_classid(class_id="LsServer") # Logout from the server handle.logout() # Convert them in a list with desired attributes sp_list = [[sp.name, sp.type, sp.assign_state, sp.assoc_state] for sp in query] return sp_list
def updateNtp(module): ucs_ip = module.params['ucs_ip'] ucs_user = module.params['ucs_user'] ucs_pass = module.params['ucs_pass'] ntp = module.params['ntp'] state = module.params['state'] results = {} results['changed'] = False results['created'] = [] results['removed'] = [] # Login to UCS try: handle = UcsHandle(ucs_ip, ucs_user, ucs_pass) except: module.fail_json(msg="Could not login to UCS") try: # Obtain a handle for the Timezone object tz = handle.query_classid(class_id="CommDateTime") if type(ntp) != list: ntp = list(ntp) for server in ntp: filter_str = '(name, "%s", type="eq")' % (server) obj = handle.query_children( in_mo=tz[0], class_id="CommNtpProvider", filter_str=filter_str ) if state == 'present' and len(obj) > 0: pass elif state == 'present' and len(obj) == 0: ntp_server = CommNtpProvider(tz[0], name=server) handle.add_mo(ntp_server) handle.commit() results['created'].append(server) results['changed'] = True elif state == 'absent' and len(obj) > 0: handle.remove_mo(obj[0]) handle.commit() results['changed'] = True results['removed'].append(server) except Exception, e: module.fail_json(msg="Could not create or validate servers; %s" % e)
def updateVlans(module): ucs_ip = module.params['ucs_ip'] ucs_user = module.params['ucs_user'] ucs_pass = module.params['ucs_pass'] vlans = module.params['vlans'] state = module.params['state'] results = {} results['changed'] = False results['created'] = [] results['removed'] = [] # Login to UCS try: handle = UcsHandle(ucs_ip, ucs_user, ucs_pass) except: module.fail_json(msg="Could not login to UCS") try: # Obtain a handle for the LAN Cloud lancloud = handle.query_classid(class_id="FabricLanCloud") defined_vlans = handle.query_children(in_mo=lancloud[0], class_id="FabricVlan") for key, val in vlans.iteritems(): filter_str = '(name, "%s", type="eq") and (id, %s, type="eq")' \ % (key, val) obj = handle.query_children(in_mo=lancloud[0], class_id="FabricVlan", filter_str=filter_str) if state == 'present' and len(obj) > 0: pass elif state == 'present' and len(obj) == 0: vlan = FabricVlan(lancloud[0], name=key, id=str(val)) handle.add_mo(vlan) handle.commit() results['created'].append(key) results['changed'] = True elif state == 'absent' and len(obj) > 0: handle.remove_mo(obj[0]) handle.commit() results['changed'] = True results['removed'].append(key) except Exception, e: module.fail_json(msg="Could not create or validate VLANs; %s" % e)
def getServiceProfile(): authInfo = _getUcsAuthInfo((request.headers)) handle = UcsHandle(*authInfo, secure=False) if not handle.login(): handle.logout() return 'Forbidden', "", 403 rootElements = [{ "ciscoXmlName": "orgOrg", "humanReadableName": "ServiceProfile" }] finalObjs = {} for x in rootElements: subElement = {} try: components = handle.query_classid(x["ciscoXmlName"]) except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: if not (type(components) == list): handle.logout() return "Couldn't fetch " + x["humanReadableName"], "", 500 for y in components: subElement["org"] = y.level subElement["members"] = [] try: lsList = handle.query_children(in_dn="org-root", class_id="lsServer") except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: if not (type(lsList) == list): handle.logout() return "Couldn't fetch Logical Servers", "", 500 for item in lsList: logicalServer = {} identifier = item.dn obj = handle.query_dn(dn=identifier) logicalServer["name"] = obj.rn logicalServer["path"] = obj.dn logicalServer["associatedServer"] = obj.pn_dn logicalServer["assoc_state"] = obj.assoc_state subElement["members"].append(logicalServer) finalObjs[x["humanReadableName"]] = subElement handle.logout() return finalObjs
def getpods(podnum): from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("172.20.1.10", "admin", "Cisco1234!") handle.login() obj = handle.query_classid("ComputeRackUnit") pods = {} pods['compute'] = [] for server in obj: pods['compute'].append({ "ServerName": server.rn, "Serial": server.serial, "Model": server.model }) return pods handle.logout()
def main(): handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False) handle.login() # Get Parrent Object lan_cloud = handle.query_classid("FabricLanCloud") # Create new VLAN Object for vlan 100 vlan_mo = FabricVlan(parent_mo_or_dn=lan_cloud[0], name="vlan100", id="100") # Add the object to be ready to be committed handle.add_mo(vlan_mo) # Commit changes back to UCS handle.commit() handle.logout()
## The UCS Python SDK Makes Deploying Servers a Breeze ## Exercise 3 # Get a handle and login to UCS Manager from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "password") handle.login() # Query the computeBlade Class blades = handle.query_classid("computeBlade") # Print computeBlade object attributes for blade in blades: print(blade.dn, blade.total_memory, blade.num_of_cpus, blade.serial) # Print out the computeBlade child object equipmentLocatorLed Class attribute oper_state for blade in blades: leds = handle.query_children(in_dn=blade.dn, class_id="equipmentLocatorLed") for led in leds: print(blade.dn, led.oper_state) # Logout of the UCS Manager handle.logout()
def main(): """ Main routine to be executed """ # Get the CLI arguements args = get_parser().parse_args() section_platform = args.platform parser = SafeConfigParser() # Since when the script executes, it is difficult to assume the relative path - as depends on where you run your Python script from. # Especially if calling it via absolute path and you're not in the actual directory # Hence, use the following to effectively obtain the config file as if it were '../my_credentials.ini' parent_configFilePath = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', MY_CONFIG_FILE) local_configFilePath = os.path.join(os.path.abspath(os.path.dirname(__file__)), '.', MY_CONFIG_FILE) # Check if MY_CONFIG_FILE is in the current local directory, otherwise check the parent directory. If missing in both, then fail if os.path.exists(local_configFilePath): # Use the local directory # print ("Found in local directory") configFilePath = local_configFilePath elif os.path.exists(parent_configFilePath): # Use the parent directory # print ("Found in parent directory") configFilePath = parent_configFilePath else: # Missing completely. Fail print ("Unable to locate your Config File: {}. Please ensure that you have it created and available".format(MY_CONFIG_FILE)) print ("Not found in the local directory: {}".format(local_configFilePath)) print ("Not found in the Parent directory: {}".format(parent_configFilePath)) exit(0) if args.debug: print ("Config File: {}".format(configFilePath)) # Attempt to read the configuration file try: result = parser.read(configFilePath) except Exception as e : print(str(e)) exit(0) if section_platform not in parser.sections(): print ("Please ensure you select a Platform that you have defined in your {} file".format(MY_CONFIG_FILE)) print ("Current Platforms defined: " + str(parser.sections())) exit(0) else: try: UCSM = parser.get(section_platform, 'UCSM') USER = parser.get(section_platform, 'USER') PASS = parser.get(section_platform, 'PASS') except Exception as e : print(str(e),' could not read configuration file') for section_name in parser.sections(): print 'Section:', section_name print ' Options:', parser.options(section_name) if args.debug: for name, value in parser.items(section_name): print ' %s = %s' % (name, value) print # Exit due to exception exit(0) # Rest of normal flow would take place here handle = UcsHandle(UCSM, USER, PASS,secure=False) handle.login() # Obtain all the blade servers available in the UCS Domain blade_mo = handle.query_classid(class_id="computeBlade") server_data = [] server_dict = {} count = 1 for line in blade_mo: # assign to dictionary, count:line.dn server_dict[count] = line.dn # assign to a list that will be used by tabulate to format nicely server_data.append((count, line.dn, line.association, line.discovery, line.name, line.model, line.server_id, line.serial, line.operability, line.oper_power)) count += 1 # Display the data in table format print tabulate(server_data, headers=["KVM Launch ID", "Blade DN", "Association", "Discovery Status", "Blade Name", "Blade Model", "Blade ID", "Blade S/N", "Operability", "Power Status"], tablefmt="grid") # Ask user to pick a server based off count ID, type(int) # Check that the ID selected is valid, ie, exists in server_dict, otherwise throw error to pick again while 1: selection = int(input("Select a KVM ID to Launch [1-" + str((count - 1)) + "]: ")) if selection < 1 or selection > (count - 1): print "Please select a KVM Launch ID between 1 and " + str((count - 1)) print "Try again..." else: break # Once selection is made, do another lookup to query_dn based off line.dn # Used the returned object to launch the KVM selected_blade_mo = handle.query_dn(server_dict[selection]) # Need to use query_dn instead of query_classid due to the returned object. # query_dn returns a class object # query_classid returns a list # The ucs_kvm_launch expects to be able to call blade_mo.dn directly via a class object print "=" * 80 print selected_blade_mo print "=" * 80 # Since launching via a service profile, use the blade object, obtain the assigned Service Profile # then perform another lookup to that specific DN to obtain a lsServer class object to launch selected_sp_mo = handle.query_dn(selected_blade_mo.assigned_to_dn) # sp_mo is of type LsServer ucs_kvm_launch(handle, service_profile=selected_sp_mo) # blade_mo is of type ComputeBlade. Can't seem to get this version to work # ucs_kvm_launch(handle, blade=selected_blade_mo, need_url=True) handle.logout()
handle = UcsHandle(UCSM, USER, PASS) # Login to UCSM handle.login() # If successful, print some details print("Login was successful") print("=" * 50) print("UCS Cookie: " + handle.cookie) print("UCS IP: " + handle.ip) print("UCS Name: " + handle.ucs) print("UCS Version: " + str(handle.version)) print("=" * 50) print("Compute Blade Output") mo_list = handle.query_classid("ComputeBlade") for blade in mo_list: print blade.serial, blade.rn, blade.oper_state, blade.oper_power, blade.server_id, blade.availability, blade.name print("=" * 50) print("Associated blades only") filter_exp = '(oper_state,"ok")' mo_list = handle.query_classid("ComputeBlade", filter_str=filter_exp) for blade in mo_list: print blade.serial print("=" * 50) print("Specific Serial Prefix Search") filter_exp = '(serial,"^QCI\d{4}", type="re")' mo_list = handle.query_classid("ComputeBlade", filter_str=filter_exp) for blade in mo_list:
NOTE: Launching KVM session still requires that your host has Java installed and functioning correctly Michael Petrinovic 2018 """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.utils.ucskvmlaunch import ucs_kvm_launch from tabulate import tabulate # Import my credentials for UCS Login from ucs_my_credentials.py in the same directory from ucs_my_credentials import * handle = UcsHandle(UCSM, USER, PASS, secure=False) handle.login() # Obtain all the blade servers available in the UCS Domain blade_mo = handle.query_classid(class_id="computeBlade") server_data = [] server_dict = {} count = 1 for line in blade_mo: # assign to dictionary, count:line.dn server_dict[count] = line.dn # assign to a list that will be used by tabulate to format nicely server_data.append((count, line.dn, line.association, line.discovery, line.name, line.model, line.server_id, line.serial, line.operability, line.oper_power)) count += 1
def main(): args = get_args() params = get_device_parameters(args) valid_addresses = get_valid_addresses(args.ucs_host, params['alternate_addresses']) login_success = False errors = [] # Try all valid addresses until one succeeds or they all fail. for host_addr in valid_addresses: if params['server_type'] == 'ucsm': handle = UcsHandle(host_addr, params['username'], params['password']) try: if not handle.login(): errors.append("Failed to connect to {} as user {}!".format( args.ucs_host, params['username'])) continue else: login_success = True except Exception as e: errors.append(str(e)) continue if args.severity is not None: # Build a filter string that we will pass into an API call (UCSM only) filter_str = '(severity, "{}", type="eq")'.format( args.severity) else: filter_str = None # Output the list of faults, if any, with the given severity level fault_list = handle.query_classid('faultInst', filter_str=filter_str) for fault in fault_list: print('{}: [{}] {}: {}'.format(fault.created, fault.severity, fault.cause, fault.descr)) handle.logout() break elif params['server_type'] == 'imc': handle = ImcHandle(host_addr, params['username'], params['password']) try: if not handle.login(timeout=10): errors.append("Failed to connect to {} as user {}!".format( args.ucs_host, params['username'])) continue else: login_success = True except IndexError: errors.append( 'An exception was thrown trying to connect to {}. ' 'It may be running an old/unsupported firmware version.' ''.format(args.ucs_host)) continue except Exception as e: errors.append(str(e)) continue # Output the list of faults, if any, with the given severity level fault_list = handle.query_classid('faultInst') for fault in fault_list: if args.severity is None or args.severity == fault.severity: print('{}: [{}] {}: {}'.format(fault.created, fault.severity, fault.cause, fault.descr)) handle.logout() break else: print("Unrecognized server type '{}'. " "It should be 'ucsm' or 'imc'.".format( params['server_type'])) exit(1) if not login_success: print('Failed all connection attempts:\n{}'.format('\n'.join(errors)))
Author: John McDonough ([email protected]) github: (@movinalot) Cisco Systems, Inc. """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.utils import comparesyncmo # Login to a SOURCE UCS and a TARGET UCS SOURCE_UCS = UcsHandle("13.58.22.56", "admin", "password") TARGET_UCS = UcsHandle("18.217.19.216", "admin", "password") SOURCE_UCS.login() TARGET_UCS.login() # Query the SOURCE UCS VLANS and the TARGET UCS VLANS SOURCE_UCS_VLANS = SOURCE_UCS.query_classid("fabricVlan") TARGET_UCS_VLANS = TARGET_UCS.query_classid("fabricVlan") # Compare the TARGET VLANS with the SOURCE VLANS DIFFERENCE_VLANS = comparesyncmo.compare_ucs_mo(TARGET_UCS_VLANS, SOURCE_UCS_VLANS) print("difference is %s" % DIFFERENCE_VLANS) if DIFFERENCE_VLANS: # Display the difference comparesyncmo.write_mo_diff(DIFFERENCE_VLANS) # Sync - apply the difference to the TARGET_UCS, remove from the # TARGET_UCS any objects that are not present on the SOURCE_UCS # This action is not done through the HANDLE, the commit() is implicit
from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("10.10.20.113", "ucspe", "ucspe") handle.login() # DOCUMENTATION https://github.com/CiscoUcs/ucsmsdk https://ucsmsdk.readthedocs.io/en/latest/ ######## ORG INFO ########### org = handle.query_classid(class_id="orgOrg", hierarchy=True) print(org) ########## Server Blade info ############ servers = handle.query_classid("computeBlade") # print(srv) for server in servers: print(server) for server in servers: print(server.dn, server.num_of_cpus, server.available_memory) ####### Specific DN query ############### blade = handle.query_dn('sys/chassis-3/blade-1') print(blade) # Logout handle.logout()
## More Powerful Cisco Compute Python Scripts with UCS Python SDK ## Exercise 2 # Add Vlans in a transaction from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login() fabric_lan_cloud = handle.query_classid("FabricLanCloud") vlan_ids = ['300', '301', '302', '303', '304', '305'] for vlan_id in vlan_ids: add_vlan = FabricVlan(parent_mo_or_dn=fabric_lan_cloud[0], name="vlan" + vlan_id, id=vlan_id) handle.add_mo(add_vlan) handle.commit() handle.logout() input("Vlans Added - Press Enter to Continue to Set Vlans...") # Set Vlans is a transaction from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login()
except: password = getpass.getpass("Password for " + sys.argv[2] + ": ") handle = UcsHandle(ip=str(sys.argv[1]), username=str(sys.argv[2]), password=password) # handle = UcsHandle(ip=sys.argv[1],username=sys.argv[2],password=sys.argv[3]) handle.login() # Filter specific errors filter_exp = '(ack,"no",type="eq")' # Collect UCS fualts using filter ucs_faults = handle.query_classid("faultInst", filter_str=filter_exp) # setup dictionary with default value for a new entry is an empty list dict_of_faults = defaultdict(list) # loop over faults and append it to the appropriate exit code key # UCS fault details can be found here # https://www.cisco.com/c/en/us/td/docs/unified_computing/ucs/ts/faults/reference/ErrMess/FaultsIntroduction.html#wp1070261 # if ucs_faults is empty # logout and return exit code '0' if not ucs_faults: print("Everything is fine -- Keep Calm and Carry On!") handle.logout()
def main(): """ Main routine to be executed """ # Get the CLI arguements args = get_parser().parse_args() section_platform = args.platform parser = SafeConfigParser() # Since when the script executes, it is difficult to assume the relative path - as depends on where you run your Python script from. # Especially if calling it via absolute path and you're not in the actual directory # Hence, use the following to effectively obtain the config file as if it were '../my_credentials.ini' parent_configFilePath = os.path.join( os.path.abspath(os.path.dirname(__file__)), '..', MY_CONFIG_FILE) local_configFilePath = os.path.join( os.path.abspath(os.path.dirname(__file__)), '.', MY_CONFIG_FILE) # Check if MY_CONFIG_FILE is in the current local directory, otherwise check the parent directory. If missing in both, then fail if os.path.exists(local_configFilePath): # Use the local directory # print ("Found in local directory") configFilePath = local_configFilePath elif os.path.exists(parent_configFilePath): # Use the parent directory # print ("Found in parent directory") configFilePath = parent_configFilePath else: # Missing completely. Fail print( "Unable to locate your Config File: {}. Please ensure that you have it created and available" .format(MY_CONFIG_FILE)) print("Not found in the local directory: {}".format( local_configFilePath)) print("Not found in the Parent directory: {}".format( parent_configFilePath)) exit(0) if args.debug: print("Config File: {}".format(configFilePath)) # Attempt to read the configuration file try: result = parser.read(configFilePath) except Exception as e: print(str(e)) exit(0) if section_platform not in parser.sections(): print( "Please ensure you select a Platform that you have defined in your {} file" .format(MY_CONFIG_FILE)) print("Current Platforms defined: " + str(parser.sections())) exit(0) else: try: UCSM = parser.get(section_platform, 'UCSM') USER = parser.get(section_platform, 'USER') PASS = parser.get(section_platform, 'PASS') except Exception as e: print(str(e), ' could not read configuration file') for section_name in parser.sections(): print 'Section:', section_name print ' Options:', parser.options(section_name) if args.debug: for name, value in parser.items(section_name): print ' %s = %s' % (name, value) print # Exit due to exception exit(0) # Rest of normal flow would take place here try: handle = UcsHandle(UCSM, USER, PASS) # Login to UCSM handle.login() # If successful, print some details print("Login was successful") print("=" * 50) print("UCS Cookie: " + handle.cookie) print("UCS IP: " + handle.ip) print("UCS Name: " + handle.ucs) print("UCS Version: " + str(handle.version)) print("=" * 50) print("Compute Blade Output") mo_list = handle.query_classid("ComputeBlade") for blade in mo_list: print blade.serial, blade.rn, blade.oper_state, blade.oper_power, blade.server_id, blade.availability, blade.name print("=" * 50) print("Associated blades only") filter_exp = '(oper_state,"ok")' mo_list = handle.query_classid("ComputeBlade", filter_str=filter_exp) for blade in mo_list: print blade.serial print("=" * 50) print("Specific Serial Prefix Search") filter_exp = '(serial,"^QCI\d{4}", type="re")' mo_list = handle.query_classid("ComputeBlade", filter_str=filter_exp) for blade in mo_list: print blade.serial print("=" * 50) print("Rack Unit Output") mo_list = handle.query_classid("ComputeRackUnit") for blade in mo_list: print blade.serial, blade.rn, blade.oper_state, blade.oper_power, blade.server_id, blade.availability, blade.name print("=" * 50) except: handle.logout() print("Exception occurred") raise finally: handle.logout()
# # Here the environment variable is called 'MY_SECURE_PASSWORD' which # contains your secret password. username = '******' # UCS Manager username password = '******' # UCS Manager password # Create a connection handle # You can reserve the Cisco DEVNET UCS sanbox and use it # for the following example. handle = UcsHandle("10.10.20.113", username, password) # Login to the server handle.login() # Query the class FabricLanCloud which contains VLANs info fabric_lan_cloud = handle.query_classid("FabricLanCloud") # Create the VLAN 123 # 'id' and 'name' are mandatory arguments vlan123 = FabricVlan(parent_mo_or_dn=fabric_lan_cloud[0], name="vlan123", id="123") # Add the VLAN 123 object to the object handle using the add_mo method. handle.add_mo(vlan123) # Commit the change to add the VLAN 123 to the UCS Manager handle.commit() # Logout from the server handle.logout()
Github: https://github.com/Ganapathe/UCS Email: [email protected] Script to assign user label to all the blades in UCSM. """ #Import Modules from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.ucsmo import ManagedObject from ucsmsdk.ucscoremeta import MoPropertyMeta, MoMeta from ucsmsdk.ucsmeta import VersionMeta #Login to UCSM handle1 = UcsHandle("ucsm-ip-adddress","ucs-domain_name\account","password") handle1.login() #Collecting the Blade informations blades_inv = handle1.query_classid("computeBlade") #Get user defined user labels and store as text file in temp folder with open(r"C:\TEMP\test2.txt") as file: data = file.read() lines = data.split("\n") #Assigning a user label i = 0 if i < len(lines): for blade_inv in blades_inv: blade_inv.usr_lbl = lines[i] i += 1 handle1.set_mo(blade_inv) print(blade_inv.usr_lbl,blade_inv.name,blade_inv.chassis_id,blade_inv.rn,blade_inv.assigned_to_dn) #Commit changes handle1.commit()
#!/usr/bin/env python # Examples from Cisco Live Preso # https://www.ciscolive.com/c/dam/r/ciscolive/us/docs/2020/pdf/DGTL-BRKPRG-2432.pdf ''' Example 1 ''' # Create a Login HANDLE and Login from ucsmsdk.ucshandle import UcsHandle HANDLE = UcsHandle("172.16.125.2", "ucspe", "ucspe" ) HANDLE.login() # Print HANDLE 'cookie' attribute print(f"\ncookie: {HANDLE.cookie}") # Query Compute blades and print number of object returned # Queries are executed with a HANDLE member method BLADES = HANDLE.query_classid('ComputeBlade') print(f"\nNumber of blades found: {len(BLADES)}\n") # Iterate of blade list displaying attributes from each object for blade in BLADES: print(blade.dn, blade.serial, blade.model) # Turn on UCS XML API view to dump XML that is sent and received # HANDLE.set_dump_xml() # BLADES = HANDLE.query_classid("ComputeBlade") # HANDLE.unset_dump_xml() # Logout HANDLE.logout()
#! /usr/bin/env python from ucsmsdk.ucshandle import UcsHandle # Define handle's params; UCSM IP address, username, password myHandle = UcsHandle("10.1.100.101", "devnetuser", "Cisco123!") # Initiate connection myHandle.login() # Retrieve all the compute blades myBlades = myHandle.query_classid("ComputeBlade") # Table-formatted print print("{0:23s}{1:8s}{2:12s}{3:14s}{4:6s}".format( "Distinguished Name", "Serial", "Admin State", "Model", "Total Memory" )) print("-"*70) # Extract DN, serial number, admin state, model, total memory # for each blade for Blade in myBlades: print("{0:23s}{1:8s}{2:12s}{3:14s}{4:6s}".format( Blade.dn, Blade.serial, Blade.admin_state, Blade.model, Blade.total_memory
mac_pool_default = handle.query_dn("org-root/mac-pool-default") mo_mac_pool_block = MacpoolBlock(parent_mo_or_dn=mac_pool_default,r_from="00:25:B5:00:00:AA",to="00:25:B5:00:00:D9") handle.add_mo(mo_mac_pool_block, modify_present=True) handle.commit() # Create a Service Profile Template and associate to a Server Pool from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.ls.LsRequirement import LsRequirement mo_sp_template = LsServer(parent_mo_or_dn="org-root", type="initial-template", name="CommanderCode_PY_Mission_Templ") handle.add_mo(mo_sp_template, modify_present=True) handle.commit() filter_exp = '(name,"CommanderCode_PY_Mission_Templ")' mo_sp_templ = handle.query_classid("lsServer",filter_str=filter_exp) mo_sp_templ_ls_requirement = LsRequirement(parent_mo_or_dn=mo_sp_templ[0].dn, name="Python_Heroes_Server_Pool") handle.add_mo(mo_sp_templ_ls_requirement, modify_present=True) # Instantiate a Service Profile from the Service Profile template mo_sp = LsServer(parent_mo_or_dn="org-root", src_templ_name="CommanderCode_PY_Mission_Templ", name="CommanderCode_PY_Mission_Server") handle.add_mo(mo_sp, modify_present=True) handle.commit() # Retrieve the Server Pool and view the Server Pool Server allocation filter_exp = '(name,"Python_Heroes_Server_Pool")' mo_compute_pool = handle.query_classid("ComputePool",filter_str=filter_exp) mo_compute_pooled_slots = handle.query_children(in_mo=mo_compute_pool[0], class_id="ComputePooledSlot") for mo_compute_pooled_slot in mo_compute_pooled_slots: print(mo_compute_pooled_slot.poolable_dn, mo_compute_pooled_slot.assigned_to_dn)
""" from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.compute.ComputePool import ComputePool from ucsmsdk.mometa.compute.ComputePooledSlot import ComputePooledSlot from ucsmsdk.mometa.ls.LsRequirement import LsRequirement HANDLE = UcsHandle("sandbox-ucsm1.cisco.com", "admin", "password") HANDLE.login() SERVER_POOL = ComputePool(parent_mo_or_dn="org-root/org-devnet", name="devcore_pool") HANDLE.add_mo(SERVER_POOL, modify_present=True) for blade in HANDLE.query_classid("computeBlade", filter_str='(chassis_id, "7")'): SERVER = ComputePooledSlot(parent_mo_or_dn=SERVER_POOL, chassis_id=blade.chassis_id, slot_id=blade.slot_id) HANDLE.add_mo(SERVER, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsRequirement( parent_mo_or_dn="org-root/org-devnet/ls-devcore_template", name="devcore_pool") HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit() HANDLE.logout()
## Mission: Programming Cisco Compute - Python Basic and Advanced ## Mission Exercise 2 - Solution # Get a handle and login to UCS Manager from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "password") handle.login() # Import Classes ComputePool and ComputePooledSlot from ucsmsdk.mometa.compute.ComputePool import ComputePool from ucsmsdk.mometa.compute.ComputePooledSlot import ComputePooledSlot # Create a ComputePool Object mo_pool = ComputePool(parent_mo_or_dn="org-root", name="Python_Heroes_Server_Pool") handle.add_mo(mo_pool, modify_present=True) handle.commit() # Retrieve the ComputePool object and add Servers filter_exp = '(name,"Python_Heroes_Server_Pool")' mo_compute_pool = handle.query_classid("computePool",filter_str=filter_exp) for slot_num in 1,2,3,4: mo_compute_pooled_slot = ComputePooledSlot(parent_mo_or_dn=mo_compute_pool[0].dn, chassis_id="2", slot_id=str(slot_num)) handle.add_mo(mo_compute_pooled_slot, modify_present=True) handle.commit() # Logout of the UCS Manager handle.logout()