Example #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()
Example #2
0
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, ""
Example #3
0
    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
Example #4
0
    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
Example #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)
Example #6
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()
Example #7
0
    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
Example #8
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
Example #9
0
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 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()
Example #11
0
    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
Example #12
0
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)")
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()
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--ip", help="IP Address")
    parser.add_argument("-u", "--username", help="Username")
    parser.add_argument("-p", "--password", help="Password")

    args = parser.parse_args()

    #Log into UCS using UcsHandle
    handle = UcsHandle(ip=args.ip,
                       username=args.username,
                       password=args.password)
    handle.login()
Example #15
0
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()
Example #16
0
def login(username, password, server):
    handle = UcsHandle(server, username, password)
    try:
        handle.login()
    except UcsException as err:
        print "Login Error: " + err.error_descr
        return ""
    except HTTPError as err:
        print "Connection Error: Bad UCSM? " + err.reason
        return ""
    except:
        print "Issue logging in.  Please check that all parameters are correct"
        return ""
    return handle
Example #17
0
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()
Example #18
0
def ucsm_login():
    try:
        print "Testing for ping response...."
        response = subprocess.check_output(
            ['ping', '-c', '3', ucsm_ip],
            stderr=subprocess.STDOUT,  # get all output
            universal_newlines=True  # return string not bytes
        )
        handle = UcsHandle(ucsm_ip, ucsm_username, ucsm_password)
        handle.login()
        return handle
    except:
        response = None
        print "Unable to ping IP address provided. Exiting...."
        exit()
Example #19
0
def custom_setup():
    import ConfigParser
    import os
    from ucsmsdk.ucshandle import UcsHandle

    config = ConfigParser.RawConfigParser()
    config.read(os.path.join(os.path.dirname(__file__), '..', 'connection',
                             'connection.cfg'))

    hostname = config.get(host, "hostname")
    username = config.get(host, "username")
    password = config.get(host, "password")
    handle = UcsHandle(hostname, username, password, port=80)
    handle.login()
    return handle
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()
Example #22
0
def main():
    handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False)
    handle.login()

    # Create XML Object to create template clone
    templates = ls_instantiate_n_template(cookie=handle.cookie,
                                          dn="org-root/ls-globotemplate",
                                          in_target_org="org-root",
                                          in_server_name_prefix_or_empty="SP",
                                          in_number_of=str(NUM_SP),
                                          in_hierarchical="no")
    # Send XML Object to xml process handler
    mo_list = handle.process_xml_elem(templates)

    for mo in mo_list:
        print(mo.dn)
Example #23
0
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")
Example #24
0
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,
    )
Example #25
0
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)
Example #26
0
 def loginTest():
     global handle
     handle = UcsHandle(ip_address, user_name, pass_word)
     try:
         if handle.login() == True:
             puts(
                 colored.cyan(
                     '#####################################################\nUCS Manager Login Successful to '
                     + ip_address +
                     '\n#####################################################\n\n\n\n'
                 ))
         launchQuery()
     except urllib2.URLError:
         puts(
             colored.red('LOGIN FAILED: Bad IP Address. Please Try Again.'))
         print('\n\n\n')
         ipAddress()
Example #27
0
def modify_UCS_VNIC(vl_range):
    handle = UcsHandle(credentials.UCS_login['ipaddr'],
                       credentials.UCS_login['username'],
                       credentials.UCS_login['password'])
    handle.login()
    for vlan_id in vl_range:
        mo = VnicLanConnTempl(parent_mo_or_dn="org-root", name="ACI-A")
        mo_vnic_a = VnicEtherIf(parent_mo_or_dn=mo,
                                default_net="no",
                                name="ACI-" + vlan_id)
        handle.set_mo(mo)
        mo = VnicLanConnTempl(parent_mo_or_dn="org-root", name="ACI-B")
        mo_vnic_b = VnicEtherIf(parent_mo_or_dn=mo,
                                default_net="no",
                                name="ACI-" + vlan_id)
        handle.set_mo(mo)
        handle.commit()
Example #28
0
def ucs_login():
    import ConfigParser
    import os
    from ucsmsdk.ucshandle import UcsHandle

    config = ConfigParser.RawConfigParser()
    config.read(
        os.path.join(os.path.dirname(__file__), '..', 'connection',
                     'connection.cfg'))

    hostname = config.get(host, "hostname")
    username = config.get(host, "username")
    password = config.get(host, "password")
    port = config.get(host, "port")
    handle = UcsHandle(hostname, username, password, port)
    handle.login()
    return handle
Example #29
0
def custom_setup():
    import os
    from ucsmsdk.ucshandle import UcsHandle

    config = configparser.RawConfigParser()
    config.read(
        os.path.join(os.path.dirname(__file__), '..', 'connection',
                     'connection.cfg'))
    try:
        hostname = config.get(host, "hostname")
        username = config.get(host, "username")
        password = config.get(host, "password")
    except:
        return None
    handle = UcsHandle(hostname, username, password)
    handle.login(auto_refresh=True, force=True)
    return handle
Example #30
0
    def set_up(self):
        # get arguments
        self.args = self.get_args()

        # set log level
        self.set_log_level(self.args.log_level)

        self.host = self.args.ucs
        if self.args.secure == True:
            self.url = 'https://%s/nuova' % self.args.ucs
        else:
            self.url = 'http://%s/nuova' % self.args.ucs
        self.user = self.args.user
        self.passwd = self.args.password

        self.token = self.args.token
        self.zeus_server = self.args.zeus

        # set up a Zeus client to submit log to Zeus.
        self.logger.info("Initiating Zeus connection...")
        self.zeus_client = client.ZeusClient(self.token, self.zeus_server)

        # set up a http client to UCS server.
        self.logger.info("Initiating UCSM connection...")
        self.handler = UcsHandle(self.host,
                                 self.user,
                                 self.passwd,
                                 port=self.args.port,
                                 secure=self.args.secure)
        # login to ucs
        self.handler.login(auto_refresh=True)
        self.add_log("DEBUG",
                     "ucs",
                     msg={
                         "User": self.user,
                         "Password": self.passwd,
                         "cookie": self.handler.cookie
                     })
        self.logger.info("Login UCSM completed.")

        self.logger.info("Getting configuration data...")
        self.get_dn_conf()

        self.logger.info("Listening to UCSM events...")
        self.event_loop()
Example #31
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()
Example #32
0
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')
Example #33
0
def test_serialize_handle():
    handle1 = custom_setup()
    if not handle1:
        msg = get_skip_msg()
        raise SkipTest(msg)

    frozen_handle = handle1.freeze()
    handle2 = UcsHandle.unfreeze(frozen_handle)
    custom_teardown(handle2)
Example #34
0
def custom_setup():
    try:
        import ConfigParser
    except:
        import configparser as ConfigParser

    import os
    from ucsmsdk.ucshandle import UcsHandle

    config = ConfigParser.RawConfigParser()
    config.read(os.path.join(os.path.dirname(__file__), '..', 'connection',
                             'connection.cfg'))

    hostname = config.get(host, "hostname")
    username = config.get(host, "username")
    password = config.get(host, "password")
    handle = UcsHandle(hostname, username, password)
    handle.login(auto_refresh=True, force=True)
    return handle
Example #35
0
def test_001_create_uri():
    # Create an object of type LsServer with parent dn specified
    # check if the object has the right values populated
    handle = UcsHandle("192.168.1.1", "admin", "password")

    assert_equal(
        handle._UcsSession__create_uri(
            port=None,
            secure=None),
        'https://192.168.1.1:443')

    assert_equal(
        handle._UcsSession__create_uri(
            port=8080,
            secure=None),
        'https://192.168.1.1:8080')

    assert_equal(
        handle._UcsSession__create_uri(
            port=None,
            secure=True),
        'https://192.168.1.1:443')

    assert_equal(
        handle._UcsSession__create_uri(
            port=None,
            secure=False),
        'http://192.168.1.1:80')

    assert_equal(
        handle._UcsSession__create_uri(
            port=444,
            secure=False),
        'http://192.168.1.1:444')
Example #36
0
def test_ucs_backup_after_freeze_unfreeze():
    # for this test to be more meaningful there needs to be proxy server
    # configured
    h1 = custom_setup()
    frozen_handle = h1.freeze()
    h2 = UcsHandle.unfreeze(frozen_handle)

    # Try a download operation using new handle
    _test_ucs_backup(file_dir="/tmp/backup",
                     file_name="config2.xml",
                     backup_type="config-logical")

    custom_teardown(h2)
Example #37
0
from ucsmsdk.mometa.org.OrgOrg import OrgOrg
from ucsmsdk.mometa.uuidpool.UuidpoolPool import UuidpoolPool
from ucsmsdk.mometa.uuidpool.UuidpoolBlock import UuidpoolBlock
from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan
from ucsmsdk.mometa.compute.ComputePool import ComputePool
from ucsmsdk.mometa.compute.ComputePooledSlot import ComputePooledSlot
from ucsmsdk.mometa.lsmaint.LsmaintMaintPolicy import LsmaintMaintPolicy

my_Org = "Test_Org"
my_Full_Path_Org = "org-root/org-%s" % my_Org
my_UUID_Pool = "%s/uuid-pool-UUID_POOL" % my_Full_Path_Org
my_Server_Pool = "%s/compute-pool-Server_Pool" % my_Full_Path_Org
my_Maint_Pol = "%s/maint-Usr_Ack" % my_Full_Path_Org
my_Power_Pol = "%s/power-policy-No_Cap" % my_Full_Path_Org
#create the handle
handle = UcsHandle("192.168.67.148","admin","password",secure=False)
#login into UCS manager
handle.login()

#Remove Sub Organization
mo = handle.query_dn(my_Full_Path_Org)
handle.remove_mo(mo)
handle.commit()

#Unconfigure Ports
#PC-50
mo = handle.query_dn("fabric/lan/A/pc-50")
handle.remove_mo(mo)
handle.commit()
#PC-51
mo = handle.query_dn("fabric/lan/B/pc-51")
Example #38
0
from ucsmsdk.mometa.ls.LsVConAssign import LsVConAssign
from ucsmsdk.mometa.vnic.VnicEther import VnicEther
from ucsmsdk.mometa.vnic.VnicFc import VnicFc
from ucsmsdk.mometa.vnic.VnicFcIf import VnicFcIf
from ucsmsdk.mometa.vnic.VnicFcNode import VnicFcNode
from ucsmsdk.mometa.ls.LsRequirement import LsRequirement
from ucsmsdk.mometa.ls.LsPower import LsPower
from ucsmsdk.mometa.fabric.FabricVCon import FabricVCon

#Are we having iSCSI to the Hosts?
iSCSI = True
#Are we having FC to the hosts?
FC = False

#Create the handle
handle = UcsHandle("10.242.100.90","admin","password",secure=False)
#login into UCS manager
handle.login()

#reading variables from the ucs workbook
my_file=open("/Users/javirodz/Documents/ucs-book.csv", "r")
my_csv_file = csv.reader(my_file)
for row in my_csv_file:
    if row[0] == "Organization Name":
        my_Org = row[1]
        my_Full_Path_Org = "org-root/org-%s" % my_Org
    elif row[0] == "KVM Starting IP Address":
        my_kvm_pool_first = row[1]
    elif row[0] == "KVM Primary DNS IP Address":
        my_Primary_DNS = row[1]
    elif row[0] == "KVM Secondary DNS IP Address":
#!/usr/bin/env python

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
Example #40
0
    '--hostname',
    help="hostname/ip of the server",
    required=True)
parser.add_argument('--username', help="username", required=True)
parser.add_argument('--password', help="password", required=True)
args = parser.parse_args()
host, user, password = args.hostname, args.username, args.password


try:
    input = raw_input
except NameError:
    pass

try:
    handle = UcsHandle(host, user, password)
    handle.login()

    ucs_gui_launch(handle)

    time.sleep(5)
    print("================================================")
    print("Hit an Enter here AFTER the Java UI is up and running...")
    print("================================================")
    wait = input()
    convert_to_ucs_python()

except:
    handle.logout()
    raise
# This is the file that I use to connect to UCS and then run the converttopython part of the UCSMSDK
import xlrd

file_location = "./UCS.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(1)

from ucsmsdk.utils.ucsguilaunch import ucs_gui_launch
from ucsmsdk.ucshandle import UcsHandle

#login to the server
handle = UcsHandle( (sheet.cell_value(3,1)),(sheet.cell_value(4,1)),(sheet.cell_value(5,1)))
handle.login()

#launch the UCSM GUI
ucs_gui_launch(handle)

#convert_to_ucs portion

from ucsmsdk.utils.converttopython import convert_to_ucs_python

convert_to_ucs_python()
Example #42
0
import xlrd

import ucsmsdk


file_location = "./UCS.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(1)

# Create Session
#


from ucsmsdk.ucshandle import UcsHandle

handle = UcsHandle( (sheet.cell_value(3,1)),(sheet.cell_value(4,1)),(sheet.cell_value(5,1)))

handle.login()

mo = handle.query_dn("org-root")
print (mo)

# Compute Chassis Link Aggregation Policy

from ucsmsdk.mometa.compute.ComputeChassisDiscPolicy import ComputeChassisDiscPolicy

mo = ComputeChassisDiscPolicy(parent_mo_or_dn="org-root", rebalance="user-acknowledged", descr="",
                              action=(sheet.cell.value(8.1)), name="", policy_owner="local", link_aggregation_pref="none")
handle.add_mo(mo, True)

handle.commit()
Example #43
0
def test_serialize_handle():
    handle1 = custom_setup()
    frozen_handle = handle1.freeze()
    handle2 = UcsHandle.unfreeze(frozen_handle)
    custom_teardown(handle2)
def ucs_login(hostname, username, password):
    from ucsmsdk.ucshandle import UcsHandle

    handle = UcsHandle(hostname, username, password)
    handle.login()
    return handle