Beispiel #1
0
    def get_servers(self, provider):
        """ Gets various information about the servers so it can be returned to provider_data. The format of the data for each server follows the same format as in the base driver description """

        service_server = connect.SmartConnect(host=provider['provider_ip'],
                                              user=provider['username'],
                                              port=int(provider['port']),
                                              pwd=provider['password'],
                                              protocol=provider['protocol'])

        servers = []
        datacenter = self.get_datacenter(provider)

        content = service_server.RetrieveContent()
        vmFolder = datacenter.vmFolder
        vmList = vmFolder.childEntity
        #        for vm in vmList:
        #            print ('Instance is : ', {
        #                'hostname' : vm.name,
        #                'ip' : vm.guest.ipAddress ,
        #                'size' : 'va-small',
        #                'used_disk' : vm.summary.storage.committed,
        #                'used_ram' : vm.summary.quickStats.hostMemoryUsage,
        #                'used_cpu' : vm.summary.quickStats.overallCpuUsage,
        #                'status' : vm.overallStatus,
        #                'provider' : provider['provider_name'],
        #            })

        for vm in vmList:
            server = {
                'hostname': vm.name,
                'ip': vm.guest.ipAddress,
                'size': 'va-small',
                'status': vm.overallStatus,
                'provider': provider['provider_name'],
                'used_disk': vm.summary.storage.committed,
                'used_ram': vm.summary.quickStats.hostMemoryUsage,
                'used_cpu': vm.summary.quickStats.overallCpuUsage,
            }

            for key in [('used_disk', 2**30), ('used_ram', 2**20),
                        ('used_cpu', 1)]:
                if not server[key[0]]: server[key[0]] = 0
                else:
                    server[key[0]] = round((0.0 + server[key[0]]) / key[1], 2)
#                server[key[0]] = 0 if not server[key[0]] else float(server[key[0]]) / key[1]
            servers.append(server)
        raise tornado.gen.Return(servers)
    def test_vm_nic_data(self):
        data = {
            'ESXi-5.5-16': [],
            'ESXi-5.5-17': [],
            'ESXi-5.5-18': [],
            'ESXi11': ['00:0c:29:e1:e0:f8'],
            'ESXi12': ['00:50:56:b4:3c:3c'],
            'ESXi20': ['00:50:56:b4:fc:9b', '00:50:56:b4:28:e7'],
            'ESXi21': ['00:50:56:b4:8d:7a', '00:50:56:b4:39:b8'],
            'ESXi22': ['00:0c:29:36:b5:5a', '00:0c:29:36:b5:64'],
            'ESXi23': ['00:50:56:b4:91:f9', '00:50:56:b4:90:9f'],
            'ESXi38-v5.0': ['00:0c:29:ce:6a:d8', '00:0c:29:ce:6a:e2'],
            'MARVEL-Agents_of_Atlas': [],
            'MARVEL-Alex_Power': [],
            'MARVEL-Archangel': [],
            'MARVEL-Freak': [],
            'MARVEL-Hepzibah': [],
            'MARVEL-Mach_IV': [],
            'MARVEL-Serpent_Society': [],
            'MARVEL-Spectrum': [],
            'MARVEL-The_Hand': [],
            'MARVEL-Vanisher_(Ultimate)': [],
            'VCVA-5.5u1-11': ['00:0c:29:9d:a3:8c'],
            'VCVA-5.5u1-14': ['00:0c:29:75:21:2e'],
            'VCVA33': ['00:0c:29:e3:f9:f7'],
            'VCVA36': ['00:0c:29:44:8b:76'],
            'VCVA37-v5.0': ['00:50:56:b4:89:db'],
            'box': ['00:50:56:82:28:7d'],
            'box_copy': ['00:50:56:82:34:02'],
            'esx4.1.0': ['00:0c:29:1f:ec:ba', '00:0c:29:1f:ec:c4']
        }

        # see: http://python3porting.com/noconv.html
        si = connect.SmartConnect(host='vcsa',
                                  user='******',
                                  pwd='my_password')

        content = si.RetrieveContent()
        virtual_machines = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.VirtualMachine], True)
        for virtual_machine in virtual_machines.view:
            name = virtual_machine.name
            self.assertTrue(name in data.keys())
            macs = data[name]
            if virtual_machine.guest:
                for net in virtual_machine.guest.net:
                    self.assertTrue(net.macAddress in macs)
Beispiel #3
0
def main():
    """
    Simple command-line program for listing the vms in a foler.
    """

    args = get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        print " "
        session_name = service_instance.content.sessionManager.currentSession.fullName
        print "Hello {}".format(session_name)
        print "You have successfully logged into {}".format(args.host)
        # NOTE (hartsock): only a successfully authenticated session has a
        # session key aka session id.
        print " "
        print " "

        # Print list of VMs in the specified folder
        VM = args.vm
        # This dumps all of the vCenter data into an object
        content = service_instance.RetrieveContent()
        # get_obj is defined above. It searchs through the content for the specified folder
        # It returns a folder object
        vm = get_obj(content, [vim.VirtualMachine], VM)
        # If the folder was found list it's contents
        if vm is not None:
            # We will add all of the childObjects of the folder to a variable
            #s = folder.childEntity
            # Iterate through the VMs in the folder printing the names
            #for vm in vms:
            print(vm.summary)
        else:
            print VM, "not found"

    except vmodl.MethodFault as error:
        #print "Caught vmodl fault : " + error.msg
        print error.msg
        return -1

    return 0
Beispiel #4
0
def connect_to_api(module, disconnect_atexit=True):
    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    validate_certs = module.params['validate_certs']

    if validate_certs and not hasattr(ssl, 'SSLContext'):
        module.fail_json(
            msg=
            'pyVim does not support changing verification mode with python < 2.7.9. Either update '
            'python or or use validate_certs=false')

    ssl_context = None
    if not validate_certs:
        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        ssl_context.verify_mode = ssl.CERT_NONE

    service_instance = None
    try:
        service_instance = connect.SmartConnect(host=hostname,
                                                user=username,
                                                pwd=password,
                                                sslContext=ssl_context)
    except vim.fault.InvalidLogin as e:
        module.fail_json(
            msg="Unable to log on to vCenter or ESXi API at %s as %s: %s" %
            (hostname, username, e.msg))
    except (requests.ConnectionError, ssl.SSLError) as e:
        module.fail_json(
            msg="Unable to connect to vCenter or ESXi API at %s on TCP/443: %s"
            % (hostname, e))
    except Exception as e:
        module.fail_json(
            msg="Unknown error connecting to vCenter or ESXi API at %s: %s" %
            (hostname, e))

    if service_instance is None:
        module.fail_json(
            msg="Unknown error connecting to vCenter or ESXi API at %s" %
            hostname)

    # Disabling atexit should be used in special cases only.
    # Such as IP change of the ESXi host which removes the connection anyway.
    # Also removal significantly speeds up the return of the module
    if disconnect_atexit:
        atexit.register(connect.Disconnect, service_instance)
    return service_instance.RetrieveContent()
    def _connect(self):

        try:
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_NONE
            self.service_instance = connect.SmartConnect(host=self.vCenterIp,
                                                         user=self.userName,
                                                         pwd=self.password,
                                                         port=443,
                                                         sslContext=context)
            atexit.register(connect.Disconnect, self.service_instance)
            #atexit.register(endit)
        except IOError as e:
            pass

        if not self.service_instance:
            raise SystemExit("Unable to connect to host with supplied info.")
Beispiel #6
0
def main():
    """
    Simple command-line program for executing a process in the VM without the
    network requirement to actually access it.
    """

    args = get_args()
    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()

        vm = content.searchIndex.FindByUuid(None, args.vm_uuid, True)
        tools_status = vm.guest.toolsStatus
        if (tools_status == 'toolsNotInstalled'
                or tools_status == 'toolsNotRunning'):
            raise SystemExit(
                "VMwareTools is either not running or not installed. "
                "Rerun the script after verifying that VMwareTools "
                "is running")

        creds = vim.vm.guest.NamePasswordAuthentication(username=args.vm_user,
                                                        password=args.vm_pwd)

        try:
            pm = content.guestOperationsManager.processManager

            ps = vim.vm.guest.ProcessManager.ProgramSpec(
                programPath=args.path_to_program,
                arguments=args.program_arguments)
            res = pm.StartProgramInGuest(vm, creds, ps)

            if res > 0:
                print "Program executed, PID is %d" % res

        except IOError, e:
            print e
    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0
Beispiel #7
0
def get_vms(config):
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_NONE
    service_instance = connect.SmartConnect(host=config["host"],
                                            user=config["user"],
                                            pwd=config["pass"],
                                            port=config["port"],
                                            sslContext=context)

    content = service_instance.RetrieveContent()
    container = content.rootFolder  # starting point to look into
    view_type = [vim.VirtualMachine]  # object types to look for
    recursive = True  # whether we should look into it recursively
    container_view = content.viewManager.CreateContainerView(
        container, view_type, recursive)

    return container_view.view
Beispiel #8
0
    def _vc_login(self):
        try:
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_NONE
            service_instance = connect.SmartConnect(
                host=self.vc_dns,
                user=self.vc_password_id.user,
                pwd=self.vc_password_id.decrypt()[0],
                port=self.vc_port,
                sslContext=context)

            #			atexit.register(connect.Disconnect, service_instance)
            #			pdb.set_trace()
            #			raise Warning ("Login OK")
            return service_instance
        except vmodl.MethodFault as error:
            raise Warning("Caught vmodl fault :", error.msg)
Beispiel #9
0
def resMatch(conf,rangeVM,name,UCSaction):
    si = connect.SmartConnect(host=name,user=conf.uUser,pwd=conf.uPasswd,sslContext=sslContext)
    content=si.content
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    listVM = []
    listUCS = []      
    for x in container.view:
        listUCS.append(x.name)
    for y in rangeVM:
        listVM.append(conf.vmprefix+"_test"+str(y))  

    for item in listVM:
        if item in listUCS:
            UCSaction[name].append(item)

    atexit.register(connect.Disconnect, si)
    return UCSaction
Beispiel #10
0
 def do_setup(self, context):
     """Any initialization the source driver does while starting."""
     super(VSphereSourceDriver, self).do_setup(context)
     host = self.configuration.vsphere_host
     username = self.configuration.vsphere_username
     password = self.configuration.vsphere_password
     port = self.configuration.vsphere_port
     try:
         self.con = connect.SmartConnect(host=host,
                                         user=username,
                                         pwd=password,
                                         port=port)
         atexit.register(connect.Disconnect, self.con)
         self.content = self.con.RetrieveContent()
     except Exception:
         raise
     self._initialized = True
Beispiel #11
0
def list_datastore_space():
    """
    List all datastores and their free space
    """
    sslContext = None

    if VMWARE_DISABLE_SSL:
        sslContext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sslContext.verify_mode = ssl.CERT_NONE

    try:
        service_instance = connect.SmartConnect(host=VMWARE_HOST,
                                                user=VMWARE_USER,
                                                pwd=VMWARE_PASS,
                                                sslContext=sslContext)
        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()
        # Search for all Datastores
        objview = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.Datastore], True)
        datastores = objview.view
        objview.Destroy()

        datastore_space = {}
        for datastore in datastores:
            capacity = datastore.summary.capacity
            freeSpace = datastore.summary.freeSpace
            datastore_details = {
                'capacity': print_size(capacity),
                'free': print_size(freeSpace),
                'used': print_size(capacity - freeSpace),
                'pfree': "%2.2f" % (freeSpace * 100.0 / capacity)
            }
            datastore_space[datastore.summary.name] = datastore_details

        return datastore_space

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1
    def get_si(self):
        """
        Get Service Instance from VCenter
        :return:
        """
        try:
            default_context = ssl._create_default_https_context
            ssl._create_default_https_context = ssl._create_unverified_context
            self.si = connect.SmartConnect(host=self.envs['vsphere_url'],
                                           user=self.envs['vsphere_user'],
                                           pwd=self.envs['vsphere_pass'],
                                           port=self.envs['vsphere_port'])
            ssl._create_default_https_context = default_context

        except vmodl.MethodFault as error:
            print "Caught vmodl fault : " + error.msg
            raise
Beispiel #13
0
def main():
    parser = argparse.ArgumentParser(description='vCenter login')
    parser.add_argument('-s',
                        '--host',
                        required=True,
                        action='store',
                        help='vSphere IP')
    parser.add_argument('-o',
                        '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='vSphere Port')
    parser.add_argument('-u',
                        '--user',
                        required=True,
                        action='store',
                        help='User name')
    parser.add_argument('-p',
                        '--password',
                        required=True,
                        action='store',
                        help='Password')
    parser.add_argument('-n',
                        '--name',
                        required=True,
                        action='store',
                        help='Resourcepool name')

    args = parser.parse_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
        atexit.register(connect.Disconnect, service_instance)

        libvmtask.resourcepool_destroy(service_instance,
                                       libvmtask.validate_input(args.name))

        return 0

    except vmodl.MethodFault as error:
        print("ERROR: " + error.msg)
        sys.exit(1)
Beispiel #14
0
    def _smart_connect(self, instance, service_check_tags):
        # Check for ssl configs and generate an appropriate ssl context object
        ssl_verify = instance.get('ssl_verify', True)
        ssl_capath = instance.get('ssl_capath', None)
        if not ssl_verify:
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_NONE
        elif ssl_capath:
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_REQUIRED
            context.load_verify_locations(capath=ssl_capath)

        # If both configs are used, log a message explaining the default
        if not ssl_verify and ssl_capath:
            self.log.debug("Your configuration is incorrectly attempting to "
                           "specify both a CA path, and to disable SSL "
                           "verification. You cannot do both. Proceeding with "
                           "disabling ssl verification.")

        try:
            # Object returned by SmartConnect is a ServerInstance
            #   https://www.vmware.com/support/developer/vc-sdk/visdk2xpubs/ReferenceGuide/vim.ServiceInstance.html
            server_instance = connect.SmartConnect(
                host=instance.get('host'),
                user=instance.get('username'),
                pwd=instance.get('password'),
                sslContext=context if not ssl_verify or ssl_capath else None
            )
        except Exception as e:
            err_msg = "Connection to {} failed: {}".format(instance.get('host'), e)
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                               tags=service_check_tags, message=err_msg)
            raise ConnectionError(err_msg)

        # Check that we have sufficient permission for the calls we need to make
        try:
            server_instance.CurrentTime()
        except Exception as e:
            err_msg = (
                "A connection to {} can be established, but performing operations on the server fails: {}"
            ).format(instance.get('host'), e)
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                               tags=service_check_tags, message=err_msg)
            raise ConnectionError(err_msg)

        return server_instance
Beispiel #15
0
def esxi_shutdown(host, ip):
    try:
        logger.debug('Host: %s, IP: %s, Port: %s' % (host, ip, esxi_port))
        esxi_instance = connect.SmartConnect(host=ip,
                                             user=esxi_user,
                                             pwd=esxi_pass,
                                             port=int(esxi_port))
        if not esxi_instance:
            msg = 'Could not connect to the host: %s, %s' % (host, ip)
            logger.error(msg)
            return False, msg
        atexit.register(connect.Disconnect, esxi_instance)

        content = esxi_instance.RetrieveContent()
        object_view = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.HostSystem], True)
        l_hosts = object_view.view
        object_view.Destroy()
        print l_hosts[0].summary

##       Enter MaintenanceMode
#        try:
#            main_mode = l_hosts[0].EnterMaintenanceMode_Task(5)
#            logger.debug('EnterMaintenanceMode_Task excuted'+str(main_mode))
#        except vim.fault.Timedout as err:
#            msg = "Caught vim fault: %s" % err.msg
#            logger.exception(msg)
#            return False, msg
#        time.sleep(30)
##       Shutdown esxi host
#        try:
#            shutdown_ = l_hosts[0].ShutdownHost_Task(True)
#            logger.debug('shutdown esxi host'+str(shutdown_))
#        except vmodl.fault.NotSupported as err:
#            msg = "Caught vmodl fault: %s" % err.msg
#            logger.exception(msg)
#            return False, msg
#
    except vmodl.MethodFault as err:
        msg = "Caught vmodl fault: %s" % err.msg
        logger.exception(msg)
        return False, msg
    except Exception as err:
        msg = "Caught exception: %s" % str(err)
        logger.exception(msg)
        return False, msg
Beispiel #16
0
def initialize(template, config_file):
    si = connect.SmartConnect(host='10.51.16.61', user='******', pwd='xxx')
    inv=si.RetrieveContent()
    DC=inv.rootFolder.childEntity[0]
    vm=DC.vmFolder
    NETWORK=DC.network
    vm_obj=[i for i in vm.childEntity if i.name == '%s' %template][0] 
    conf1=ConfigObj('%s' %config_file,unrepr=True)
    print conf1.keys()
    i=0
     
    for vm_type in conf1.keys()[1:]:
        for vm_name in conf1['%s' %vm_type]:
            clonespec=create_spec(config_file,vm_type,vm_name, DC,NETWORK )
            task = vm_obj.Clone(folder=vm, name = '%s' %vm_name, spec=clonespec)
            result = WaitTask(task, 'Create %s from template: %s' %(vm_name,template) )
            print result
Beispiel #17
0
def main():
	parser = argparse.ArgumentParser(description='vCenter login')
	parser.add_argument('-s', '--host', required=True, action='store', help='vSphere IP')
	parser.add_argument('-o', '--port', type=int, default=443, action='store', help='vSphere Port')
	parser.add_argument('-u', '--user', required=True, action='store', help='User name')
	parser.add_argument('-p', '--password', required=True, action='store', help='Password')
	parser.add_argument('-n', '--name', required=False, action='store', help='VM name')
	args = parser.parse_args()

	try:
		service_instance = connect.SmartConnect(host=args.host,
												user=args.user,
												pwd=args.password,
												port=int(args.port))
		atexit.register(connect.Disconnect, service_instance)


		if args.name:

			content = service_instance.content
			objView = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
			vmlist = objView.view
			objView.Destroy()

			for vm in vmlist:
				if vm.name == args.name:
					print "Powering on VM " + vm.name
					task = vm.PowerOn()
					libvmtask.WaitForTasks([task], service_instance)
					print "Powered on VM " + vm.name

					#libvmtask.list_files(service_instance, '*.vmdk')
					#libvmtask.list_files(service_instance, '*.iso')
					#libvmtask.detach_disk(vm, service_instance, '[NAS] hulli/hulli.vmdk')
					#libvmtask.attach_disk(vm, service_instance, '[NAS] hulli/hulli.vmdk')

		else:
			raise SystemExit("Please provide a VM name")


		return 0

	except vmodl.MethodFault as error:
		print("ERROR: " + error.msg)
		sys.exit(1)
Beispiel #18
0
def main():
    parser = argparse.ArgumentParser(description='vCenter login')
    parser.add_argument('-s',
                        '--host',
                        required=True,
                        action='store',
                        help='vSphere IP')
    parser.add_argument('-o',
                        '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='vSphere Port')
    parser.add_argument('-u',
                        '--user',
                        required=True,
                        action='store',
                        help='User name')
    parser.add_argument('-p',
                        '--password',
                        required=False,
                        action='store',
                        help='Password')
    parser.add_argument('-n',
                        '--name',
                        required=False,
                        action='store',
                        help='VM Name to list')
    args = parser.parse_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()

        libvmtask.list_files(service_instance, "*.iso")

        return 0

    except vmodl.MethodFault as error:
        print("ERROR: " + error.msg)
        sys.exit(1)
def main():
    """
   Simple command-line program demonstrating vSphere perfManager API
   """

    args = get_args()
    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        search_index = content.searchIndex
        # quick/dirty way to find an ESXi host
        host = search_index.FindByDnsName(dnsName=args.vihost, vmSearch=False)

        perfManager = content.perfManager
        metricId = vim.PerformanceManager.MetricId(counterId=6, instance="*")
        startTime = datetime.datetime.now() - datetime.timedelta(hours=1)
        endTime = datetime.datetime.now()

        query = vim.PerformanceManager.QuerySpec(maxSample=1,
                                                 entity=host,
                                                 metricId=[metricId],
                                                 startTime=startTime,
                                                 endTime=endTime)

        print(perfManager.QueryPerf(querySpec=[query]))

    except vmodl.MethodFault as e:
        print("Caught vmodl fault : " + e.msg)
        return -1
    except Exception as e:
        print("Caught exception : " + str(e))
        return -1

    return 0
Beispiel #20
0
def detail(request, server_id):
    server1 = get_object_or_404(server, pk=server_id)
    
    
    vms.objects.filter(server=server1).delete()
    
    sslContext = None
    sslContext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    sslContext.verify_mode = ssl.CERT_NONE
    try:
        service_instance = connect.SmartConnect(host=server1.IP_addr,user=server1.user,pwd=server1.passwd,port=443,sslContext=sslContext)
        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()
        container = content.rootFolder  # starting point to look into
        viewType = [vim.VirtualMachine]  # object types to look for
        recursive = True  # whether we should look into it recursively
        containerView = content.viewManager.CreateContainerView(
            container, viewType, recursive)

        children = containerView.view
        for child in children:
            summary = child.summary
            Moid = int(re.search(r'\d+', str(child)).group())
            Name = summary.config.name
            Guest = summary.config.guestFullName
            CPU = summary.config.numCpu
            Mem = summary.config.memorySizeMB // 1024
            run = summary.runtime.powerState
            if run == "poweredOn":
                run = "y"
            else:
                run = "n"
            #Uuid = summary.config.instanceUuid
            if summary.guest is not None:
                ip_address = summary.guest.ipAddress
                if ip_address:
                    Ipa = ip_address
                else:
                    Ipa = "none"
            server1.vms_set.create(vm_text=Name,moid=Moid,Guest=Guest,CPU=CPU,Mem=Mem,Ipa=Ipa,run=run)
    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)


    return render(request, 'vms/detail.html', {'server': server1})
Beispiel #21
0
def main():
    args = get_args()
    ovfd = get_ovf_descriptor(args.ovf_path)
    try:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.verify_mode = ssl.CERT_NONE
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port,
                                  sslContext=context)
    except:
        print "Unable to connect to %s" % args.host
        exit(1)
    objs = get_objects(si, args)
    manager = si.content.ovfManager
    spec_params = vim.OvfManager.CreateImportSpecParams()
    import_spec = manager.CreateImportSpec(ovfd,
                                           objs["resource pool"],
                                           objs["datastore"],
                                           spec_params)
    lease = objs["resource pool"].ImportVApp(import_spec.importSpec,
                                             objs["datacenter"].vmFolder)
    while(True):
        if (lease.state == vim.HttpNfcLease.State.ready):
            # Assuming single VMDK.
            url = lease.info.deviceUrl[0].url.replace('*', args.host)
            # Spawn a dawmon thread to keep the lease active while POSTing
            # VMDK.
            keepalive_thread = Thread(target=keep_lease_alive, args=(lease,))
            keepalive_thread.start()
            # POST the VMDK to the host via curl. Requests library would work
            # too.
            curl_cmd = (
                "curl -Ss -X POST --insecure -T %s -H 'Content-Type: \
                application/x-vnd.vmware-streamVmdk' %s" %
                (args.vmdk_path, url))
            system(curl_cmd)
            lease.HttpNfcLeaseComplete()
            keepalive_thread.join()
            return 0
        elif (lease.state == vim.HttpNfcLease.State.error):
            print "Lease error: " + lease.state.error
            exit(1)
    connect.Disconnect(si)
    def _vim_connect(self):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = ssl.CERT_NONE

        display.vvv("ESTABLISH VIM CONNECTION FOR USER: %s on PORT %s TO %s" %
                    (self._vim_host_user, self._vim_port, self._vim_host),
                    host=self._vim_host)
        try:
            service_instance = connect.SmartConnect(host=self._vim_host,
                                                    user=self._vim_host_user,
                                                    pwd=self._vim_host_pass,
                                                    port=self._vim_port,
                                                    sslContext=context)
        except vim.fault.InvalidLogin:
            raise AnsibleError("Login failed for user %s" %
                               self._vim_host_user)

        return service_instance
def connectVcenter(host='', user='', password='', port=443):
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE

    service_instance = connect.SmartConnect(host=host,
                                            user=user,
                                            pwd=password,
                                            port=int(port),
                                            sslContext=context)
    if not service_instance:
        logging.info(
            "Unable to connect with the vCenter Server using the provided credentials"
        )
        return False

    atexit.register(connect.Disconnect, service_instance)
    #content = service_instance.RetrieveContent()
    return service_instance
Beispiel #24
0
def vcenter_connection(vcenter, username, password):
    """Returns a vCenter service instance, connected with the given login
    information.
    """
    if not all([vcenter, username, password]):
        LOG.error('vCenter host, username, and password required')
        return None
    try:
        service_instance = connect.SmartConnect(host=vcenter, user=username,
                                                pwd=password,
                                                port=settings.VCENTER_PORT)
    except vim.fault.InvalidLogin as e:
        LOG.error('Could not connect to %s: %s' % (vcenter, e.msg))
        return None
    except requests_exceptions.ConnectionError as e:
        LOG.error('Could not connect to %s: %s' % (vcenter, e.message))
        return None
    return service_instance
def connect_to_vcenter(module, disconnect_atexit=True):
    hostname = module.params['vcenter_hostname']
    username = module.params['vcenter_username']
    password = module.params['vcenter_password']
    port = module.params['vcenter_port']

    try:
        service_instance = connect.SmartConnect(host=hostname,
                                                user=username,
                                                pwd=password,
                                                port=port)

        if disconnect_atexit:
            atexit.register(connect.Disconnect, service_instance)

        return service_instance.RetrieveContent()
    except vim.fault.InvalidLogin, invalid_login:
        module.fail_json(msg=invalid_login.msg, apierror=str(invalid_login))
Beispiel #26
0
    def search_index(self):
        if self._search_index:
            return self._search_index

        # form a connection...
        si = connect.SmartConnect(
            host=self.options.host,
            user=self.options.user,
            pwd=self.options.password,
            port=443,
        )

        # Note: from daemons use a shutdown hook to do this, not the atexit
        atexit.register(connect.Disconnect, si)

        # http://pubs.vmware.com/vsphere-55/topic/com.vmware.wssdk.apiref.doc/vim.SearchIndex.html
        self._search_index = si.content.searchIndex
        return self._search_index
Beispiel #27
0
def vcenter_auth():
    service_instance = None
    try:
        s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        s.verify_mode = ssl.CERT_NONE
        service_instance = connect.SmartConnect(
            host=os.environ["vcenter_host"],
            user=os.environ["vcenter_user"],
            pwd=os.environ["vcenter_password"],
            sslContext=s,
        )
        atexit.register(connect.Disconnect, service_instance)
    except IOError:
        pass

    if not service_instance:
        raise SystemExit("Unable to connect to host with supplied info.")
    return service_instance
Beispiel #28
0
def main():
    # command line
    options = get_options()

    si = connect.SmartConnect(host=options.host, pwd=options.password)
    print("Connected %s" % options.host)

    vmHandle = folder.Find(options.vmname)

    cspec = Vim.Vm.ConfigSpec()
    cspec.messageBusTunnelEnabled = (options.task.lower() == 'enable')
    task = vmHandle.Reconfigure(cspec)
    WaitForTask(task)

    # util.interrogate(vmHandle.config)

    print("messageBusTunnelEnabled: %s" %
          vmHandle.config.messageBusTunnelEnabled)
Beispiel #29
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        container = content.rootFolder  # starting point to look into
        viewType = [vim.VirtualMachine]  # object types to look for
        recursive = True  # whether we should look into it recursively
        containerView = content.viewManager.CreateContainerView(
            container, viewType, recursive)

        children = containerView.view
        if args.find is not None:
            pat = re.compile(args.find, re.IGNORECASE)
        for child in children:
            if args.find is None:
                print_vm_info(child)
            else:
                if pat.search(child.summary.config.name) is not None:
                    print_vm_info(child)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
Beispiel #30
0
    def get_datastores(self, data):
        """
        Get datastores from VMWare.
        """
        try:
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            ssl_context.verify_mode = ssl.CERT_NONE
            server_instance = connect.SmartConnect(
                host=data['hostname'],
                user=data['username'],
                pwd=data['password'],
                sslContext=ssl_context,
            )
        except vim.fault.InvalidLogin as e:
            raise CallError(e.msg, errno.EPERM)
        except socket.gaierror as e:
            raise CallError(str(e), e.errno)

        content = server_instance.RetrieveContent()
        objview = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.HostSystem], True)

        esxi_hosts = objview.view
        objview.Destroy()

        datastores = {}
        for esxi_host in esxi_hosts:
            storage_system = esxi_host.configManager.storageSystem
            datastores_host = {}
            for host_mount_info in storage_system.fileSystemVolumeInfo.mountInfo:
                if host_mount_info.volume.type != 'VMFS':
                    continue

                datastores_host[host_mount_info.volume.name] = {
                    'uuid': host_mount_info.volume.uuid,
                    'capacity': host_mount_info.volume.capacity,
                    'vmfs_version': host_mount_info.volume.version,
                    'local': host_mount_info.volume.local,
                    'ssd': host_mount_info.volume.ssd
                }
            datastores[esxi_host.name] = datastores_host

        connect.Disconnect(server_instance)
        return datastores