Exemplo n.º 1
0
    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 __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)
Exemplo n.º 3
0
	def create_nsx_policy_api_client(self, auth_type=BASIC_AUTH,):
	    if auth_type == BASIC_AUTH:
		stub_config = self.get_basic_auth_stub_config()
	    elif auth_type == SESSION_AUTH:
		stub_config = get_session_auth_stub_config(self)
	    stub_factory = nsx_policy_client.StubFactory(stub_config)
	    return ApiClient(stub_factory)
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
Exemplo n.º 5
0
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)
    stub_factory = nsx_client.StubFactory(stub_config)
    api_client = ApiClient(stub_factory)

    # Now any API calls we make should authenticate to NSX using
    # HTTP Basic Authentication. 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)
Exemplo n.º 6
0
def create_api_client(stub_factory_class, user, password, nsx_host,
                      tcp_port=443, auth_type=BASIC_AUTH):
    if auth_type == BASIC_AUTH:
        stub_config = get_basic_auth_stub_config(
            user, password, nsx_host, tcp_port)
    elif auth_type == SESSION_AUTH:
        stub_config = get_session_auth_stub_config(
            user, password, nsx_host, tcp_port)
    stub_factory = stub_factory_class.StubFactory(stub_config)
    return ApiClient(stub_factory)
Exemplo n.º 7
0
    def __init__(self, session, refresh_token, vmc_url, csp_url):
        """
        Initialize VmcClient by creating a stub factory instance using a CSP
        Security context filter added to the filter chain of the connector

        :type  session: :class:`requests.Session`
        :param session: Requests HTTP session instance
        :type  refresh_token: :class:`str`
        :param refresh_token: Refresh token obtained from CSP
        """
        # Build Refresh URL using the CSP URL and the Refresh URL suffix
        refresh_url = csp_url.rstrip('/') + self._CSP_REFRESH_URL_SUFFIX
        stub_factory = VmcStubFactory(
            StubConfigurationFactory.new_std_configuration(
                get_requests_connector(session=session,
                                       msg_protocol='rest',
                                       url=vmc_url,
                                       provider_filter_chain=[
                                           CSPSecurityContextFilter(
                                               session, refresh_token,
                                               refresh_url)
                                       ])))
        ApiClient.__init__(self, stub_factory)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
    def create(self):
        try:
            transport_zone_id = None

            stub_factory = nsx_client.StubFactory(self.stub_config)

            api_client = ApiClient(stub_factory)

            overlay_transport_zone_spec = model_client.TransportZone(transport_type=self.zone_type,
                                                                     display_name=self.display_name,
                                                                     description=self.description,
                                                                     host_switch_name=self.host_switch_name)
            transport_zone = api_client.TransportZones.create(overlay_transport_zone_spec)
            print("TransportZone - Overlay Transport zone created. id is %s" % transport_zone)
            transport_zone_id = transport_zone.id
            return transport_zone_id, True
        except Exception,e:
            return "TransportZone -  %s Transport Zone %s creation failed with %s"%(self.zone_type,self.display_name,e) , False
"""

__author__ = 'VMware, Inc.'

import requests
from vmware.vapi.bindings.stub import ApiClient, StubFactoryBase
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory

from vmware.vapi.vsphere.client import StubFactory

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)


def test_vcenter_client():
    assert hasattr(client, 'vcenter')
    assert isinstance(client.vcenter, StubFactoryBase)


def test_cluster_client():
    assert hasattr(client.vcenter, 'Cluster')


def test_datacenter_client():
    assert hasattr(client.vcenter, 'Datacenter')

Exemplo n.º 11
0
def get_session_auth_api_client(user, password, nsx_host, tcp_port=443):
    stub_config = get_session_auth_stub_config(user, password, nsx_host,
                                               tcp_port)
    stub_factory = nsx_client.StubFactory(stub_config)
    return ApiClient(stub_factory)
Exemplo n.º 12
0
	def get_session_auth_api_client(self):
	    stub_config = get_session_auth_stub_config(self,
		self.username, self.password, self.ip, self.tcp_port)
	    stub_factory = nsx_client.StubFactory(stub_config)
	    return ApiClient(stub_factory)