예제 #1
0
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()
예제 #2
0
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
예제 #3
0
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
예제 #4
0
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()
예제 #5
0
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)
예제 #6
0
 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
예제 #7
0
class UCSMController:
    def __init__(self):
        self.handle = UcsHandle(ip=IP, username=USERNAME, password=PASSWORD)
        if not self.handle.login():
            raise Exception("No valid UCS Manager credentials")

    def GetHandle(self):
        return self.handle

    def GetInterfaceProfiles(self):
        handle = self.GetHandle()
        return handle.query_classid("vnicLanConnTempl")

    def GetBIOSProfiles(self):
        handle = self.GetHandle()
        return handle.query_classid("biosVProfile")

    def GetSvcProfiles(self):
        handle = self.GetHandle()
        return handle.query_classid("lsServer")

    def GetByDN(self, dn, hierarchy=True):
        handle = self.GetHandle()
        return handle.query_dn(dn, hierarchy=hierarchy)

    def Logout(self):
        self.handle.logout()
예제 #8
0
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()
예제 #9
0
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
예제 #10
0
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()
예제 #11
0
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
예제 #12
0
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()
예제 #13
0
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
class UCS(object):
    def __init__(self, ucsm_ip="", ucsm_login="", ucsm_pw=""):
        self.handle = UcsHandle(ucsm_ip, ucsm_login ,ucsm_pw)
        self.ucsm_ip = ucsm_ip
        self.ucsm_pw = ucsm_pw
        self.ucsm_login = ucsm_login

    def login(self):
        self.handle.login()

    def logout(self):
        self.handle.logout()
예제 #15
0
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))
예제 #16
0
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()
예제 #17
0
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
예제 #18
0
def main():
    handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False)
    handle.login()

    # Query for existing vlan
    vlan_100 = handle.query_dn("fabric/lan/net-vlan100")

    # Setup handle entry to remove vlan
    handle.remove_mo(vlan_100)

    # Commit changes back to UCS
    handle.commit()

    handle.logout()
예제 #19
0
def backup_ucsm():
    # Create a connection handle
    handle = UcsHandle("r143b-ucs.rich.ciscolabs.com", "admin", "N3ptune1")

    # Login to the server
    handle.login()

    backup_ucs(handle,
               backup_type="config-logical",
               file_dir=backup_dir,
               file_name=backup_filename)

    # Logout from the server
    handle.logout()
예제 #20
0
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
예제 #21
0
def singleGetTechSupport(ucsm_ip, user, password, chassis, blade):
    print chassis + '-' + blade + "블레이드 로그를 수집합니다."
    print "해당 수집 작업은 5분에서 20분 정도 소요될 예정입니다."
    handle = UcsHandle(ucsm_ip, user, password)
    handle.login()
    get_ucs_tech_support(handle,
                         file_dir="/root/techsupport",
                         file_name=s + 'FI_BL' + chassis + '-' + blade +
                         '.tar',
                         chassis_id=chassis,
                         cimc_id=blade,
                         timeout_in_sec=600,
                         remove_from_ucs=True)
    handle.logout()
예제 #22
0
def process_request(event):
    """ Process the UCS Request """

    handle = UcsHandle(
        event['auth']['hostname'],
        event['auth']['username'],
        event['auth']['password'])
    handle.login()

    if event['action']['method'] == 'query_classid':
        RETURN_DICT['response'] = query_classid(handle, event['action']['class_id'])
    elif event['action']['method'] == 'configure':
        RETURN_DICT['response'] = configure_mos(handle, event['action'])

    handle.logout()
예제 #23
0
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()
예제 #24
0
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()
예제 #25
0
def main():
    handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False)
    handle.login()
    print(" ==== Printing Off Handle ==== ")
    pprint.pprint(vars(handle))
    print(" ==== Printed Off Handle ==== ")

    ## Print IP address of UCSM
    print(handle.ip)

    ## Print UCS Name
    print(handle.ucs)

    ## Print Cookie
    print(handle.cookie)

    handle.logout()
예제 #26
0
def getRackmount(host=None, user=None, password=None):
    data = []
    handle = UcsHandle(host, user, password, secure=False)
    if handle.login():
        computeRackUnit = handle.query_children(in_dn="sys",
                                                class_id="computeRackUnit")
        for x in computeRackUnit:
            server = {}
            server["name"] = x.rn
            server["path"] = x.dn
            server["macs"] = []
            macs = handle.query_children(in_dn=x.dn, class_id='PciEquipSlot')
            for y in macs:
                server["macs"].append(y.mac_left)
                server["macs"].append(y.mac_right)
            data.append(server)
            handle.logout()
        return data
예제 #27
0
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()
def main(args):
    """main function"""

    if args.id:
        username = args.id

    if args.port:
        port = args.port
    else:
        port = 443

    if args.secure:
        secure = True
    else:
        secure = False

    handle = UcsHandle(args.ucs,
                       username=args.id,
                       password=getpass.getpass(prompt="UCSM Password: "******"", CONST_HTTPD_PORT), handler)

        print "point browser to http://localhost:{0}".format(CONST_HTTPD_PORT)
        httpd.serve_forever()
예제 #29
0
def main():
    handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False)
    handle.login()

    # Query for existing vlan
    vlan_100 = handle.query_dn("fabric/lan/net-vlan100")
    print(vlan_100.dn, vlan_100.sharing)

    # Update sharing type to primary
    vlan_100.sharing = "primary"

    # Add the object to be ready to be committed
    handle.set_mo(vlan_100)

    # Commit changes back to UCS
    handle.commit()

    # Get Updated vlan
    vlan_100 = handle.query_dn("fabric/lan/net-vlan100")
    print(vlan_100.dn, vlan_100.sharing)

    handle.logout()
예제 #30
0
def main():
    handle = UcsHandle("192.168.254.200","ucspe","ucspe", secure=False)
    handle.login()

    ## Acknolwedge Chassis
    mo = EquipmentChassis(parent_mo_or_dn="sys", admin_state="re-acknowledge", id="5")
    handle.add_mo(mo, True)
    handle.commit()

    ## Update MAC Pool
    mo = MacpoolBlock(parent_mo_or_dn="org-root/mac-pool-default", r_from="00:25:B5:00:00:00", to="00:25:B5:00:00:C7")
    handle.add_mo(mo)
    handle.commit()

    ## Update UUID Pools
    handle.query_dn("org-root/uuid-pool-default")
    mo = UuidpoolBlock(parent_mo_or_dn="org-root/uuid-pool-default", r_from="0000-000000000001", to="0000-0000000000C8")
    handle.add_mo(mo)
    handle.commit()

    ## Setup Fabric Ethernet Uplink A Side
    mo = FabricEthLan(parent_mo_or_dn="fabric/lan", id="A")
    mo_1 = FabricEthLanEp(parent_mo_or_dn=mo, admin_speed="10gbps", admin_state="enabled", auto_negotiate="yes", eth_link_profile_name="default", fec="auto", flow_ctrl_policy="default", name="", port_id="1", slot_id="1", usr_lbl="")
    handle.add_mo(mo, True)
    handle.commit()

    ## Setup Fabric Ethernet Uplink A Side
    mo = FabricEthLan(parent_mo_or_dn="fabric/lan", id="B")
    mo_1 = FabricEthLanEp(parent_mo_or_dn=mo, admin_speed="10gbps", admin_state="enabled", auto_negotiate="yes", eth_link_profile_name="default", fec="auto", flow_ctrl_policy="default", name="", port_id="1", slot_id="1", usr_lbl="")
    handle.add_mo(mo, True)
    handle.commit()

    ## Setup Service Profile Template
    mo = LsServer(parent_mo_or_dn="org-root", ident_pool_name="default", name="globotemplate", type="initial-template", uuid="00000000-0000-0000-0000-000000000000")
    handle.add_mo(mo)
    handle.commit()

    handle.logout()
from ucsmsdk.ucshandle import UcsHandle

# Create a connection handle
handle = UcsHandle("172.xx.xx.xx", "admin", "cisco!098")

# Put in the VLANs you want to remove first one, and then the last one.
vlan_start = 400
vlan_end = 499
vlan_name_prefix = "vmware_client_"

# Login to the server
handle.login()


for a in range(vlan_start, vlan_end + 1):
    mydn = vlan_name_prefix + str(a)
    print "Removing " + (mydn)
    myfulldn = "fabric/lan/net-" + mydn

    # Query for an existing Mo
    sp = handle.query_dn(myfulldn)

    # Remove the object
    handle.remove_mo(sp)
    # and commit the changes (actually happens now)
    handle.commit()


# Logout from the server
handle.logout()