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 __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 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 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 setUpClass(cls): session = requests.session() session.verify = False cls.rest_connector = get_requests_connector(session=session, msg_protocol='rest', url='https://some-url') cls.stub_config = StubConfiguration(cls.rest_connector)
def _process_child(self, provider_cfg, child): """ Process a aggregator child provider_cfg :type provider_cfg: :class:`dict` :param provider_cfg: Properties dictionary :type child: :class:`str` :param child: Child to be processed """ try: url = provider_cfg.get_child_url(child) connector = connect.get_requests_connector( session=requests.session(), url=url) api_provider = connector.get_api_provider() rpc_protocol = get_url_scheme(url) msg_protocol = provider_cfg.get_provider_message_format(child) if api_provider: self.register_provider(api_provider, child, rpc_protocol, msg_protocol, addr=url) except Exception as e: stack_trace = traceback.format_exc() raise Exception('Could not register %s at %s due to %s' % (child, url, stack_trace))
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 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 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): """ 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 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 _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 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 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 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 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 __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 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 ConnectNSX(auth_list): """ ConnectNSX(list) Connection function to NSX. Can be by certifcates or by authentication. Returns ---------- list with session object and connector object Args ---------- auth : list list must contain login/cert - password/key - Tag (AUTH or CERT) """ YAML_DICT = GetYAMLDict() if auth_list[2] == 'AUTH': session = requests.session() session.verify = False connector = connect.get_requests_connector(session=session, msg_protocol='rest', url='https://' + YAML_DICT['NSX_MGR_IP']) security_context = create_user_password_security_context( auth_list[0], auth_list[1]) connector.set_security_context(security_context) return [session, connector] elif auth_list[2] == 'CERT': session = requests.session() session.verify = False session.cert = (auth_list[0], auth_list[1]) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url='https://' + YAML_DICT['NSX_MGR_IP']) return [session, connector] else: print("Issue on authentication") exit(1)
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 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, 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
def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX-T MANAGER FQDN>", 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() ls_list = [] ls_svc = LogicalSwitches(stub_config) ls_list = ls_svc.list() # print(ls_list) tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() start_row = 1 for vs in ls_list.results: ls = vs.convert_to(LogicalSwitch) sheet1.write(start_row, 0, ls.display_name) sheet1.write(start_row, 1, ls.vni, style_alignleft) sheet1.write(start_row, 2, ls.vlan, style_alignleft) sheet1.write(start_row, 4, ls.transport_zone_id) sheet1.write(start_row, 6, ls.replication_mode) sheet1.write(start_row, 7, ls.admin_state) # print(ls.resource_type) newlist = [] for i in range(len(ls.tags)): newlist.append(ls.tags[i].tag) sheet1.write(start_row, 8, (str(newlist[0]))) if len(newlist) > 1: sheet1.write(start_row, 9, (str(newlist.pop()))) x = len(tz_list.results) for i in range(0, x): if ls.transport_zone_id == tz_list.results[i].id: sheet1.write(start_row, 3, tz_list.results[i].display_name) sheet1.write(start_row, 5, tz_list.results[i].transport_type) start_row += 1 ls_wkbk.save('Logical Switches.xls')
def get_basic_auth_stub_config(user, password, nsx_host, tcp_port=443): """ Create a stub configuration that uses HTTP basic authentication. """ 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) 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, password) connector.set_security_context(security_context) return stub_config
def connect_cis(): """Connect to CIS""" import configuration as config import requests import urllib3 from com.vmware.cis_client import Session from vmware.vapi.security.user_password import create_user_password_security_context from vmware.vapi.stdlib.client.factories import StubConfigurationFactory from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.security.session import create_session_security_context # Create a session object in the client. session = requests.Session() # We don't have valid certificates so... urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) session.verify = False # Create a connection for the session. connector = get_requests_connector( session=session, url='https://' + config.VM_HOSTNAME + '/api' ) # Add username/password security context to the connector. connector.set_security_context( create_user_password_security_context( config.VM_USERNAME, config.VM_PASSWORD ) ) # Create a stub configuration by using the username-password security context. my_stub_config = StubConfigurationFactory.new_std_configuration(connector) # Create a Session stub with username-password security context. session_stub = Session(my_stub_config) # Use the create operation to create an authenticated session. session_id = session_stub.create() # Create a session ID security context. session_id_context = create_session_security_context(session_id) # Update the stub configuration with the session ID security context. my_stub_config.connector.set_security_context(session_id_context) return my_stub_config