def get_configuration(server, username, password, skipVerification): session = get_unverified_session() if skipVerification else None if not session: session = requests.Session() host_url = "https://{}/api".format(server) sec_ctx = create_user_password_security_context(username, password) session_svc = Session( StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ]))) session_id = session_svc.create() print("Session ID : ", session_id) sec_ctx = create_session_security_context(session_id) stub_config = StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ])) return stub_config
def execute(self): logger.info('vapi_url: {0}'.format(self.vapi_url)) # parse the URL and determine the scheme o = urlparse(self.vapi_url) assert o.scheme is not None if o.scheme.lower() != 'https': logger.error('VAPI URL must be a https URL') raise Exception('VAPI URL must be a https URL') logger.info('sts_url: {0}'.format(self.sts_url)) logger.info('Initialize SsoAuthenticator and fetching SAML bearer token...') authenticator = sso.SsoAuthenticator(self.sts_url) bearer_token = authenticator.get_bearer_saml_assertion(self.sso_username, self.sso_password, delegatable=True) logger.info('Creating SAML Bearer Security Context...') sec_ctx = create_saml_bearer_security_context(bearer_token) logger.info('Connecting to VAPI provider and preparing stub configuration...') connector = connect.get_connector('https', 'json', url=self.vapi_url) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) connector.set_security_context(sec_ctx) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.session = Session(self.stub_config) logger.info('Login to VAPI endpoint and get the session_id...') self.session_id = self.session.create() logger.info('Update the VAPI connection with session_id...') session_sec_ctx = create_session_security_context(self.session_id) connector.set_security_context(session_sec_ctx)
def __init__(self, session, server, username, password, bearer_token, hok_token, private_key): """ Initialize VsphereClient by creating a parent stub factory instance of all vSphere components. :type session: :class:`requests.Session` :param session: Requests HTTP session instance. If not specified, then one is automatically created and used :type server: :class:`str` :param server: vCenter host name or IP address :type username: :class:`str` :param username: Name of the user :type password: :class:`str` :param password: Password of the user :type bearer_token: :class:`str` :param bearer_token: SAML Bearer Token :type hok_token: :class:`str` :param hok_token: SAML Hok Token :type private_key: :class:`str` :param private_key: Absolute file path of the private key of the user """ if not session: self.session = session = requests.Session() host_url = "https://" + server + JSON_RPC_ENDPOINT if username is not None and password is not None and \ not bearer_token and not hok_token: sec_ctx = create_user_password_security_context(username, password) elif bearer_token and not username and not hok_token: sec_ctx = create_saml_bearer_security_context(bearer_token) elif hok_token and private_key and not bearer_token and not username: sec_ctx = create_saml_security_context(hok_token, private_key) else: raise ValueError('Please provide exactly one of the following ' 'authentication scheme: username/password, ' 'bear_token or hok_token/private_key') session_svc = Session( StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ]))) session_id = session_svc.create() sec_ctx = create_session_security_context(session_id) stub_config = StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ])) self.session_svc = Session(stub_config) stub_factory = StubFactory(stub_config) ApiClient.__init__(self, stub_factory)
def _vApiInit(self, host, user, password, proto='https', msg_type='json'): """ The authenticated stub configuration object can be used to issue requests against vCenter. The _config object stores the session identifier that can be used to issue authenticated requests against vCenter. """ session = requests.Session() session.verify = False api_url = '{0}://{1}/api'.format(proto, host) self._connector = get_requests_connector(session=session, url=api_url) self._config = StubConfigurationFactory.new_std_configuration( self._connector) # Creating security context loging for vAPI endpoint authentication sec_context_login = create_user_password_security_context( user, password) self._config.connector.set_security_context(sec_context_login) # Create the stub for the session service and login by creating a session. session_svc = Session(self._config) session_id = session_svc.create() # Successful authentication. Store the session identifier in the security # context of the stub config and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) self._config.connector.set_security_context(session_security_context)
def _login_vapi(self): """ Login to vCenter API using REST call Returns: connection object """ session = requests.Session() session.verify = self.validate_certs if not self.validate_certs: # Disable warning shown at stdout requests.packages.urllib3.disable_warnings() vcenter_url = "https://%s/api" % self.hostname # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context(self.username, self.password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = session_svc.create() # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: raise AnsibleError("Failed to login to %s using %s" % (self.hostname, self.username)) return stub_config
def vsphere_client(): stub_config = StubConfigurationFactory.new_std_configuration( get_requests_connector(session=requests.session(), url='https://localhost/vapi')) stub_factory = StubFactory(stub_config) client = ApiClient(stub_factory) return client
def main(): module = AnsibleModule(argument_spec=dict(display_name=dict(required=True, type='str'), vlan_logical_switches=dict( required=True, type='str'), vmks=dict(required=True, type='str'), pnics=dict(required=False, type='dict'), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=False) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() migrateVmks(module, stub_config)
def SheetSecDFW(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['DFW'] = [] # connection to NSX SessionNSX = ConnectNSX(auth_list) policies_json = GetAPI( SessionNSX[0], '/policy/api/v1/infra/domains/default/security-policies', auth_list) stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1]) rules_svc = Rules(stub_config) # Header of Excel and initialization of lines XLS_Lines = [] TN_HEADER_ROW = ('Security Policy', 'Security Policy Applied to', 'Category', 'Rule Name', 'Rule ID', 'Source', 'Destination', 'Services', 'Profiles', 'Rule Applied to', 'Action', 'Direction', 'Disabled', 'IP Protocol', 'Logged') if isinstance(policies_json, dict) and 'results' in policies_json: for policy in policies_json["results"]: # Check Applied to for policies scopelist = GetListNameFromPath(policy['scope']) #### Get RULES #### PrintRulesbyCategory(rules_svc, policy['display_name'], policy['id'], policy['category'], scopelist, XLS_Lines, NSX_Config) else: XLS_Lines.append( ['No results', "", "", "", "", "", "", "", "", "", "", "", "", ""]) FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
def setUp(self): self.provider = LocalProvider() self.provider.add_interface(MockImpl()) connector = LocalConnector(self.provider) stub_config = StubConfigurationFactory.new_std_configuration(connector) self.service = Service(stub_config) self.operation = Operation(stub_config)
def get_session_auth_stub_config(user, password, nsx_host, tcp_port=443): """ Create a stub configuration that uses session-based authentication. Session authentication is more efficient, since the server only needs to perform authentication of the username/password one time. """ session = requests.session() # Since the NSX manager default certificate is self-signed, # we disable verification. This is dangerous and real code # should verify that it is talking to a valid server. session.verify = False requests.packages.urllib3.disable_warnings() nsx_url = 'https://%s:%s' % (nsx_host, tcp_port) resp = session.post(nsx_url + "/api/session/create", data={ "j_username": user, "j_password": password }) if resp.status_code != requests.codes.ok: resp.raise_for_status() # Set the Cookie and X-XSRF-TOKEN headers session.headers["Cookie"] = resp.headers.get("Set-Cookie") session.headers["X-XSRF-TOKEN"] = resp.headers.get("X-XSRF-TOKEN") connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) return stub_config
def connect(self, host, user, pwd, skip_verification=False, cert_path=None, suppress_warning=True): """ Create an authenticated stub configuration object that can be used to issue requests against vCenter. Returns a stub_config that stores the session identifier that can be used to issue authenticated requests against vCenter. """ host_url = self.get_jsonrpc_endpoint_url(host) session = requests.Session() if skip_verification: session = self.create_unverified_session(session, suppress_warning) elif cert_path: session.verify = cert_path connector = get_requests_connector(session=session, url=host_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) return self.login(stub_config, user, pwd)
def SheetTZ(auth_list,WORKBOOK,TN_WS, NSX_Config ={} ): NSX_Config['TZ'] = [] Dict_TZ = {} # Connect NSX SessionNSX = ConnectNSX(auth_list) stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1]) XLS_Lines = [] TN_HEADER_ROW = ('Name', 'Description', 'ID', 'Ressource Type', 'Host Switch ID', 'Hos Switch Mode', 'Host Switch Name', 'Host Switch is Default', 'is Nested NSX', 'Transport Type', 'Uplink Teaming Policy Name') tz_list = TransportZones(stub_config).list() for TZ in tz_list.results: tz = TZ.convert_to(TransportZone) if tz.uplink_teaming_policy_names is not None: TZ_Teaming = "\n".join(tz.uplink_teaming_policy_names) else: TZ_Teaming = "" Dict_TZ['name'] = tz.display_name Dict_TZ['description'] = tz.description Dict_TZ['id'] = tz.id Dict_TZ['resource_type'] = tz.resource_type Dict_TZ['host_swithc_id'] = tz.host_switch_id Dict_TZ['host_switch_mode'] = tz.host_switch_mode Dict_TZ['host_switch_name'] = tz.host_switch_name Dict_TZ['is_default'] = tz.is_default Dict_TZ['nested'] = tz.nested_nsx Dict_TZ['type'] = tz.transport_type Dict_TZ['teaming'] = tz.uplink_teaming_policy_names NSX_Config['TZ'].append(Dict_TZ) # Create line XLS_Lines.append([tz.display_name, tz.description, tz.id, tz.resource_type, tz.host_switch_id, tz.host_switch_mode, tz.host_switch_name, tz.is_default, tz.nested_nsx, tz.transport_type, TZ_Teaming]) FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA")
def run(self): """ Converges the external PSC into the Management Node without shutting down the Platform Services Controller. """ session = get_unverified_session() if self.skipverification else None sec_ctx = create_user_password_security_context( self.username, self.password) # TODO The following line to be deleted when API is changed to # @Release type. As of now this is only for testing app_ctx = ApplicationContext({SHOW_UNRELEASED_APIS: "True"}) connector = get_requests_connector( session=session, msg_protocol='json', url='https://{0}:5480/api'.format(self.server), provider_filter_chain=[ LegacySecurityContextFilter( security_context=sec_ctx)]) connector.set_application_context(app_ctx) stub_config = StubConfigurationFactory.new_std_configuration(connector) deployment_type = DeploymentType(stub_config) """ Running convergence task precheck. Remove the line ", only_precheck = True" to perform convergence. """ convergence_task = deployment_type.convert_to_vcsa_embedded_task( DeploymentType.ConvergenceSpec(DeploymentType.PscInfo( sso_admin_username=self.sso_admin_username, sso_admin_password=self.sso_admin_password), only_precheck=True)) print('Converge operation started with task ID: \n{0}'.format( convergence_task.get_task_id()))
def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX MANAGER IP>", 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context("<USERNAME>", "<PASSWORD>") connector.set_security_context(security_context) urllib3.disable_warnings() tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() r = tz_list.results start_row = 1 for i in r: tz = i.convert_to(TransportZone) sheet1.write(start_row, 0, tz.display_name) sheet1.write(start_row, 1, tz.description) sheet1.write(start_row, 2, tz.id) sheet1.write(start_row, 3, tz.resource_type) sheet1.write(start_row, 4, tz.host_switch_id) sheet1.write(start_row, 5, tz.host_switch_mode) sheet1.write(start_row, 6, tz.host_switch_name) sheet1.write(start_row, 7, tz.is_default) sheet1.write(start_row, 8, tz.nested_nsx) sheet1.write(start_row, 9, tz.transport_type) sheet1.write(start_row, 10,tz.uplink_teaming_policy_names) start_row += 1 ls_wkbk.save('Transport Zones.xls')
def run(self): """ Decommissions a PSC node from a Management Node """ session = get_unverified_session() if self.skipverification else None sec_ctx = create_user_password_security_context( self.username, self.password) # TODO The following line to be deleted when API is changed to # @Release type. As of now this is only for testing app_ctx = ApplicationContext({SHOW_UNRELEASED_APIS: "True"}) connector = get_requests_connector(session=session, msg_protocol='json', url='https://{0}:5480/api'.format( self.server)) connector.set_security_context(sec_ctx) connector.set_application_context(app_ctx) stub_config = StubConfigurationFactory.new_std_configuration(connector) pscs_obj = Pscs(stub_config) """ Running decommission task precheck. Remove the line ", only_precheck = True" to perform decommission. """ decommission_task = pscs_obj.decommission_task( self.psc_hostname, Pscs.DecommissionSpec(sso_admin_username=self.sso_admin_username, sso_admin_password=self.sso_admin_password), only_precheck=True) print('Decommission operation started with task ID: \n%s', decommission_task.get_task_id())
def stub_connect(host, username, password, verify=False): """ Connect to the vCenter using the REST API """ from com.vmware.cis_client import Session from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.security.session import create_session_security_context from vmware.vapi.security.user_password import create_user_password_security_context from vmware.vapi.stdlib.client.factories import StubConfigurationFactory url = "https://{}/api".format(host) session = requests.Session() session.verify = verify connector = get_requests_connector(session=session, url=url) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context( username, password) stub_config.connector.set_security_context(user_password_security_context) session_svc = Session(stub_config) session_id = session_svc.create() session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def main(): # Read the command-line arguments. The args object will contain # 4 properties, args.nsx_host, args.tcp_port, args.user, and # args.password. args = getargs.getargs() # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Set up the API connector and security context nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( args.user, args.password) connector.set_security_context(security_context) # Now any API calls we make should authenticate to NSX using # HTTP Basic Authentication. Let's get a list of all Transport Zones. transportzones_svc = TransportZones(stub_config) tzs = transportzones_svc.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(tzs)
def SheetSegments(auth_list,WORKBOOK,TN_WS,NSX_Config = {}): NSX_Config['Segments'] = [] Dict_LS = {} # NSX Connection SessionNSX = ConnectNSX(auth_list) stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1]) ls_svc = LogicalSwitches(stub_config) ls_list = ls_svc.list() nb = len(ls_list.results) tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() XLS_Lines = [] TN_HEADER_ROW = ('Segments', 'VNI', 'VLAN', 'Transport Zone Name', 'Transport Zone Type', 'Replication Mode', 'Admin State') if ls_list.result_count > 0: while True: for segment in ls_list.results: TZ_NAME = "" TZ_Type = "" for tz in tz_list.results: if segment.transport_zone_id == tz.id: TZ_NAME = tz.display_name TZ_Type = tz.transport_type Dict_LS['segment_name'] = segment.display_name Dict_LS['vni'] = segment.vni Dict_LS['vlan'] = segment.vlan Dict_LS['tz_name'] = TZ_NAME Dict_LS['tz_type'] = TZ_Type Dict_LS['replication_mode'] = segment.replication_mode Dict_LS['status'] = segment.admin_state NSX_Config['Segments'].append(Dict_LS) XLS_Lines.append([segment.display_name, segment.vni, segment.vlan, TZ_NAME, TZ_Type, segment.replication_mode,segment.admin_state]) if ls_list.cursor is None: break else: print(" --> more than " + str(nb) + " results for " + style.RED + "Segments" + style.NORMAL + " - please wait") ls_list = LogicalSwitches(stub_config).list(cursor =ls_list.cursor ) nb = len(ls_list.results) + nb else: XLS_Lines.append(["no Segments", "", "", "", "", "",""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV,TN_HEADER_ROW,XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA") ConditionnalFormat(TN_WS, 'G2:G' + str(len(XLS_Lines) + 1), 'UP')
def __init__(self, connector): """ Initialize IntrospectableApiProvider :type connector: :class:`vmware.vapi.protocol.client.connector.Connector` :param Connector: Protocol connector to use for operation invocations """ stub_config = StubConfigurationFactory.new_std_configuration(connector) self._operation = Operation(stub_config)
def run(self): print('\n\n#### Example: Login to vCenter server with ' 'embedded Platform Services Controller') # Since the platform services controller is embedded, the sso server # is the same as the vCenter server. ssoUrl = 'https://{}/sts/STSService'.format(self.server) print('\nStep 1: Connect to the Single Sign-On URL and ' 'retrieve the SAML bearer token.') authenticator = sso.SsoAuthenticator(ssoUrl) context = None if self.skip_verification: context = get_unverified_context() bearer_token = authenticator.get_bearer_saml_assertion( self.username, self.password, delegatable=True, ssl_context=context) # Creating SAML Bearer Security Context sec_ctx = create_saml_bearer_security_context(bearer_token) print('\nStep 2. Login to vAPI services using the SAML bearer token.') # The URL for the stub requests are made against the /api HTTP endpoint # of the vCenter system. vapi_url = 'https://{}/api'.format(self.server) # Create an authenticated stub configuration object that can be used to # issue requests against vCenter. session = requests.Session() if self.skip_verification: session = create_unverified_session(session) connector = get_requests_connector(session=session, url=vapi_url) connector.set_security_context(sec_ctx) stub_config = StubConfigurationFactory.new_std_configuration( connector) self.session = Session(stub_config) # Login to VAPI endpoint and get the session_id self.session_id = self.session.create() # Update the VAPI connection with session_id session_sec_ctx = create_session_security_context(self.session_id) connector.set_security_context(session_sec_ctx) print('\nStep 3: List available datacenters using the vAPI services') datacenter_svc = Datacenter(stub_config) pprint(datacenter_svc.list()) self.session.delete() print('VAPI session disconnected successfully...')
def main(): module = AnsibleModule( argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), form_factor=dict(required=False, type='str', default='MEDIUM', choices=['SMALL', 'MEDIUM', 'LARGE']), vsphere_cluster=dict(required=True, type='str'), host_id=dict(required=False, type='str', default=None), data_network_ids=dict(required=True, type='list'), default_gateway_addresses=dict(required=True, type='list'), hostname=dict(required=True, type='str'), management_network_id=dict(required=True, type='str'), management_port_subnet=dict(required=True, type='str'), management_port_prefix=dict(required=True, type='int'), storage_id=dict(required=True, type='str'), vc_id=dict(required=True, type='str'), cli_password=dict(required=True, type='str', no_log=True), root_password=dict(required=True, type='str', no_log=True), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True) ), supports_check_mode=True ) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() node = getEdheNodeByName(module, stub_config) if module.params['state'] == "present": if node: module.exit_json(changed=False, id=node.id, msg="Edge with name %s already exists!" % (module.params['display_name'])) elif not node: createEdge(module, stub_config) elif module.params['state'] == "absent": if node: nodes_svc = Nodes(stub_config) nodes_svc.delete(node.id) module.exit_json(changed=True, object_name=module.params['display_name'], message="Node with name %s deleted"%(module.params['display_name'])) elif not node: module.exit_json(changed=False, object_name=module.params['display_name'], message="Node with name %s does not exists"%(module.params['display_name']))
def automationSDKConnect(vcenter=None, username=None, password=None, insecure=None): """Creates stub_config with connection object for advanced features like VM Tagging present in vsphere-automation-sdk-python library, which is required to be installed: https://github.com/vmware/vsphere-automation-sdk-python""" vcenter = vcenter or conf.VCENTER username = username or conf.USERNAME password = password or conf.PASSWORD insecure = insecure or conf.INSECURE_CONNECTION if not HAS_AUTOMAT_SDK_INSTALLED: raise VmCLIException( 'Required vsphere-automation-sdk-python not installed. Exiting...') sys.exit(1) if (vcenter and username) and not password: password = getpass.getpass() elif not (vcenter and username and password): logger.error('No authentication credentials provided!') sys.exit(1) if not vcenter.startswith('http'): vcenter = 'https://{}/api'.format(vcenter) session = requests.Session() if insecure: requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning) session.verify = False connector = get_requests_connector(session=session, url=vcenter) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context( username, password) stub_config.connector.set_security_context(user_password_security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) try: session_id = session_svc.create() except Unauthenticated: logger.error('Unable to connect. Check your credentials!') sys.exit(1) # Successful authentication. Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def __init__(self, sddc=None, verbose=False): self.sddc = sddc if not self.sddc: raise ValueError('You must supply a valid SDDC() object') self.org = sddc.org self.vmc = self.org.vmc self.vc_url = self.sddc.sddc.resource_config.vc_url self.vc_host = re.sub(r'https://(.*)/', r'\1', self.vc_url) self.vc_username = self.sddc.sddc.resource_config.cloud_username self.vc_password = self.sddc.sddc.resource_config.cloud_password session = requests.Session() connector = get_requests_connector(session=session, url='https://' + self.vc_host + '/api') user_password_security_context = create_user_password_security_context( self.vc_username, self.vc_password) context = ssl._create_unverified_context() self.stub_config = StubConfigurationFactory.new_std_configuration( connector) self.stub_config.connector.set_security_context( user_password_security_context) session_svc = Session(self.stub_config) session_id = session_svc.create() session_security_context = create_session_security_context(session_id) self.stub_config.connector.set_security_context( session_security_context) self.library_stub = content_client.Library(self.stub_config) self.subscribed_library_stub = content_client.SubscribedLibrary( self.stub_config) self.si = SmartConnect(host=self.vc_host, user=self.vc_username, pwd=self.vc_password, sslContext=context) self.content = self.si.RetrieveContent() self.references = {} self.referenceTypes = { 'datastores': [vim.Datastore], 'resourcePools': [vim.ClusterComputeResource], 'folders': [vim.Folder], 'VMs': [vim.VirtualMachine] } for referenceName in self.referenceTypes: self.refreshReference(referenceName)
def __init__(self, stub_factory_class, session, refresh_token, vmc_url, csp_url, org_id, sddc_id): """ Initialize VmcClient by creating a stub factory instance using a CSP Security context filter added to the filter chain of the connector :type stub_factory_class: :class:`type` :param stub_factory_class: Which stub factory class to use :type session: :class:`requests.Session` :param session: Requests HTTP session instance :type refresh_token: :class:`str` :param refresh_token: Refresh token obtained from CSP :type vmc_url: :class:`str` :param vmc_url: URL of the VMC service :type csp_url: :class:`str` :param csp_url: URL of the CSP service :type org_id: :class:`str` :param org_id: ID of the VMC organization :type sddc_id: :class:`str` :param sddc_id: ID of the VMC Software-Defined Data Center (SDDC) """ # Call the VMC API to obtain the URL for the NSX Reverse Proxy refresh_url = "%s/%s" % (csp_url, self._CSP_REFRESH_URL_SUFFIX) resp = requests.post("%s?refresh_token=%s" % (refresh_url, refresh_token)) resp.raise_for_status() resp_json = resp.json() access_token = resp_json["access_token"] v_session = requests.Session() v_session.headers["csp-auth-token"] = access_token sddc_url = "%svmc/api/orgs/%s/sddcs/%s" % (vmc_url, org_id, sddc_id) resp = v_session.get(sddc_url) resp.raise_for_status() resp_json = resp.json() nsx_url = resp_json.get("resource_config", {}).get("nsx_api_public_endpoint_url") # Strip trailing "/" if present if nsx_url and nsx_url[-1] == "/": nsx_url = nsx_url[:-1] # Create the stub factory for the NSX API stub_factory = stub_factory_class( StubConfigurationFactory.new_std_configuration( get_requests_connector(session=session, msg_protocol='rest', url=nsx_url, provider_filter_chain=[ CSPSecurityContextFilter( session, refresh_token, refresh_url) ]))) ApiClient.__init__(self, stub_factory)
def execute(self): logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl)) lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, soap_url=self.lssoapurl) lookupservicehelper.connect() if self.mgmtinstancename is None: self.mgmtinstancename, self.mgmtnodeid = lookupservicehelper.get_default_mgmt_node() elif self.mgmtnodeid is None: self.mgmtnodeid = lookupservicehelper.get_mgmt_node_id(self.mgmtinstancename) assert self.mgmtnodeid is not None self.vapiurl = lookupservicehelper.find_vapi_url(self.mgmtnodeid) logger.info('vapi_url: {0}'.format(self.vapiurl)) logger.info('Connecting to VAPI endpoint and preparing stub configuration...') connector = connect.get_connector('https', 'json', url=self.vapiurl) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) sec_ctx = create_user_password_security_context(self.ssousername, self.ssopassword) connector.set_security_context(sec_ctx) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.session = Session(self.stub_config) logger.info('Login to VAPI endpoint and get the session_id...') self.session_id = self.session.create() logger.info('Update the VAPI connection with session_id...') session_sec_ctx = create_session_security_context(self.session_id) connector.set_security_context(session_sec_ctx) # make sure you can access some of the VAPI services tag_svc = Tag(self.stub_config) logger.info('List all the existing tags user has access to...') tags = tag_svc.list() if len(tags) > 0: for tag in tags: logger.info('Found Tag: {0}'.format(tag)) else: logger.info('No Tag Found...')
def connect_to_rest(self): """ Connect to server using username and password """ session = requests.Session() session.verify = self.params.get('validate_certs') username = self.params.get('username', None) password = self.params.get('password', None) protocol = self.params.get('protocol', 'https') hostname = self.params.get('hostname') if not all([self.params.get('hostname', None), username, password]): self.module.fail_json( msg= "Missing one of the following : hostname, username, password." " Please read the documentation for more information.") vcenter_url = "%s://%s/api" % (protocol, hostname) # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context( username, password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = None try: session_id = session_svc.create() except OSError as os_err: self.module.fail_json(msg="Failed to login to %s: %s" % (hostname, to_native(os_err))) if session_id is None: self.module.fail_json( msg="Failed to create session using provided credentials." " Please check hostname, username and password.") # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: self.module.fail_json(msg="Failed to login to %s" % hostname) return stub_config
def connect(self): assert self.node_id is not None assert self.platform_service_controller is not None self.instance_name = self.platform_service_controller.lookupservicehelper.get_mgmt_node_instance_name(self.node_id) # discover the service endpoints from the lookup service on infrastructure node self.vapi_url = self.platform_service_controller.lookupservicehelper.find_vapi_url(self.node_id) assert self.vapi_url is not None self.vim_url = self.platform_service_controller.lookupservicehelper.find_vim_url(self.node_id) assert self.vim_url is not None # login to vAPI endpoint logger.info('Connecting to vapi url: {0}'.format(self.vapi_url)) connector = connect.get_connector('https', 'json', url=self.vapi_url) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) connector.set_security_context(self.platform_service_controller.sec_ctx) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.session = Session(self.stub_config) self.session_id = self.session.create() # update the connection with session id session_sec_ctx = create_session_security_context(self.session_id) connector.set_security_context(session_sec_ctx) # pyvmomi # extract the host from the vim url vim_host = get_url_host(self.vim_url) assert vim_host is not None self.si = SmartConnect(host=vim_host, user=self.platform_service_controller.ssousername, pwd=self.platform_service_controller.ssopassword) assert self.si is not None # retrieve the service content self.content = self.si.RetrieveContent() assert self.content is not None self.vim_uuid = self.content.about.instanceUuid
def automationSDKConnect(vcenter=None, username=None, password=None, insecure=None): """Creates stub_config with connection object for advanced features like VM Tagging present in vsphere-automation-sdk-python library, which is required to be installed: https://github.com/vmware/vsphere-automation-sdk-python""" vcenter = vcenter or conf.VCENTER username = username or conf.USERNAME password = password or conf.PASSWORD insecure = insecure or conf.INSECURE_CONNECTION if not HAS_AUTOMAT_SDK_INSTALLED: raise VmCLIException('Required vsphere-automation-sdk-python not installed. Exiting...') sys.exit(1) if (vcenter and username) and not password: password = getpass.getpass() elif not (vcenter and username and password): logger.error('No authentication credentials provided!') sys.exit(1) if not vcenter.startswith('http'): vcenter = 'https://{}/api'.format(vcenter) session = requests.Session() if insecure: requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) session.verify = False connector = get_requests_connector(session=session, url=vcenter) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context(username, password) stub_config.connector.set_security_context(user_password_security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) try: session_id = session_svc.create() except Unauthenticated: logger.error('Unable to connect. Check your credentials!') sys.exit(1) # Successful authentication. Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def main(): # Read the command-line arguments. arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-n', '--nsx_host', type=str, required=True, help='NSX host to connect to') arg_parser.add_argument('-t', '--tcp_port', type=int, default=443, help='TCP port for NSX server') arg_parser.add_argument('-c', '--client_certificate', type=str, required=True, help='Name of PEM file containing client ' 'certificate and private key') args = arg_parser.parse_args() # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Configure the requests library to supply a client certificate session.cert = args.client_certificate # Set up the API connector and client nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) stub_factory = nsx_client.StubFactory(stub_config) api_client = ApiClient(stub_factory) # Now any API calls we make should authenticate to NSX using # the client certificate. Let's get a list of all Transport Zones. tzs = api_client.TransportZones.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(tzs)
def _build(self, api_provider): """ Get the metamodel metadata and process it :type api_provider: :class:`vmware.vapi.core.ApiProvider` :param api_provider: ApiProvider to get the metadata """ local_connector = get_local_connector(api_provider) stub_config = StubConfigurationFactory.new_std_configuration( local_connector) component_svc = Component(stub_config) components = component_svc.list() for component_id in components: component_data = component_svc.get(component_id) self._process_component_info(component_data.info)
def __init__(self, ipaddr, username, password): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (ipaddr, 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) self.stub_config = StubConfigurationFactory.new_std_configuration( connector) security_context = create_user_password_security_context( username, password) connector.set_security_context(security_context)
def create_api_connection(): session = requests.session() session.proxies.update(PROXY) session.verify = False nsx_url = 'https://%s:%s' % (NSX_HOST, TCP_PORT) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( USER, os.popen("gopass " + GOPASS_CREDENTIAL).read()) connector.set_security_context(security_context) return stub_config
def stub_configuration(nsx_ip, nsx_user, nsx_pass): stub_config = None try: session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (nsx_ip, 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( nsx_user, nsx_pass) connector.set_security_context(security_context) except Exception, e: stub_config = None raise Exception("Could not get Stub for NSX %s" % nsx_ip)
def main(): # Read the command-line arguments. The args object will contain # 3 properties, args.nsx_host, args.tcp_port, and args.refresh_token. args = getargs.getargs() if args.refresh_token is None: sys.stderr.write( "Error: you must provide a refresh token for this example\n") sys.exit(1) # Obtain a token to use for authenticating to the NSX Manager. We # just use the python requests library directly. params = {"refresh_token", args.refresh_token} resp = requests.post("%s?refresh_token=%s" % (VMC_AUTH_URL, args.refresh_token)) resp.raise_for_status() # Will raise exception if error resp_json = resp.json() # This is the access token you will pass with all NSX Manager API requests access_token = resp_json["access_token"] # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # Arrange for the requests library to send the bearer token header # with each request. session.headers["Authorization"] = "Bearer %s" % access_token # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Set up the API connector nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) resp = session.get("%s/api/v1/cluster" % nsx_url) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Let's get a list of all Domains domains_svc = Domains(stub_config) domains = domains_svc.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(domains)
def connect_to_rest(self): """ Function to connect to server using username and password """ session = requests.Session() session.verify = self.params.get('validate_certs') username = self.params.get('username', None) password = self.params.get('password', None) if not all([self.params.get('hostname', None), username, password]): self.module.fail_json(msg="Missing one of the following : hostname, username, password." " Please read the documentation for more information.") vcenter_url = "%(protocol)s://%(hostname)s/api" % self.params # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context(username, password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = None try: session_id = session_svc.create() except OSError as os_err: self.module.fail_json(msg="Failed to login to %s: %s" % (self.params['hostname'], to_native(os_err))) if session_id is None: self.module.fail_json(msg="Failed to create session using provided credentials." " Please check hostname, username and password.") # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: self.module.fail_json(msg="Failed to login to %(hostname)s" % self.params) return stub_config