def soap_login(options):
	run_delay(options)

	if options.has_key("--ssl"):
		url = "https://"
	else:
		url = "http://"

	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		conn = Client(url + "/vimService.wsdl")
		conn.set_options(location = url)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except Exception:
		fail(EC_LOGIN_DENIED)

	options["ServiceContent"] = ServiceContent
	options["mo_SessionManager"] = mo_SessionManager
	return conn
    def connect(self, timeout=1800):
        from .client import Client
        from .transport import HttpAuthenticated
        if self.connected:
            return

        self.client = Client(self.server, timeout=timeout)
        transport = HttpAuthenticated(proxy=self.proxy,
                                      certfile=self.certfile,
                                      keyfile=self.keyfile)
        self.client.client.set_options(transport=transport)
        # create the Service Instance managed object
        ref = Property('ServiceInstance')
        ref._type = 'ServiceInstance'
        self.service_instance = ServiceInstance(self,
                                                name='ServiceInstance',
                                                ref=ref)

        # get the service content
        self.service_content = self.service_instance.RetrieveServiceContent()
        self.property_collector = self.service_content.propertyCollector
        self.session_manager = self.service_content.sessionManager

        self.root = self.service_content.rootFolder
        self.connected = True
def get_object_list_by_folder(client, ServiceContent, folder_name, object_type, fields):

    folder_id = find_object_id_by_name(client, ServiceContent, "Folder", folder_name)
    folder = get_object(client, ServiceContent, "Folder", folder_id, ["name"])

    # for vm in list['childEntity']['ManagedObjectReference']:
    # if vm['_type']=="VirtualMachine":
    #    print vm['value']
    # return folder

    FolderTraversalSpec, DatacenterVMTraversalSpec = select_traversal_spec(client, ServiceContent)

    mo_RootFolder = Property(folder_id)
    mo_RootFolder._type = "Folder"

    objSpec = client.factory.create("ns0:ObjectSpec")
    objSpec.obj = mo_RootFolder
    objSpec.selectSet = [FolderTraversalSpec, DatacenterVMTraversalSpec]

    pfs = client.factory.create("ns0:PropertyFilterSpec")
    pfs.propSet = [select_object_attributes(client, object_type, fields)]
    pfs.objectSet = [objSpec]

    objContent = get_object_properties(client, ServiceContent, pfs)

    list = map(properties_to_dict, objContent)

    return list
def soap_login(options):
	run_delay(options)

	if options.has_key("--ssl") or options.has_key("--ssl-secure") or options.has_key("--ssl-insecure"):
		if options.has_key("--ssl-insecure"):
			verify = False
		else:
			verify = True
		url = "https://"
	else:
		verify = False
		url = "http://"

	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		headers = {"Content-Type" : "text/xml;charset=UTF-8", "SOAPAction" : ""}
		conn = Client(url + "/vimService.wsdl", location=url, transport=RequestsTransport(verify=verify), headers=headers)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except requests.exceptions.SSLError, ex:
		fail_usage("Server side certificate verification failed")
Exemple #5
0
 def get_mor(mor_type):
     '''
     Fetch the VIM Managed Object Reference
     :param mor_type: The type of the object
     :return:
     '''
     mor = Property(mor_type)
     mor._type = mor_type
     return mor
Exemple #6
0
 def _build_property(property_name, value=None):
     """
     Create a property object with given name and value
     """
     new_property = Property(property_name)
     new_property._type = property_name
     if value is not None:
         new_property.value = value
     return new_property
Exemple #7
0
 def _build_property(self, property_name, value=None):
     """
     Create a property object with given name and value
     """
     new_property = Property(property_name)
     new_property._type = property_name
     if value is not None:
         new_property.value = value
     return new_property
Exemple #8
0
 def connect(self):
     from .client import SmsClient
     from suds.sax.element import Element
     self.client = SmsClient(self._vim.server_fqdn)
     session = eval(list(self._vim.client.client.options.transport.cookiejar)[0].value)
     cookie = Element("vcSessionCookie")
     cookie.setText(session)
     self.client.wsdl.options.__pts__.set("soapheaders", cookie)
     ref = Property('ServiceInstance')
     ref._type = 'ServiceInstance'
     self.service_instance = SmsServiceInstance(self, name='ServiceInstance', ref=ref)
     self.connected = True
def set_power_status(conn, options):
	mo_SearchIndex = Property(options["ServiceContent"].searchIndex.value)
	mo_SearchIndex._type = "SearchIndex"
	vm = conn.service.FindByUuid(mo_SearchIndex, vmSearch = 1, uuid = options["--uuid"])

	mo_machine = Property(vm.value)
	mo_machine._type = "VirtualMachine"
	
	if options["--action"] == "on":
		conn.service.PowerOnVM_Task(mo_machine)
	else:
		conn.service.PowerOffVM_Task(mo_machine)	
def select_object_spec(client, ServiceContent):

    FolderTraversalSpec, DatacenterVMTraversalSpec = select_traversal_spec(client, ServiceContent)

    # Object Spec
    mo_RootFolder = Property(ServiceContent.rootFolder.value)
    mo_RootFolder._type = "Folder"

    objSpec = client.factory.create("ns0:ObjectSpec")
    objSpec.obj = mo_RootFolder
    objSpec.selectSet = [FolderTraversalSpec, DatacenterVMTraversalSpec]

    return objSpec
 def connect(self):
     from .client import SmsClient
     from suds.sax.element import Element
     self.client = SmsClient("{0}:8443".format(self._vim.server_fqdn))
     session = eval(
         list(self._vim.client.client.options.transport.cookiejar)[0].value)
     cookie = Element("vcSessionCookie")
     cookie.setText(session)
     self.client.wsdl.options.__pts__.set("soapheaders", cookie)
     ref = Property('ServiceInstance')
     ref._type = 'ServiceInstance'
     self.service_instance = SmsServiceInstance(self,
                                                name='ServiceInstance',
                                                ref=ref)
     self.connected = True
Exemple #12
0
    def connect(self, timeout=1800):
        if self.connected:
            return
        
        self.client = Client(self.server, timeout=timeout)
        
        # create the Service Instance managed object
        ref = Property('ServiceInstance')
        ref._type = 'ServiceInstance'
        self.service_instance = ServiceInstance(self, name='ServiceInstance', ref=ref)

        # get the service content
        self.service_content = self.service_instance.RetrieveServiceContent()
        self.property_collector = self.service_content.propertyCollector
        self.session_manager = self.service_content.sessionManager

        self.root = self.service_content.rootFolder
        self.connected = True
def soap_login(options):
	run_delay(options)

	if "--ssl" in options or "--ssl-secure" in options or "--ssl-insecure" in options:
		if "--ssl-insecure" in options:
			import ssl
			from requests.packages.urllib3.exceptions import InsecureRequestWarning
			if hasattr(ssl, '_create_unverified_context'):
				ssl._create_default_https_context = ssl._create_unverified_context
			requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
			verify = False
		else:
			verify = True
		url = "https://"
	else:
		verify = False
		url = "http://"

	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		headers = {"Content-Type" : "text/xml;charset=UTF-8", "SOAPAction" : ""}
		conn = Client(url + "/vimService.wsdl", location=url, transport=RequestsTransport(verify=verify), headers=headers)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except requests.exceptions.SSLError as ex:
		fail_usage("Server side certificate verification failed")
	except Exception:
		fail(EC_LOGIN_DENIED)

	options["ServiceContent"] = ServiceContent
	options["mo_SessionManager"] = mo_SessionManager
	return conn
def soap_login(options):
	if options.has_key("--ssl"):
		url = "https://"
	else:
		url = "http://"
	
	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"
	try:
		conn = Client(url + "/vimService.wsdl")
		conn.set_options(location = url)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		SessionManager = conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except Exception, ex:
		fail(EC_LOGIN_DENIED)	
Exemple #15
0
    def connect(self, timeout=1800):
        from .client import Client
        from .transport import HttpAuthenticated
        if self.connected:
            return

        self.client = Client(self.server, timeout=timeout)
        transport = HttpAuthenticated(proxy=self.proxy, certfile=self.certfile, keyfile=self.keyfile)
        self.client.client.set_options(transport=transport)
        # create the Service Instance managed object
        ref = Property('ServiceInstance')
        ref._type = 'ServiceInstance'
        self.service_instance = ServiceInstance(self, name='ServiceInstance', ref=ref)

        # get the service content
        self.service_content = self.service_instance.RetrieveServiceContent()
        self.property_collector = self.service_content.propertyCollector
        self.session_manager = self.service_content.sessionManager

        self.root = self.service_content.rootFolder
        self.connected = True
def set_power_status(conn, options):
	mo_SearchIndex = Property(options["ServiceContent"].searchIndex.value)
	mo_SearchIndex._type = "SearchIndex"
	vm = conn.service.FindByUuid(mo_SearchIndex, vmSearch=1, uuid=options["--uuid"])

	mo_machine = Property(vm.value)
	mo_machine._type = "VirtualMachine"

	try:
		if options["--action"] == "on":
			conn.service.PowerOnVM_Task(mo_machine)
		else:
			conn.service.PowerOffVM_Task(mo_machine)
	except suds.WebFault as ex:
		if (str(ex).find("Permission to perform this operation was denied")) >= 0:
			fail(EC_INVALID_PRIVILEGES)
		else:
			if options["--action"] == "on":
				fail(EC_WAITING_ON)
			else:
				fail(EC_WAITING_OFF)
def client_init(url, username, password):

    logging.basicConfig(level=logging.INFO)
    logging.getLogger("suds.client").setLevel(logging.INFO)
    logging.getLogger("suds.wsdl").setLevel(logging.INFO)

    client = Client(url + "/sdk/vimService?wsdl")

    client.set_options(location=url + "/sdk")

    mo_ServiceInstance = Property("ServiceInstance")
    mo_ServiceInstance._type = "ServiceInstance"

    ServiceContent = client.service.RetrieveServiceContent(mo_ServiceInstance)

    mo_SessionManager = Property(ServiceContent.sessionManager.value)
    mo_SessionManager._type = "SessionManager"

    SessionManager = client.service.Login(mo_SessionManager, username, password)

    return client, ServiceContent, SessionManager
def soap_login(options):
    run_delay(options)

    if "--ssl" in options or "--ssl-secure" in options or "--ssl-insecure" in options:
        if "--ssl-insecure" in options:
            import ssl
            import urllib3
            if hasattr(ssl, '_create_unverified_context'):
                ssl._create_default_https_context = ssl._create_unverified_context
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
            verify = False
        else:
            verify = True
        url = "https://"
    else:
        verify = False
        url = "http://"

    url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

    tmp_dir = tempfile.mkdtemp()
    tempfile.tempdir = tmp_dir
    atexit.register(remove_tmp_dir, tmp_dir)

    try:
        headers = {
            "Content-Type": "text/xml;charset=UTF-8",
            "SOAPAction": "vim25"
        }
        login_timeout = int(options["--login-timeout"]) or 60
        conn = Client(url + "/vimService.wsdl",
                      location=url,
                      transport=RequestsTransport(verify=verify),
                      headers=headers,
                      timeout=login_timeout)

        mo_ServiceInstance = Property('ServiceInstance')
        mo_ServiceInstance._type = 'ServiceInstance'
        ServiceContent = conn.service.RetrieveServiceContent(
            mo_ServiceInstance)
        mo_SessionManager = Property(ServiceContent.sessionManager.value)
        mo_SessionManager._type = 'SessionManager'

        conn.service.Login(mo_SessionManager, options["--username"],
                           options["--password"])
    except requests.exceptions.SSLError as ex:
        fail_usage("Server side certificate verification failed: %s" % ex)
    except Exception as e:
        logging.error("Server side certificate verification failed: {}".format(
            str(e)))
        fail(EC_LOGIN_DENIED)

    options["ServiceContent"] = ServiceContent
    options["mo_SessionManager"] = mo_SessionManager
    return conn
def get_power_status(conn, options):
	mo_ViewManager = Property(options["ServiceContent"].viewManager.value)
	mo_ViewManager._type = "ViewManager"

	mo_RootFolder = Property(options["ServiceContent"].rootFolder.value)
	mo_RootFolder._type = "Folder"

	mo_PropertyCollector = Property(options["ServiceContent"].propertyCollector.value)
	mo_PropertyCollector._type = 'PropertyCollector'

	ContainerView = conn.service.CreateContainerView(mo_ViewManager, recursive = 1, container = mo_RootFolder, type = ['VirtualMachine'])
	mo_ContainerView = Property(ContainerView.value)
	mo_ContainerView._type = "ContainerView"

	FolderTraversalSpec = conn.factory.create('ns0:TraversalSpec')
	FolderTraversalSpec.name = "traverseEntities"
	FolderTraversalSpec.path = "view"
	FolderTraversalSpec.skip = False
	FolderTraversalSpec.type = "ContainerView"

	objSpec = conn.factory.create('ns0:ObjectSpec')
	objSpec.obj = mo_ContainerView
	objSpec.selectSet = [ FolderTraversalSpec ]
	objSpec.skip = True

	propSpec = conn.factory.create('ns0:PropertySpec')
	propSpec.all = False
	propSpec.pathSet = ["name", "summary.runtime.powerState", "config.uuid"]
	propSpec.type = "VirtualMachine"

	propFilterSpec = conn.factory.create('ns0:PropertyFilterSpec')
	propFilterSpec.propSet = [ propSpec ]
	propFilterSpec.objectSet = [ objSpec ]

	try:
		raw_machines = conn.service.RetrievePropertiesEx(mo_PropertyCollector, propFilterSpec)
	except Exception, ex:
		fail(EC_STATUS)
Exemple #20
0
def soap_login(options):
    run_delay(options)

    if "--ssl" in options or "--ssl-secure" in options or "--ssl-insecure" in options:
        if "--ssl-insecure" in options:
            from requests.packages.urllib3.exceptions import InsecureRequestWarning
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            verify = False
        else:
            verify = True
        url = "https://"
    else:
        verify = False
        url = "http://"

    url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

    tmp_dir = tempfile.mkdtemp()
    tempfile.tempdir = tmp_dir
    atexit.register(remove_tmp_dir, tmp_dir)

    try:
        headers = {"Content-Type": "text/xml;charset=UTF-8", "SOAPAction": ""}
        conn = Client(url + "/vimService.wsdl",
                      location=url,
                      transport=RequestsTransport(verify=verify),
                      headers=headers)

        mo_ServiceInstance = Property('ServiceInstance')
        mo_ServiceInstance._type = 'ServiceInstance'
        ServiceContent = conn.service.RetrieveServiceContent(
            mo_ServiceInstance)
        mo_SessionManager = Property(ServiceContent.sessionManager.value)
        mo_SessionManager._type = 'SessionManager'

        conn.service.Login(mo_SessionManager, options["--username"],
                           options["--password"])
    except requests.exceptions.SSLError as ex:
        fail_usage("Server side certificate verification failed")
    except Exception:
        fail(EC_LOGIN_DENIED)

    options["ServiceContent"] = ServiceContent
    options["mo_SessionManager"] = mo_SessionManager
    return conn
Exemple #21
0
def soap_login(options):
    run_delay(options)

    if options.has_key("--ssl") or options.has_key(
            "--ssl-secure") or options.has_key("--ssl-insecure"):
        if options.has_key("--ssl-insecure"):
            verify = False
        else:
            verify = True
        url = "https://"
    else:
        verify = False
        url = "http://"

    url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

    tmp_dir = tempfile.mkdtemp()
    tempfile.tempdir = tmp_dir
    atexit.register(remove_tmp_dir, tmp_dir)

    try:
        headers = {"Content-Type": "text/xml;charset=UTF-8", "SOAPAction": ""}
        conn = Client(url + "/vimService.wsdl",
                      location=url,
                      transport=RequestsTransport(verify=verify),
                      headers=headers)

        mo_ServiceInstance = Property('ServiceInstance')
        mo_ServiceInstance._type = 'ServiceInstance'
        ServiceContent = conn.service.RetrieveServiceContent(
            mo_ServiceInstance)
        mo_SessionManager = Property(ServiceContent.sessionManager.value)
        mo_SessionManager._type = 'SessionManager'

        conn.service.Login(mo_SessionManager, options["--username"],
                           options["--password"])
    except requests.exceptions.SSLError, ex:
        fail_usage("Server side certificate verification failed")
def set_power_status(conn, options):
    mo_SearchIndex = Property(options["ServiceContent"].searchIndex.value)
    mo_SearchIndex._type = "SearchIndex"
    vm = conn.service.FindByUuid(mo_SearchIndex,
                                 vmSearch=1,
                                 uuid=options["--uuid"])

    mo_machine = Property(vm.value)
    mo_machine._type = "VirtualMachine"

    try:
        if options["--action"] == "on":
            conn.service.PowerOnVM_Task(mo_machine)
        else:
            conn.service.PowerOffVM_Task(mo_machine)
    except suds.WebFault as ex:
        if (str(ex).find("Permission to perform this operation was denied")
            ) >= 0:
            fail(EC_INVALID_PRIVILEGES)
        else:
            if options["--action"] == "on":
                fail(EC_WAITING_ON)
            else:
                fail(EC_WAITING_OFF)
def get_power_status(conn, options):
    mo_ViewManager = Property(options["ServiceContent"].viewManager.value)
    mo_ViewManager._type = "ViewManager"

    mo_RootFolder = Property(options["ServiceContent"].rootFolder.value)
    mo_RootFolder._type = "Folder"

    mo_PropertyCollector = Property(
        options["ServiceContent"].propertyCollector.value)
    mo_PropertyCollector._type = 'PropertyCollector'

    ContainerView = conn.service.CreateContainerView(mo_ViewManager,
                                                     recursive=1,
                                                     container=mo_RootFolder,
                                                     type=['VirtualMachine'])
    mo_ContainerView = Property(ContainerView.value)
    mo_ContainerView._type = "ContainerView"

    FolderTraversalSpec = conn.factory.create('ns0:TraversalSpec')
    FolderTraversalSpec.name = "traverseEntities"
    FolderTraversalSpec.path = "view"
    FolderTraversalSpec.skip = False
    FolderTraversalSpec.type = "ContainerView"

    objSpec = conn.factory.create('ns0:ObjectSpec')
    objSpec.obj = mo_ContainerView
    objSpec.selectSet = [FolderTraversalSpec]
    objSpec.skip = True

    propSpec = conn.factory.create('ns0:PropertySpec')
    propSpec.all = False
    propSpec.pathSet = ["name", "summary.runtime.powerState", "config.uuid"]
    propSpec.type = "VirtualMachine"

    propFilterSpec = conn.factory.create('ns0:PropertyFilterSpec')
    propFilterSpec.propSet = [propSpec]
    propFilterSpec.objectSet = [objSpec]

    try:
        raw_machines = conn.service.RetrievePropertiesEx(
            mo_PropertyCollector, propFilterSpec)
    except Exception as e:
        logging.error("Failed: {}".format(str(e)))
        fail(EC_STATUS)

    (machines, uuid, mappingToUUID) = process_results(raw_machines, {}, {}, {})

    # Probably need to loop over the ContinueRetreive if there are more results after 1 iteration.
    while hasattr(raw_machines, 'token'):
        try:
            raw_machines = conn.service.ContinueRetrievePropertiesEx(
                mo_PropertyCollector, raw_machines.token)
        except Exception as e:
            logging.error("Failed: {}".format(str(e)))
            fail(EC_STATUS)
        (more_machines, more_uuid,
         more_mappingToUUID) = process_results(raw_machines, {}, {}, {})
        machines.update(more_machines)
        uuid.update(more_uuid)
        mappingToUUID.update(more_mappingToUUID)
        # Do not run unnecessary SOAP requests
        if "--uuid" in options and options["--uuid"] in uuid:
            break

    if ["list", "monitor"].count(options["--action"]) == 1:
        return machines
    else:
        if "--uuid" not in options:
            if options["--plug"].startswith('/'):
                ## Transform InventoryPath to UUID
                mo_SearchIndex = Property(
                    options["ServiceContent"].searchIndex.value)
                mo_SearchIndex._type = "SearchIndex"

                vm = conn.service.FindByInventoryPath(mo_SearchIndex,
                                                      options["--plug"])

                try:
                    options["--uuid"] = mappingToUUID[vm.value]
                except KeyError:
                    fail(EC_STATUS)
                except AttributeError:
                    fail(EC_STATUS)
            else:
                ## Name of virtual machine instead of path
                ## warning: if you have same names of machines this won't work correctly
                try:
                    (options["--uuid"], _) = machines[options["--plug"]]
                except KeyError:
                    fail(EC_STATUS)
                except AttributeError:
                    fail(EC_STATUS)

        try:
            if uuid[options["--uuid"]] == "poweredOn":
                return "on"
            else:
                return "off"
        except KeyError:
            fail(EC_STATUS)
def get_power_status(conn, options):
	mo_ViewManager = Property(options["ServiceContent"].viewManager.value)
	mo_ViewManager._type = "ViewManager"

	mo_RootFolder = Property(options["ServiceContent"].rootFolder.value)
	mo_RootFolder._type = "Folder"

	mo_PropertyCollector = Property(options["ServiceContent"].propertyCollector.value)
	mo_PropertyCollector._type = 'PropertyCollector'

	ContainerView = conn.service.CreateContainerView(mo_ViewManager, recursive=1,
			container=mo_RootFolder, type=['VirtualMachine'])
	mo_ContainerView = Property(ContainerView.value)
	mo_ContainerView._type = "ContainerView"

	FolderTraversalSpec = conn.factory.create('ns0:TraversalSpec')
	FolderTraversalSpec.name = "traverseEntities"
	FolderTraversalSpec.path = "view"
	FolderTraversalSpec.skip = False
	FolderTraversalSpec.type = "ContainerView"

	objSpec = conn.factory.create('ns0:ObjectSpec')
	objSpec.obj = mo_ContainerView
	objSpec.selectSet = [FolderTraversalSpec]
	objSpec.skip = True

	propSpec = conn.factory.create('ns0:PropertySpec')
	propSpec.all = False
	propSpec.pathSet = ["name", "summary.runtime.powerState", "config.uuid"]
	propSpec.type = "VirtualMachine"

	propFilterSpec = conn.factory.create('ns0:PropertyFilterSpec')
	propFilterSpec.propSet = [propSpec]
	propFilterSpec.objectSet = [objSpec]

	try:
		raw_machines = conn.service.RetrievePropertiesEx(mo_PropertyCollector, propFilterSpec)
	except Exception:
		fail(EC_STATUS)

	(machines, uuid, mappingToUUID) = process_results(raw_machines, {}, {}, {})

        # Probably need to loop over the ContinueRetreive if there are more results after 1 iteration.
	while hasattr(raw_machines, 'token'):
		try:
			raw_machines = conn.service.ContinueRetrievePropertiesEx(mo_PropertyCollector, raw_machines.token)
		except Exception:
			fail(EC_STATUS)
		(more_machines, more_uuid, more_mappingToUUID) = process_results(raw_machines, {}, {}, {})
		machines.update(more_machines)
		uuid.update(more_uuid)
		mappingToUUID.update(more_mappingToUUID)
		# Do not run unnecessary SOAP requests
		if "--uuid" in options and options["--uuid"] in uuid:
			break

	if ["list", "monitor"].count(options["--action"]) == 1:
		return machines
	else:
		if "--uuid" not in options:
			if options["--plug"].startswith('/'):
				## Transform InventoryPath to UUID
				mo_SearchIndex = Property(options["ServiceContent"].searchIndex.value)
				mo_SearchIndex._type = "SearchIndex"

				vm = conn.service.FindByInventoryPath(mo_SearchIndex, options["--plug"])

				try:
					options["--uuid"] = mappingToUUID[vm.value]
				except KeyError:
					fail(EC_STATUS)
				except AttributeError:
					fail(EC_STATUS)
			else:
				## Name of virtual machine instead of path
				## warning: if you have same names of machines this won't work correctly
				try:
					(options["--uuid"], _) = machines[options["--plug"]]
				except KeyError:
					fail(EC_STATUS)
				except AttributeError:
					fail(EC_STATUS)

		try:
			if uuid[options["--uuid"]] == "poweredOn":
				return "on"
			else:
				return "off"
		except KeyError:
			fail(EC_STATUS)
#    properties of the service instance, that is the various vSphere
#    manager entities and the root folder of the inventory
# 4) Authenticate, ecc ecc
#
#
# NB: use type suds.sudsobjects.property instead of building a
#     ns0:ManagedObjectReference with client.factory.create(), for some
#     unknown reason this method does not works for me!!

location = 'https://esx3/sdk'
url = location + '/vimService?wsdl'

client = Client(url)
client.set_options(location = location)


# Build reference to the Managed Object 'ServiceInstance'
serviceInstance = Property('ServiceInstance')
serviceInstance._type = 'ServiceInstance'

# Retrive all the objects referenced by ServiceInstance
serviceInstanceContent = client.service.RetrieveServiceContent(serviceInstance)

# Build reference to the ManagedObject 'SessionManager'
sessionManager = Property(serviceInstanceContent.sessionManager.value)
sessionManager._type = 'SessionManager'

userSession = client.service.Login(sessionManager, 'root', 'Passw0rd')

print "Login Time: {0}".format( userSession.loginTime )
			fail(EC_STATUS)
		(more_machines, more_uuid, more_mappingToUUID) = process_results(raw_machines, {}, {}, {})
		machines.update(more_machines)
		uuid.update(more_uuid)
		mappingToUUID.update(more_mappingToUUID)
		# Do not run unnecessary SOAP requests
		if options.has_key("--uuid") and options["--uuid"] in uuid:
			break

	if ["list", "monitor"].count(options["--action"]) == 1:
		return machines
	else:
		if options.has_key("--uuid") == False:
			if options["--plug"].startswith('/'):
				## Transform InventoryPath to UUID
				mo_SearchIndex = Property(options["ServiceContent"].searchIndex.value)
				mo_SearchIndex._type = "SearchIndex"
			
				vm = conn.service.FindByInventoryPath(mo_SearchIndex, options["--plug"])
			
				try:
					options["--uuid"] = mappingToUUID[vm.value]
				except KeyError, ex:
					fail(EC_STATUS)
				except AttributeError, ex:
					fail(EC_STATUS)
			else:
				## Name of virtual machine instead of path
				## warning: if you have same names of machines this won't work correctly
				try:
					(options["--uuid"], _) = machines[options["--plug"]]
def get_property_by_name(client, ServiceContent, type, name):
    id = find_object_id_by_name(client, ServiceContent, type, name)
    p = Property(id)
    p._type = type
    return p
def get_object_properties(client, ServiceContent, propFilterSpec):
    mo_PropertyCollector = Property(ServiceContent.propertyCollector.value)
    mo_PropertyCollector._type = "PropertyCollector"
    return client.service.RetrieveProperties(mo_PropertyCollector, propFilterSpec)
#     ns0:ManagedObjectReference with client.factory.create(), for some
#     unknown reason this method does not works for me!!

location = 'https://esx3/sdk'
url = 'file:/home/marco/Documents/Projects/Python-WMware/vimWSDL/vimServiceEsx3.wsdl'

# Build Client object to access the SOAP service
client = Client(url)
client.set_options(location = location)

# Service Connection variable ....just to maintain the naming convention
# used in the document "Designing backup solutions for VMware vSphere"
serviceConnection = client.service

# Build reference to the Managed Object 'ServiceInstance'
serviceInstance_MoRef = Property('ServiceInstance')
serviceInstance_MoRef._type = 'ServiceInstance'

# Retrive the properties of ServiceInstance, this is done by calling the
# RetrieveServiceContent() method which returns a ServiceContent object
serviceContent = serviceConnection.RetrieveServiceContent(serviceInstance_MoRef)

# Build reference to the ManagedObject 'SessionManager'
sessionManager_MoRef = serviceContent.sessionManager

# Login to the service
userSession = serviceConnection.Login(sessionManager_MoRef, 'root', 'Passw0rd')

# Obtain a MoRef to the root folder
rootFolder_MoRef = serviceContent.rootFolder
from tools.vmware_init import client_init, find_object_id_by_name, get_object, get_property_by_name
from secret import username,password
from suds.sudsobject import Property

client, ServiceContent, SessionManager = client_init('https://vmware1.mif', username,password)

folder = get_property_by_name(client, ServiceContent, "Folder", "VIRTUALIZACIJOS PASKAITOS")
tpl = get_property_by_name(client, ServiceContent, "VirtualMachine", "VIRT_LINUX_000_TPL")

locationSpec = client.factory.create('ns0:VirtualMachineRelocateSpec')

locationSpec.host = None
locationSpec.datastore = None
locationSpec.transform = None
pool = Property('resgroup-1405')
pool._type = 'ResourcePool'

locationSpec.pool = pool

cloneSpec = client.factory.create('ns0:VirtualMachineCloneSpec')
cloneSpec.powerOn = True
cloneSpec.template = False
cloneSpec.location = locationSpec
cloneSpec.snapshot = None

start_id = 1

for i in range(start_id, start_id+40):
    client.service.CloneVM_Task(tpl, folder, "VIRT_LINUX_"+str(i).zfill(3)+".A", cloneSpec)
    client.service.CloneVM_Task(tpl, folder, "VIRT_LINUX_"+str(i).zfill(3)+".B", cloneSpec)
#    properties of the service instance, that is the various vSphere
#    manager entities and the root folder of the inventory
# 4) Authenticate, ecc ecc
#
#
# NB: use type suds.sudsobjects.property instead of building a
#     ns0:ManagedObjectReference with client.factory.create(), for some
#     unknown reason this method does not works for me!!

location = 'https://esx3/sdk'
url = location + '/vimService?wsdl'

client = Client(url)
client.set_options(location = location)


# Build reference to the Managed Object 'ServiceInstance'
serviceInstance = Property('ServiceInstance')
serviceInstance._type = 'ServiceInstance'

# Retrive the properties of ServiceInstance, this is done by calling the
# RetrieveServiceContent() method which returns a ServiceContent object
serviceContent = client.service.RetrieveServiceContent(serviceInstance)

# Build reference to the ManagedObject 'SessionManager'
sessionManager = serviceContent.sessionManager

userSession = client.service.Login(sessionManager, 'root', 'Passw0rd')

print "Login Time: {0}".format( userSession.loginTime )