Ejemplo n.º 1
0
def __Login(host, port, user, pwd, service, adapter, version, path, keyFile,
            certFile):
    """
   Private method that performs the actual Connect and returns a
   connected service instance object.

   @param host: Which host to connect to.
   @type  host: string
   @param port: Port
   @type  port: int
   @param user: User
   @type  user: string
   @param pwd: Password
   @type  pwd: string
   @param service: Service
   @type  service: string
   @param adapter: Adapter
   @type  adapter: string
   @param version: Version
   @type  version: string
   @param path: Path
   @type  path: string
   @param keyFile: ssl key file path
   @type  keyFile: string
   @param certFile: ssl cert file path
   @type  certFile: string
   """

    # XXX remove the adapter and service arguments once dependent code is fixed
    if adapter != "SOAP":
        raise ValueError(adapter)

    # Create the SOAP stub adapter
    stub = SoapStubAdapter(host,
                           port,
                           version=version,
                           path=path,
                           certKeyFile=keyFile,
                           certFile=certFile)

    # Get Service instance
    si = vim.ServiceInstance("ServiceInstance", stub)
    try:
        content = si.RetrieveContent()
    except vmodl.MethodFault:
        raise
    except Exception, e:
        raise vim.fault.HostConnectFault(msg=str(e))
Ejemplo n.º 2
0
def SmartStubAdapter(host='localhost', port=443, path='/sdk',
                     url=None, sock=None, poolSize=5,
                     certFile=None, certKeyFile=None,
                     httpProxyHost=None, httpProxyPort=80, sslProxyPath=None,
                     thumbprint=None, cacertsFile=None, preferredApiVersions=None,
                     acceptCompressedResponses=True,
                     connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
                     samlToken=None, sslContext=None):
   """
   Determine the most preferred API version supported by the specified server,
   then create a soap stub adapter using that version

   The parameters are the same as for pyVmomi.SoapStubAdapter except for
   version which is renamed to prefferedApiVersions

   @param preferredApiVersions: Acceptable API version(s) (e.g. vim.version.version3)
                                If a list of versions is specified the versions should
                                be ordered from most to least preferred.  If None is
                                specified, the list of versions support by pyVmomi will
                                be used.
   @type  preferredApiVersions: string or string list
   """
   if preferredApiVersions is None:
      preferredApiVersions = GetServiceVersions('vim25')

   sslContext = localSslFixup(host, sslContext)

   supportedVersion = __FindSupportedVersion('https' if port > 0 else 'http',
                                             host,
                                             port,
                                             path,
                                             preferredApiVersions,
                                             sslContext,
                                             httpProxyHost,
                                             httpProxyPort
                                             )
   if supportedVersion is None:
      raise Exception("%s:%s is not a VIM server" % (host, port))

   return SoapStubAdapter(host=host, port=port, path=path,
                          url=url, sock=sock, poolSize=poolSize,
                          certFile=certFile, certKeyFile=certKeyFile,
                          httpProxyHost=httpProxyHost, httpProxyPort=httpProxyPort,
                          sslProxyPath=sslProxyPath, thumbprint=thumbprint,
                          cacertsFile=cacertsFile, version=supportedVersion,
                          acceptCompressedResponses=acceptCompressedResponses,
                          connectionPoolTimeout=connectionPoolTimeout,
                          samlToken=samlToken, sslContext=sslContext)
Ejemplo n.º 3
0
def GetStorageManager(vcHost):
   smsStub = None
   vpxdStub = connect.GetStub()
   sessionCookie = vpxdStub.cookie.split('"')[1]
   httpContext = VmomiSupport.GetHttpContext()
   cookie = Cookie.SimpleCookie()
   cookie["vmware_soap_session"] = sessionCookie
   httpContext["cookies"] = cookie

   VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie
   smsStub = SoapStubAdapter(host=vcHost, ns = "sms/4.0",
                                path = "/sms/sdk",
                                poolSize=0)

   si = Sms.ServiceInstance("ServiceInstance", smsStub)
   return si.QueryStorageManager()
Ejemplo n.º 4
0
def connect(host, port, user, pwd, adapter="SOAP"):
   if adapter == None:
      adapter = "SOAP"

   if host == None:
      host = "localhost"

   if port == None:
      port = 443

   if user == None:
      user = os.getlogin()

   print "Connecting to :", host, "at", port, "as", user, "over", adapter

   # Create the VMDB stub adapter
   stub = SoapStubAdapter(host, port)

   # Get Service instance
   si = Vim.ServiceInstance("ServiceInstance", stub)
   content = si.RetrieveContent()
   sessionManager = content.GetSessionManager()

   # Login locally
   if pwd == None:
      localTicket = sessionManager.AcquireLocalTicket(user)
      user = localTicket.GetUserName()
      passwordFile = localTicket.GetPasswordFilePath()
      try:
         fd = open(passwordFile, "r")
         pwd = fd.readline()
         fd.close()
      except Exception:
         msg = "Failed to read password file.  A password is required to " + \
               "connect remotely."
         raise Exception(msg)
      
   # Login
   try:
      x = sessionManager.Login(user, pwd, None);
   except Vim.Fault.InvalidLogin:
      print "Invalid login:"******"Failed to login as ", user
      sys.exit()

   return si
Ejemplo n.º 5
0
 def __Login(self):
     print("INFO: connecting to hostd using '%s'" % (self._protocol))
     self._cnx = SoapStubAdapter(self._host, self._port, self._namespace)
     self._si = Vim.ServiceInstance("ServiceInstance", self._cnx)
     self._content = self._si.RetrieveContent()
     self._pc = self._content.GetPropertyCollector()
     self._sm = self._content.GetSessionManager()
     self._us = self._sm.Login(self._user, self._pswd, None)
     # report if anyone else is logged in
     sessionList = self._sm.GetSessionList()
     if (len(sessionList) > 1):
         self._MsgUpdated = True
         self._sm.UpdateMessage(
             "Integration Tests are running on this system")
         print("WARNING: more than one operator online during test run")
         for item in sessionList:
             print("%s login: %s last active: %s" % \
             (item.GetFullName(), item.GetLoginTime(), item.GetLastActiveTime()))
Ejemplo n.º 6
0
def main():
    ssl._create_default_https_context = ssl._create_unverified_context
    supportedArgs = [(["s:", "server="], "localhost", "Host name", "server")]
    supportedToggles = [(["usage",
                          "help"], False, "Show usage information", "usage")]

    args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles)
    if args.GetKeyValue("usage") == True:
        args.Usage()
        sys.exit(0)

    try:
        host = args.GetKeyValue("server")
        stub = SoapStubAdapter(host, 443, "vim25/2.5", "/sdk")
        si = Vim.ServiceInstance("ServiceInstance", stub)
        sc = si.RetrieveContent()
        print sc.about.build
    except Exception, e:
        print e
        sys.exit(1)
Ejemplo n.º 7
0
def get_vc_content(options):
    """ function to get content object of given vc

    @param options cli options to this script
    @return vc content object
    """
    vc_ip = options.vc
    vc_user = options.vc_user
    vc_password = options.vc_password
    stub = SoapStubAdapter(host=vc_ip,
                           port=443,
                           path="/sdk",
                           version="vim.version.version7")
    service_instance = Vim.ServiceInstance("ServiceInstance", stub)
    if not service_instance:
        print("serviceInstance not defined")
    ssl._create_default_https_context = ssl._create_unverified_context
    content = service_instance.RetrieveContent()
    if not content:
        print("content not defined")
    content.sessionManager.Login(vc_user, vc_password)
    return content
Ejemplo n.º 8
0
 def test1_Login2HostdOverSOAPandSSL(self):
     """
   Verify protocol login to hostd over vmdb over ssl over tcp.
   """
     self._cnx = SoapStubAdapter(self._host, self._port, ns=self._ver)
     si = Vim.ServiceInstance("ServiceInstance", self._cnx)
     self.failUnless(isinstance(si, Vim.ServiceInstance),
                     "expected Vim.ServiceInstance, got %s" % \
                     si.__class__.__name__)
     content = si.RetrieveContent()
     self.failUnless(isinstance(content, Vim.ServiceInstanceContent),
                     "expected Vim.ServiceInstanceContent, got %s" % \
                     content.__class__.__name__)
     sm = content.GetSessionManager()
     self.failUnless(isinstance(sm, Vim.SessionManager),
                     "expected Vim.SessionManager, got %s" % \
                     sm.__class__.__name__)
     us = sm.Login(self._user.encode('utf8'), self._pswd.encode('utf8'),
                   None)
     result = isinstance(us, Vim.UserSession)
     self.failUnless(result,
                     "expected Vim.UserSesion, got %s" % \
                     us.__class__.__name__)
Ejemplo n.º 9
0
 def _service_instance(self):
     stub = SoapStubAdapter("localhost", HOSTD_PORT)
     return vim.ServiceInstance("ServiceInstance", stub)
Ejemplo n.º 10
0
from pyVmomi import Vim, SoapStubAdapter
from pyVim import arguments
from pyVim import folder, vm
from pyVim.helpers import Log

supportedArgs = [(["t:", "ticket="], "", "ticket", "ticket")]
supportedToggles = [(["usage", "help"], False, "usage information", "usage")]
args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles)

if args.GetKeyValue("usage") == True:
    args.Usage()
    sys.exit(0)

ticket = args.GetKeyValue("ticket")
host = 'localhost'
stub = SoapStubAdapter(host=host, version="vim.version.version10")
newsi = Vim.ServiceInstance("ServiceInstance", stub)

# Try to acquire a clone ticket on a un-authenticated session. Should fail.
try:
    newsi.GetContent().GetSessionManager().AcquireCloneTicket()
except:
    pass

newsm = newsi.GetContent().GetSessionManager().CloneSession(ticket)
for vm1 in folder.GetVmAll(si=newsi):
    print vm1

try:
    Log("Power Off (should pass)")
    vm1.PowerOff()
Ejemplo n.º 11
0
def __Login(host, port, user, pwd, service, adapter, version, path,
            keyFile, certFile, sslContext):
   """
   Private method that performs the actual Connect and returns a
   connected service instance object.

   @param host: Which host to connect to.
   @type  host: string
   @param port: Port
   @type  port: int
   @param user: User
   @type  user: string
   @param pwd: Password
   @type  pwd: string
   @param service: Service
   @type  service: string
   @param adapter: Adapter
   @type  adapter: string
   @param version: Version
   @type  version: string
   @param path: Path
   @type  path: string
   @param keyFile: ssl key file path
   @type  keyFile: string
   @param certFile: ssl cert file path
   @type  certFile: string
   @param sslContext: SSL Context describing the various SSL options. It is only
                      supported in Python 2.7.9 or higher.
   @type  sslContext: SSL.Context
   """

   # XXX remove the adapter and service arguments once dependent code is fixed
   if adapter != "SOAP":
      raise ValueError(adapter)

   # Create the SOAP stub adapter
   stub = SoapStubAdapter(host, port, version=version, path=path,
                          certKeyFile=keyFile, certFile=certFile, sslContext=sslContext)

   # Get Service instance
   si = vim.ServiceInstance("ServiceInstance", stub)
   try:
      content = si.RetrieveContent()
   except vmodl.MethodFault:
      raise
   except Exception as e:
      # NOTE (hartsock): preserve the traceback for diagnostics
      # pulling and preserving the traceback makes diagnosing connection
      # failures easier since the fault will also include where inside the
      # library the fault occurred. Without the traceback we have no idea
      # why the connection failed beyond the message string.
      (type, value, traceback) = sys.exc_info()
      if traceback:
         fault = vim.fault.HostConnectFault(msg=str(e))
         reraise(vim.fault.HostConnectFault, fault, traceback)
      else:
          raise vim.fault.HostConnectFault(msg=str(e))

   # Get a ticket if we're connecting to localhost and password is not specified
   if host == 'localhost' and not pwd:
      try:
         (user, pwd) = GetLocalTicket(si, user)
      except:
         pass # This is not supported against vCenter, and connecting
              # with an empty password is fine in debug builds

   # Login
   try:
      x = content.sessionManager.Login(user, pwd, None)
   except vim.fault.InvalidLogin:
      raise
   except Exception as e:
      raise
   return si, stub
Ejemplo n.º 12
0
    port = 443

    cookie = get_cookie(host_ip, user, passwd)
    print()
    print(cookie)

    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    # context = ssl._create_unverified_context()
    context.verify_mode = ssl.CERT_NONE

    new_stub = SoapStubAdapter(
        host_ip,
        port,
        version="vim.version.version6",
        path="/sdk",
        certKeyFile=None,
        certFile=None,
        thumbprint=None,
        sslContext=context,
        # thumbprint=None,
        requestContext={"vcSessionCookie": cookie},
        connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC)
    '''
    new_stub = SoapStubAdapter(host_ip, port, version="pbm.version.version2",
                               path="/pbm", certKeyFile=None, certFile=None,
                               thumbprint=None, sslContext=context,
                               # thumbprint=None,
                               requestContext={"vcSessionCookie": cookie},
                               connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC)
    '''

    si = vim.ServiceInstance("ServiceInstance", new_stub)
Ejemplo n.º 13
0
 def soap_creator():
     return SoapStubAdapter('vcsa', 443)
Ejemplo n.º 14
0
 def soap_creator():
     return SoapStubAdapter('vcsa', 443, requestContext={'vcSessionCookie': '123456789'})
Ejemplo n.º 15
0
def __RetrieveContent(host,
                      port,
                      adapter,
                      version,
                      path,
                      keyFile,
                      certFile,
                      thumbprint,
                      sslContext,
                      connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC):
    """
   Retrieve service instance for connection.
   @param host: Which host to connect to.
   @type  host: string
   @param port: Port
   @type  port: int
   @param adapter: Adapter
   @type  adapter: string
   @param version: Version
   @type  version: string
   @param path: Path
   @type  path: string
   @param keyFile: ssl key file path
   @type  keyFile: string
   @param certFile: ssl cert file path
   @type  certFile: string
   @param connectionPoolTimeout: Timeout in secs for idle connections to close, specify negative numbers for never
                                 closing the connections
   @type  connectionPoolTimeout: int
   """

    # XXX remove the adapter and service arguments once dependent code is fixed
    if adapter != "SOAP":
        raise ValueError(adapter)

    # Create the SOAP stub adapter
    stub = SoapStubAdapter(host,
                           port,
                           version=version,
                           path=path,
                           certKeyFile=keyFile,
                           certFile=certFile,
                           thumbprint=thumbprint,
                           sslContext=sslContext,
                           connectionPoolTimeout=connectionPoolTimeout)

    # Get Service instance
    si = vim.ServiceInstance("ServiceInstance", stub)
    content = None
    try:
        content = si.RetrieveContent()
    except vmodl.MethodFault:
        raise
    except Exception as e:
        # NOTE (hartsock): preserve the traceback for diagnostics
        # pulling and preserving the traceback makes diagnosing connection
        # failures easier since the fault will also include where inside the
        # library the fault occurred. Without the traceback we have no idea
        # why the connection failed beyond the message string.
        (type, value, traceback) = sys.exc_info()
        if traceback:
            fault = vim.fault.HostConnectFault(msg=str(e))
            reraise(vim.fault.HostConnectFault, fault, traceback)
        else:
            raise vim.fault.HostConnectFault(msg=str(e))

    return content, si, stub
Ejemplo n.º 16
0
def __Login(host, port, user, pwd, service, adapter, version, path,
            keyFile, certFile, thumbprint, sslContext, httpConnectionTimeout):
   """
   Private method that performs the actual Connect and returns a
   connected service instance object.

   @param host: Which host to connect to.
   @type  host: string
   @param port: Port
   @type  port: int
   @param user: User
   @type  user: string
   @param pwd: Password
   @type  pwd: string
   @param service: Service
   @type  service: string
   @param adapter: Adapter
   @type  adapter: string
   @param version: Version
   @type  version: string
   @param path: Path
   @type  path: string
   @param keyFile: ssl key file path
   @type  keyFile: string
   @param certFile: ssl cert file path
   @type  certFile: string
   @param thumbprint: host cert thumbprint
   @type  thumbprint: string
   @param sslContext: SSL Context describing the various SSL options. It is only
                      supported in Python 2.7.9 or higher.
   @type  sslContext: SSL.Context
   @param httpConnectionTimeout: Timeout in secs for http requests.
   @type  httpConnectionTimeout: int

   """

   # XXX remove the adapter and service arguments once dependent code is fixed
   if adapter != "SOAP":
      raise ValueError(adapter)

   # Create the SOAP stub adapter
   stub = SoapStubAdapter(host, port, version=version, path=path,
                          certKeyFile=keyFile, certFile=certFile,
                          thumbprint=thumbprint, sslContext=sslContext,
                          httpConnectionTimeout=httpConnectionTimeout)

   # Get Service instance
   si = vim.ServiceInstance("ServiceInstance", stub)
   try:
      content = si.RetrieveContent()
   except vmodl.MethodFault:
      raise
   except Exception as e:
      raise vim.fault.HostConnectFault(msg=str(e))

   # Get a ticket if we're connecting to localhost and password is not specified
   if host == 'localhost' and not pwd:
      try:
         (user, pwd) = GetLocalTicket(si, user)
      except:
         pass # This is not supported against vCenter, and connecting
              # with an empty password is fine in debug builds


   # Login
   content.sessionManager.Login(user, pwd, None)
   return si, stub
Ejemplo n.º 17
0
def loginWithTicket(host, port, ticket):
    stub = SoapStubAdapter(host=host,
                           port=port,
                           version="vim.version.version9")
    si = Vim.ServiceInstance("ServiceInstance", stub)
    sm = si.GetContent().GetSessionManager().CloneSession(ticket)
Ejemplo n.º 18
0
def connectToServers(hostConnect=False):
    """
   Creates connections to the vCenter/ESXi, vSAN and DPS/DPD server
   @param hostConnect Host connection. If set to True, connections are made to ESXi and vSAN/Data Protection daemon running in it.
                      If set to False, connections are made to vCenter and vSAN/Data Protection service running in it
   @return vCenter/ESXi server instance, vSAN stub and DPS/DPD stub
   """
    # For python 2.7.9 and later, the default SSL context has stricter
    # connection handshaking rule, hence we are turning off the hostname checking
    # and client side cert verification.
    sslContext = None
    if sys.version_info[:3] > (2, 7, 8):
        sslContext = ssl.create_default_context()
        sslContext.check_hostname = False
        sslContext.verify_mode = ssl.CERT_NONE

    if hostConnect:
        # Create connection to ESXi host to retrieve clone ticket used for login to Data Protection Daemon (DPD)
        hostIp = input('Enter ESXi host IP: ')
        hostUserName = input('Enter ESXi host username: '******'Enter ESXi host password: '******'vsan'),
                sslContext=sslContext)
            vsanStub.cookie = vsphereInstance._stub.cookie
        except Exception as e:
            msg = "ERROR: Could not connect to vSAN service running on ESXi. Exception thrown is \n {0}".format(
                e)
            sys.exit(msg)

        hostSessionManager = vsphereInstance.content.sessionManager
        cloneTicket = hostSessionManager.AcquireCloneTicket()

        # Create stub to DPD and login
        vsandpStub = SoapStubAdapter(host=hostIp,
                                     port=PORT,
                                     path=VSAN_DP_PATH,
                                     version=VSAN_DP_VERSION,
                                     sslContext=sslContext)
        dpdSessionManager = vim.vsandp.host.SessionManager(
            'vsan-dp-session-manager', vsandpStub)
        dpdSessionManager.UserLoginByCloneTicket(cloneTicket, None)
        atexit.register(dpdSessionManager.UserLogout)
    else:
        vcIp = input("Enter vCenter IP address: ")
        username = input('Enter vCenter username: '******'Enter vCenter password: '******'@' + domainName
        # Connect to vCenter
        try:
            vsphereInstance = SmartConnect(host=vcIp,
                                           user=username,
                                           pwd=password,
                                           port=PORT,
                                           path=VSPHERE_PATH,
                                           sslContext=sslContext)
        except vim.InvalidLogin:
            sys.exit("ERROR: Incorrect login provided for vCenter")
        except Exception as e:
            msg = "ERROR: Could not connect to vCenter. Exception thrown is \n {0}".format(
                e)
            sys.exit(msg)
        atexit.register(Disconnect, vsphereInstance)

        # Create vSAN stub
        try:
            vsanStub = SoapStubAdapter(
                host=vcIp,
                port=PORT,
                path=VSAN_VC_PATH,
                version=VmomiSupport.newestVersions.Get('vsan'),
                sslContext=sslContext)
            vsanStub.cookie = vsphereInstance._stub.cookie
        except Exception as e:
            msg = "ERROR: Could not connect to vCenter side vSAN server. Exception thrown is \n {0}".format(
                e)
            sys.exit(msg)

        try:
            # Create stub to Data Protection Service (DPS)
            vsandpStub = SoapStubAdapter(host=vcIp,
                                         port=PORT,
                                         path=VSAN_DP_PATH,
                                         version=VSAN_DP_VERSION,
                                         sslContext=sslContext)
            authenticator = sso.SsoAuthenticator(
                sts_url=STS_URL_TEMPLATE % vcIp + domainName)
            bearer = authenticator.get_bearer_saml_assertion(
                username,
                password,
                delegatable=True,
                token_duration=SAML_TOKEN_DURATION,
                ssl_context=sslContext)
            vsandpStub.samlToken = bearer
            sessionManager = vim.vsandp.dps.SessionManager(
                'vsan-dp-session-manager', vsandpStub)
            sessionManager.VsanDpsLoginByToken(
                'en')  # User can login using non-English locale if needed
        except Exception as e:
            msg = "ERROR: Could not connect to DPS server. Exception thrown is \n {0}".format(
                e)
            sys.exit(msg)
        atexit.register(sessionManager.VsanDpsLogout)

    return (vsphereInstance, vsanStub, vsandpStub)
Ejemplo n.º 19
0
 def test1_Connect2HostdOverSOAP(self):
     """
   Verify connection to hostd over soap over tcp.
   """
     self._cnx = SoapStubAdapter(self._host, self._port, ns=self._ver)