def static_setup(): from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.ucscoremeta import UcsVersion global ref_handle global diff_handle ref_handle = UcsHandle("192.168.1.1", "admin", "password") diff_handle = UcsHandle("192.168.1.2", "admin", "password") ref_handle.__dict__['_UcsSession__version'] = UcsVersion("2.2(5a)") diff_handle.__dict__['_UcsSession__version'] = UcsVersion("2.2(2c)")
def run_module(): """ Run the module """ module = AnsibleModule(argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', default='admin'), password=dict(type='str', required=True, no_log=True), name=dict(type='str'), descr=dict(type='str'), state=dict( type='str', default='present', choices=['present', 'absent']))) from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.org.OrgOrg import OrgOrg handle = UcsHandle(module.params['hostname'], module.params['username'], module.params['password']) handle.login() ucs_mo = OrgOrg(parent_mo_or_dn='org-root', name=module.params['name'], descr=module.params['descr']) handle.add_mo(ucs_mo, modify_present=True) handle.commit() handle.logout() # TODO: Add delete object code result = dict(changed=True) module.exit_json(**result)
def ucsm_config_import(ucsm_ip, user, password): handle = UcsHandle(ucsm_ip, user, password) handle.login() import_ucs_backup(handle, file_dir=r"C:\py\config", file_name=ucsm_ip + "_" + "config-all.xml") handle.logout()
def login(self, username, password, server): # Test if the server reachable s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: result = s.connect_ex((server, 80)) if result != 0: return None, "{0} is not reachable".format(server) s.close() except socket.error as err: return None, "UCS Login Error: {0} {1}".format( server, err.strerror) handle = UcsHandle(server, username, password) try: handle.login() except UcsException as err: print "Login Error: " + err.error_descr return None, err.error_descr except HTTPError as err: print "Connection Error: Bad UCSM? " + err.reason return None, err.reason except Exception as e: print "Issue logging in. Please check that all parameters are correct" print e return None, "Issue logging in. Please check that all parameters are correct." msg = self.ensure_version(handle) return handle, msg
def systemGetAll(host=None, user=None, password=None): handle = UcsHandle(host, user, password, secure=False) if handle.login(): elements = [{ "ciscoXmlName": "EquipmentChassis", "humanReadableName": "Chassis" }, { "ciscoXmlName": "NetworkElement", "humanReadableName": "Fabric Interconnects" }, { "ciscoXmlName": "EquipmentFex", "humanReadableName": "FEX" }, { "ciscoXmlName": "computeRackUnit", "humanReadableName": "Servers" }] finalObjs = {} for x in elements: units = [] components = handle.query_children(in_dn="sys", class_id=x["ciscoXmlName"]) for y in components: subElement = {"relative_path": "/" + (vars(y))["dn"]} units.append(subElement) finalObjs[x["humanReadableName"]] = units handle.logout() return finalObjs
def vKVM_launcher_blade(ucsm_ip, user, password, chassis, blade): handle = UcsHandle(ucsm_ip, user, password) handle.login() mo = handle.query_dn("sys/chassis-{0}/blade-{1}".format(chassis, blade)) print mo ucs_kvm_launch(handle, blade=mo) handle.logout()
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 test_invalid_disk_state(add_mo_mock, commit_mock): add_mo_mock.return_value = True commit_mock.return_value = True handle = UcsHandle('169.254.1.1', 'admin', 'password') # Scenario invalid state assert_raises(ValueError, disk_state_set, handle, 16, 1, "blah")
def getRackmount(): authInfo = _getUcsAuthInfo((request.headers)) data = [] handle = UcsHandle(*authInfo, secure=False) if handle.login(): try: computeRackUnit = handle.query_children(in_dn="sys", class_id="computeRackUnit") except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: if (type(computeRackUnit) == list): for x in computeRackUnit: server = {} server["name"] = x.rn server["path"] = x.dn server["macs"] = [] try: macs = handle.query_children(in_dn=x.dn, class_id='PciEquipSlot') except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 for y in macs: server["macs"].append(y.mac_left) server["macs"].append(y.mac_right) data.append(server) handle.logout() return data else: handle.logout() return "Couldn't fetch computeRackUnits:", "", 500 else: handle.logout() return 'Forbidden', "", 403
def systemGetAll(): authInfo = _getUcsAuthInfo((request.headers)) handle = UcsHandle(*authInfo, secure=False) if handle.login(): elements = [{"ciscoXmlName": "EquipmentChassis", "humanReadableName": "Chassis"}, {"ciscoXmlName": "NetworkElement", "humanReadableName": "Fabric Interconnects"}, {"ciscoXmlName": "EquipmentFex", "humanReadableName": "FEX"}, {"ciscoXmlName": "computeRackUnit", "humanReadableName": "Servers"}] finalObjs = {} for x in elements: units = [] try: components = handle.query_children(in_dn="sys", class_id=x["ciscoXmlName"]) except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: if(type(components) == list): for y in components: subElement = {"relative_path": "/" + (vars(y))["dn"]} units.append(subElement) finalObjs[x["humanReadableName"]] = units else: handle.logout() return "Couldn't fetch " + x["ciscoXmlName"], "", 500 handle.logout() return finalObjs else: handle.logout() return 'Forbidden', "", 403
def test_valid_server_port_create(add_mo_mock, commit_mock): # Patch UcsHandle.add_mo to simulate CIMC interaction w/o real CIMC # Patch UcsHandle.commit to simulate CIMC interaction w/o real CIMC add_mo_mock.return_value = True commit_mock.return_value = True handle = UcsHandle('169.254.1.1', 'admin', 'password') # Scenario: Set Fabric-A port Eth1/10 to server port fabric_dn = 'fabric/lan/A' port_id = '10' slot_id = '1' server_port_create(handle, fabric_dn, port_id, slot_id) # Assert values of the object passed to add_mo() test_server_mo = add_mo_mock.call_args[0][0] assert test_server_mo.port_id == "10" assert test_server_mo.slot_id == "1" assert test_server_mo.dn == '{0}/slot-{1}-port-{2}'.format( fabric_dn, slot_id, port_id) # Scenario: Set Fabric-B port Eth2/6 to server port fabric_dn = 'fabric/lan/B' port_id = '6' slot_id = '2' server_port_create(handle, fabric_dn, port_id, slot_id) # Assert values of the object passed to add_mo() test_server_mo = add_mo_mock.call_args[0][0] assert test_server_mo.port_id == "6" assert test_server_mo.slot_id == "2" assert test_server_mo.dn == '{0}/slot-{1}-port-{2}'.format( fabric_dn, slot_id, port_id)
def login(self): from ucsmsdk.ucshandle import UcsHandle # use_proxy=yes (default) and proxy=None (default) should be using the system defined proxy # use_proxy=yes (default) and proxy=value should use the provided proxy # use_proxy=no (user) should not be using a proxy if self.module.params['use_proxy']: proxy = self.module.params['proxy'] else: # force no proxy to be used. Note that proxy=None in UcsHandle will # use the system proxy so we must set to something else proxy = {} try: handle = UcsHandle(ip=self.module.params['hostname'], username=self.module.params['username'], password=self.module.params['password'], port=self.module.params['port'], secure=self.module.params['use_ssl'], proxy=proxy) handle.login() except Exception as e: self.result['msg'] = str(e) self.module.fail_json(**self.result) self.login_handle = handle
def ucsmUpload(): #while(True): time.sleep(90) os.system(r'echo "Starting UCSM Config Upload Script..." >> /root/logs/importUcsmBackupA.log') try: os.system(r'echo "Will Connect to UCSM now..." >> /root/logs/importUcsmBackupA.log') handle=UcsHandle("198.18.134.220","admin","C1sco12345",secure=False) handle.login() os.system(r'echo "Connected to UCSM, will push config now..." >> /root/logs/importUcsmBackupA.log') import_ucs_backup(handle, file_dir=file_dir, file_name=file_name, merge=True) os.system(r'echo "Configuration uploaded. Disconnecting..." >> /root/logs/importUcsmBackupA.log') handle.logout() os.system(r' echo "Done" > /root/logs/ucsmA.status') os.system(r'echo "Done" >> /root/logs/importUcsmBackupA.log') return True except Exception as e: if ("HTTP Error 503" in str(e)): errorMessage=str(e) os.system(r'echo "Error while pushing the config to UCS.Will restart the services and try again in 90 sec." >> /root/logs/importUcsmBackupA.log') os.system(r' echo ' + errorMessage + ' >> /root/logs/importUcsmBackupA.log') os.system(r' curl --data "Submit=Restart UCS Emulator with Current Settings&confirm=yes" http://198.18.134.220:8082/settings/restart/emulator >> /root/logs/importUcsmBackupA.log') return 60 else: errorMessage=str(e) os.system(r'echo "Error while connecting to UCSM .Will try to connect again in 90 sec." >> /root/logs/importUcsmBackupA.log') #os.system(r' echo ' + errorMessage + ' >> /root/logs/importUcsmBackupA.log') return 5
def test_invalid_server_pool_add_rack_unit(query_mock, add_mo_mock, commit_mock): add_mo_mock.return_value = True commit_mock.return_value = True handle = UcsHandle('169.254.1.1', 'admin', 'password') # Scenario: Invalid Org query_mock.return_value = None # Verify exception was raised for invalid org assert_raises( ValueError, server_pool_add_rack_unit, handle, 16, ) # Scenario: Org is not a ComputePool query_mock.return_value = OrgOrg(parent_mo_or_dn="org-root", name="root") # Verify exception was raised for invalid type assert_raises( TypeError, server_pool_add_rack_unit, handle, 16, )
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 login(username, password, server): # first see if reachable s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: result = s.connect_ex((server, 80)) if result != 0: return "", "%s is not reachable" % server s.close() except socket.error as err: return "", "UCS Login Error: %s %s" % (server, err.strerror) handle = UcsHandle(server, username, password) try: handle.login() except UcsException as err: print "Login Error: " + err.error_descr return "", err.error_descr except HTTPError as err: print "Connection Error: Bad UCSM? " + err.reason return "", err.reason except: print "Issue logging in. Please check that all parameters are correct" return "", "Issue logging in. Please check that all parameters are correct." return handle, ""
def _getHandler(headers, handlers): authInfo = Ucs._getUcsAuthInfo(headers) host, user, password = authInfo timestamp = time.time() handle_obj = handlers.get(host, None) ucs_handle = handle_obj and handle_obj.get('ucs-handle', None) is_auth_valid = ucs_handle \ and handle_obj.get('ucs-user') == user \ and handle_obj.get('ucs-password') == password \ and (timestamp - handle_obj['timestamp']) < SESSION_DURATION if is_auth_valid: handle_obj['timestamp'] = timestamp else: if ucs_handle: # logout existing handler if it is invalid ucs_handle.logout() ucs_handle = UcsHandle(*authInfo, secure=False) if ucs_handle.login(): ucs_handle_obj = { 'ucs-user': user, 'ucs-password': password, 'ucs-host': host, 'ucs-handle': ucs_handle, 'timestamp': timestamp } handlers[host] = ucs_handle_obj else: ucs_handle.logout() return None return ucs_handle
def ucsm_config_backup(ucsm_ip, user, password): handle = UcsHandle(ucsm_ip, user, password) handle.login() backup_ucs(handle, backup_type="config-all", file_dir=r"C:\py\config", file_name=ucsm_ip + "_" + "config-all.xml") handle.logout()
def get_vnic_mac_from_sp(ipaddr, user, pword, sp_name, vnic_name): """get mac of vnic from service profile.""" handle = UcsHandle(ipaddr, user, pword) handle.login() macs = sp_macaddress(handle, sp_name) handle.logout() my_output = macs[vnic_name] return my_output
def test_invalid_ipmi_policy_create(query_mock, add_mo_mock, commit_mock): add_mo_mock.return_value = True commit_mock.return_value = True handle = UcsHandle('169.254.1.1', 'admin', 'password') # Scenario: Invalid Org query_mock.return_value = None # Verify exception was raised for invalid org assert_raises(ValueError, ipmi_policy_create, handle, 'invalid')
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 fullGetTechSupport(ucsm_ip, user, password): print "블레이드 샤시 로그를 수집합니다" print "해당 수집 작업은 5분에서 20분 정도 소요될 예정입니다." handle = UcsHandle(ucsm_ip, user, password) handle.login() get_ucs_tech_support(handle, file_dir="/root/techsupport", file_name=s + 'FI_UCSM.tar', timeout_in_sec=600, remove_from_ucs=True) handle.logout()
def getChassis(): authInfo = _getUcsAuthInfo((request.headers)) data = [] handle = UcsHandle(*authInfo, secure=False) if handle.login(): try: elememts = handle.query_children(in_dn="sys", class_id="EquipmentChassis") except UcsException as e: return 'Internal Server Error', e.error_descr, 500 else: if (type(elememts) == list): for element in elememts: chassis = {} identifier = element.dn obj = handle.query_dn(dn=identifier) chassis["name"] = obj.rn chassis["path"] = obj.dn chassis["members"] = [] try: blades = handle.query_children(in_dn=identifier, class_id='ComputeBlade') except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: if (type(blades) == list): for x in blades: server = {} server["name"] = x.rn server["path"] = x.dn server["macs"] = [] try: adptares = handle.query_children( in_dn=x.dn, class_id='AdaptorUnit') except UcsException as e: handle.logout() return 'Internal Server Error', e.error_descr, 500 else: for x in adptares: server["macs"].append(x.base_mac) chassis["members"].append(server) data.append(chassis) else: handle.logout() return "Couldn't fetch ComputeBlade", "", 500 else: handle.logout() return "Couldn't fetch EquipmentChassis", "", 500 else: handle.logout() return 'Forbidden', "", 403 handle.logout() return data
def getCatalog(host=None, user=None, password=None, identifier=None): handle = UcsHandle(host, user, password, secure=False) if handle.login(): element = handle.query_dn(dn=identifier) catalog = element.__dict__ for property in catalog.keys(): if (property[0] == "_"): del catalog[property] handle.logout() return catalog
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 test_valid_server_pool_create(query_mock, add_mo_mock, commit_mock): query_mock.return_value = OrgOrg(parent_mo_or_dn="org-root", name="root") add_mo_mock.return_value = True commit_mock.return_value = True handle = UcsHandle('169.254.1.1', 'admin', 'password') # Scenario: Default parameters pool_retval = server_pool_create(handle, 'valid-pool') # Verify we were passed back the correct object type assert isinstance(pool_retval, ComputePool) # Verify the name we gave it was assigned correctly assert pool_retval.name == "valid-pool"
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 ucs_login(self,ip,username,password): results = {} handle = UcsHandle(ip, username, password) try: handle.login() #mo = handle.query_dn("org-root/boot-policy-ciscotest") #print(mo) results['logged_in'] = True #print("Logged In !!!!") except: results['logged_in'] = False return handle
def proess_tech_support(): """ Create and download a UCS Tech Support """ handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() get_tech_support(handle=handle, option="ucsm-mgmt", file_dir='.', file_name="ucsm.tar", timeout=1800) handle.logout()
def authenticate_to_ucs_domain(): global handle handle = UcsHandle(ucs_name, login_name, password) try: print('\n*** Logging in') handle.login() print('*** Successfully Logged in \n') except: print( '*** ERROR - UNABLE TO LOGIN. CHECK CREDENTIALS AND TRY AGAIN.\n\n\n' ) exit()