Exemple #1
0
    def post(self, id):
        parser = reqparse.RequestParser()
        parser.add_argument("name")
        parser.add_argument("description")
        parser.add_argument("owner")
        parser.add_argument("location")
        parser.add_argument("power")
        parser.add_argument("OS")
        parser.add_argument("api-key", required=True, help="Missing API key.")
        args = parser.parse_args()

        global apikey

        # Power management
        if (args["power"] == "poweredOn" and len(args) > 0
                and apikey == args["api-key"]):
            connection = connect.ConnectNoSSL("192.168.182.132", 443, "root",
                                              "toasterddos")
            cursor.execute("SELECT `name` FROM `vms` WHERE `id`='" + str(id) +
                           "'")
            vm = getVM(connection.content, cursor.fetchone()["name"])
            vm.PowerOn()
            connect.Disconnect(connection)
            return "On.", 200
        elif (args["power"] == "poweredOff" and len(args) > 0
              and apikey == args["api-key"]):
            connection = connect.ConnectNoSSL("192.168.182.132", 443, "root",
                                              "toasterddos")
            cursor.execute("SELECT `name` FROM `vms` WHERE `id`='" + str(id) +
                           "'")
            vm = getVM(connection.content, cursor.fetchone()["name"])
            vm.PowerOff()
            connect.Disconnect(connection)
            return "Off.", 200
        return "Bad request.", 403
Exemple #2
0
def get_vm_info(host, usr, pwd, vm_name):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name

        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        vm_details = {
            "cpu": vm.config.hardware.numCPU,
            "memory": vm.config.hardware.memoryMB,
            "drive": [],
            "network": []
        }
        for device in vm.config.hardware.device:
            if device.backing is not None:
                if device.deviceInfo.label.find("disk") > 0:
                    vm_details["drive"].append(device.deviceInfo.label)
                elif device.deviceInfo.label.find("adapter") > 0:
                    vm_details["network"].append(device.deviceInfo.label)
                else:
                    pass
        connect.Disconnect(si)
    except Exception, e:
        return "Get VM(%s) details failed!" % vm_name
Exemple #3
0
def esxi_destory_vm(host, usr, pwd, vm_name):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name

        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        if vm.runtime.powerState == "poweredOn":
            task = vm.PowerOffVM_Task()
            tasks.wait_for_tasks(si, [task])

        task = vm.Destroy_Task()
        tasks.wait_for_tasks(si, [task])
        connect.Disconnect(si)
    except Exception, e:
        print e
        return "Destory VM(%s) failed!" % vm_name
Exemple #4
0
 def __del__(self):
     # Disconnect vsphere client
     try:
         connect.Disconnect(self.vsphere_client)
     except Exception as e:
         g.log.error(e)
         raise exceptions.CloudProviderError(e)
Exemple #5
0
def check_credentials(h, u, pw, pt):
    service_instance = 0
    try:
        service_instance = connect.SmartConnect(host=h,
                                                user=u,
                                                pwd=pw,
                                                port=int(pt))

    except vmodl.MethodFault as error:
        print("  failed  - user " + u + " password: "******"* SUCCESS - user " + u + " password: " + pw)
    connect.Disconnect(service_instance)
    return 0
def main():
    args = get_args()

    try:
        ssl = __import__("ssl")
        context = ssl._create_unverified_context()

        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port,
                                  sslContext=context)
    except Exception as e:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port)
    except:
        print "Unable to connect to %s" % args.host
        exit(1)

    content = si.RetrieveContent()

    # Edit Agent VM Settings
    update_agent_vm_setting(content, args.host_name, args.datastore_name,
                            args.network_name)

    connect.Disconnect(si)
def main():
    args = get_args()
    try:
        if is_xenial_or_above():
            ssl = __import__("ssl")
            context = ssl._create_unverified_context()
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port,
                                      sslContext=context)
        else:
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port)
        si_content = si.RetrieveContent()
    except:
        print "Unable to connect to %s" % args.host
        exit(1)
    # get VM object
    vm_obj = get_obj(si_content, [vim.VirtualMachine], args.vm_name)
    if not vm_obj:
        print "VM %s not pressent" % (args.vm_name)
        exit(1)
    if args.pci_nics:
        task = add_pci_nics(args, vm_obj)
        wait_for_task(task)
    if args.sriov_nics:
        task = add_sriov_nics(args, vm_obj, si_content)
        wait_for_task(task)
    connect.Disconnect(si)
Exemple #8
0
def main():
    args = get_args()
    if args.date:
        try:
                dt = datetime.strptime(args.date, '%d/%m/%Y %H:%M')
        except ValueError:
                print('Unrecognized date format')
                raise
                return -1

    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    # try:
    #     si = connect.SmartConnectNoSSL(host=args.host,
    #                                    user=args.user,
    #                                    pwd=password,
    #                                    port=int(args.port))
    # except vim.fault.InvalidLogin:
    #     print("Could not connect to the specified host using specified "
    #           "username and password")
    #     return -1
    si = connect.SmartConnectNoSSL(host=args.host,
                                   user=args.user,
                                   pwd=password,
                                   port=int(args.port))

    atexit.register(connect.Disconnect, si)
    # vm = None
    #
    view = si.content.viewManager.CreateContainerView(si.content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    vms = [vm for vm in view.view if vm.name == args.vmname]

    if not vms:
        print('VM not found')
        connect.Disconnect(si)
        return -1
    vm = vms[0]

    # vm = si.content.searchIndex.FindByDnsName(None, args.vmname,
    #                                           True)

    # spec = vim.scheduler.ScheduledTaskSpec()
    # spec.name = 'PowerOff vm %s' % args.vmname
    # spec.description = 'poweroff vm machine'
    # spec.scheduler = vim.scheduler.OnceTaskScheduler()
    # spec.scheduler.runAt = dt
    # spec.action = vim.action.MethodAction()
    # spec.action.name = vim.VirtualMachine.PowerOff
    # spec.enabled = True

    # si.content.scheduledTaskManager.CreateScheduledTask(vm, spec)

    TASK = vm.PowerOff()
    tasks.wait_for_tasks(si, [TASK])
Exemple #9
0
def get_all_vms(host, usr, pwd):
    vms_list = []
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        for vm in vm_view.view:
            summary = vm.summary
            dt = summary.config.vmPathName.split(" ")[0]
            dt = dt[1:(len(dt) - 1)]
            vm_config = {
                "name": summary.config.name,
                "datastore": dt,
                "status": summary.runtime.powerState[7:],
                "ip": [],
                "uuid": summary.config.instanceUuid
            }
            if len(vm.guest.net) > 0:
                for nic in vm.guest.net:
                    if len(nic.ipAddress) == 0:
                        continue
                    elif len(nic.ipAddress[0]) > 15:
                        pass
                    else:
                        vm_config["ip"].append(nic.ipAddress[0])
            vms_list.append(vm_config)
        connect.Disconnect(si)
    except Exception, e:
        return "Get vms failed!"
 def __del__(self):
     """
     Clean stuff up
     :return:
     """
     if self.si is not None:
         connect.Disconnect(self.si)
Exemple #11
0
def main():
    args = get_args()
    try:
        ssl = __import__("ssl")
        context = ssl._create_unverified_context()

        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port,
                                  sslContext=context)
    except Exception as e:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port)
    except:
        print "Unable to connect to %s" % args.host
        exit(1)

    si_content = si.RetrieveContent()
    # check if PG exists else return error
    dv_switch = get_obj(si_content, [vim.DistributedVirtualSwitch],
                        args.dvs_name)
    if not dv_switch:
        print "dv switch %s not pressent" % (args.dvs_name)
        exit(1)
    dv_pg = get_dvs_pg_obj(si_content, [vim.dvs.DistributedVirtualPortgroup],
                           args.dv_pg_name, args.dvs_name)
    if not dv_pg:
        print "port-group %s not present in dvs %s" % (args.dv_pg_name,
                                                       args.dvs_name)
        exit(1)
    update_dv_pg(args, dv_pg)
    connect.Disconnect(si)
Exemple #12
0
    def smart_connect(self):
        """Creates the connection object to the vSphere API using parameters supplied from the configuration.
        """
        context = None
        if not self.config.ssl_verify:
            context = ssl.SSLContext(ssl.PROTOCOL_TLS)
            context.verify_mode = ssl.CERT_NONE
        elif self.config.ssl_capath:
            context = ssl.SSLContext(ssl.PROTOCOL_TLS)
            context.verify_mode = ssl.CERT_REQUIRED
            # `check_hostname` must be enabled as well to verify the authenticity of a cert.
            context.check_hostname = True
            context.load_verify_locations(capath=self.config.ssl_capath)

        try:
            # Object returned by SmartConnect is a ServerInstance
            # https://www.vmware.com/support/developer/vc-sdk/visdk2xpubs/ReferenceGuide/vim.ServiceInstance.html
            conn = connect.SmartConnect(host=self.config.hostname,
                                        user=self.config.username,
                                        pwd=self.config.password,
                                        sslContext=context)
            # Next line tries a simple API call to check the health of the connection.
            conn.CurrentTime()
        except Exception as e:
            err_msg = "Connection to {} failed: {}".format(
                self.config.hostname, e)
            raise APIConnectionError(err_msg)

        if self._conn:
            connect.Disconnect(self._conn)
        self._conn = conn
def main():
    args = get_args()
    try:
        if is_xenial_or_above():
            ssl = __import__("ssl")
            context = ssl._create_unverified_context()
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port, sslContext=context)
        else:
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port)
        si_content = si.RetrieveContent()
    except:
        print "Unable to connect to %s" % args.host
        exit(1)
    # get VM object
    vm_obj = get_obj(si_content, [vim.VirtualMachine], args.vm_name)
    if not vm_obj:
        print "VM %s not pressent" %(args.vm_name)
        exit(1)
    #net_obj = get_obj(si_content, [vim.Network], args.network_name)
    nics = args.nics.split(',')
    for nic in nics:
        if not nic:
           continue
        task = update_mac(nic, vm_obj, si_content)
        wait_for_task(task)
    connect.Disconnect(si)
Exemple #14
0
    def get_datastores(self, address, username, password, full=False):
        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        ssl_context.verify_mode = ssl.CERT_NONE

        try:
            si = connect.SmartConnect(host=address, user=username, pwd=password, sslContext=ssl_context)
            content = si.RetrieveContent()
            vm_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
        except vmodl.MethodFault as err:
            raise RpcException(errno.EFAULT, err.msg)

        try:
            for datastore in content.viewManager.CreateContainerView(content.rootFolder, [vim.Datastore], True).view:
                vms = []
                if full:
                    for vm in vm_view.view:
                        if datastore not in vm.datastore:
                            continue

                        vms.append({
                            'id': vm.config.uuid,
                            'name': vm.summary.config.name,
                            'on': vm.summary.runtime.powerState == 'poweredOn',
                            'snapshottable': can_be_snapshotted(vm)
                        })

                yield {
                    'id': datastore.info.url,
                    'name': datastore.info.name,
                    'free_space': datastore.info.freeSpace,
                    'virtual_machines': vms
                }
        finally:
            connect.Disconnect(si)
Exemple #15
0
def main():
    args = get_args()

    try:
        ssl = __import__("ssl")
        context = ssl._create_unverified_context()

        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port,
                                  sslContext=context)
    except Exception as e:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port)
    except:
        print "Unable to connect to %s" % args.host
        exit(1)

    # Connect to EAM endpoint
    eamCx = ConnectEAM(si, si._stub, context)
    # Query and find if ContrailVM-Agency is existing
    agencies = eamCx.QueryAgency()
    if agencies:
        for agency in agencies:
            agency_name = agency.QueryConfig().agencyName
            if agency_name == "ContrailVM-Agency":
                agency.DestroyAgency()
    connect.Disconnect(si)
    return 0
def main():
    args = get_args()
    try:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port)
        si_content = si.RetrieveContent()
    except:
        print "Unable to connect to %s" % args.host
        exit(1)
    # check if PG exists else return error
    dv_switch = get_obj(si_content, [vim.DistributedVirtualSwitch],
                        args.dvs_name)
    if not dv_switch:
        print "dv switch %s not pressent" % (args.dvs_name)
        exit(1)
    dv_pg = get_dvs_pg_obj(si_content, [vim.dvs.DistributedVirtualPortgroup],
                           args.dv_pg_name, args.dvs_name)
    if not dv_pg:
        print "port-group %s not present in dvs %s" % (args.dv_pg_name,
                                                       args.dvs_name)
        exit(1)
    update_dv_pg(args, dv_pg)
    add_pvlan_config(dv_switch)
    connect.Disconnect(si)
	def reconnect(self):
		try:
			if self.vs != None:
				connect.Disconnect(self.vs)
			self.vs = connect.Connect(self.host, self.port, self.user, self.password)
			return True
		except Exception as e:
			print str(e)
			return False
def get_windows_under_gid(host, login, passwd):
    vcenter_si = None
    try:
        vcenter_si = connect.SmartConnectNoSSL(host=host, user=login, pwd=passwd)
    except:
        logger.error("Can't login to {}".format(host))
        return None
    content = vcenter_si.RetrieveContent()
    datacenter = content.rootFolder.childEntity[0]
    # datastores = datacenter.datastore
    vmfolder = datacenter.vmFolder
    raw_vmlist = vmfolder.childEntity
    perf_manager = content.perfManager
    # cluster = datacenter.hostFolder.childEntity[0]
    vmlist = get_all_vm_under_folder(raw_vmlist)
    vm_windows_attribute_key = get_attribute_key_by_name(content, LICENSED_WINDOWS_FIELD_NAME)

    gid_windows_count = defaultdict(list)
    # os_set = set()
    # for vm in vmlist:
    #     os_set.add(vm.config.guestId)
    for vm in vmlist:
        # resourcePool is None means this it template
        if vm.resourcePool is None:
            continue
        top_parent_name = find_top_resource_pool(vm.resourcePool)
        vm_data = VM()
        vm_data.name = vm.name
        vm_data.resource_pool_name = vm.resourcePool.name
        vm_data.top_resource_pool_name = top_parent_name
        vm_data.config_cpu = vm.summary.config.numCpu
        vm_data.config_ram = vm.summary.config.memorySizeMB
        vm_data.os = vm.config.guestId
        vm_data.powered_on = vm.summary.runtime.powerState == "poweredOn"
        if vm_data.powered_on:  # and vm_data.os.startswith("win"):
            cpu_usage, mem_usage = get_vm_resource_usage(perf_manager, vm)
            vm_data.cpu_usage = cpu_usage.avg
            vm_data.ram_usage = mem_usage.avg
        if vm_windows_attribute_key is not None:
            for tag in vm.value:
                if tag.key == vm_windows_attribute_key and tag.value == LICENSED_WINDOWS_FIELD_VALUE:
                    vm_data.windows_licensed = True

        gid_windows_count[top_parent_name].append(vm_data)
        # if vm.config.guestId.startswith('win'):
            # top_parent_name = find_top_resource_pool(vm.resourcePool)
            # if top_parent_name is not None and top_parent_name.startswith('GID'):
            # if top_parent_name is not None and 'GID' in top_parent_name:
                # gid_windows_count[top_parent_name] += 1

    # total_gid_windows_count = 0
    # for k, v in sorted(gid_windows_count.items()):
    #     logger.debug("{} have {} windows.".format(k, v))
    #     total_gid_windows_count += v
    # logger.info('Total: {}'.format(total_gid_windows_count))
    connect.Disconnect(vcenter_si)
    return {"host": host, "gid_windows_count": gid_windows_count}
Exemple #19
0
def esxi_add_drive(host, usr, pwd, vm_name, disk_size):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name
        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        esxi_add_new_disk_process(vm, si, disk_size)
        connect.Disconnect(si)
    except Exception, e:
        return "Create new drive on VM(%s) failed!" % vm_name
Exemple #20
0
def run():

    parser = build_args()
    args = parser.parse_args()

    # Get the VM type specifications
    vms = readYaml(args.yaml)  #("vmSpecifications.yaml")
    # Obtain temporary host or vCenter credentials and determine storage type
    tempHostPw = "password"
    #print("Credentials for vCenter or ESXi are required:")
    #account = input("Enter in the account name: ")
    #password = input("Enter in your SU account password: "******"192.168.1.56"
    myHost = connectHost(host, "root", tempHostPw)

    # Get a list of all datastores
    datastores = returnDatastores(myHost)
    print(datastores)
    # Cycle through each VM in the hash and create it if it dosen't already exist then populate the hash with the uuid
    for vm in vms:

        checkVm = returnVmUuid(vm, myHost)
        if not checkVm:
            # Create the VM
            print("Creating the VM -", vm)
            createVmTask = createVm(myHost, vm, vms[vm])
            if createVmTask.info.state == "error":
                raise Exception("VM {0} had the creation error {1}".format(
                    vm, createVmTask.info.error.__class__.__name__))
            while createVmTask.info.state == "running":
                print("   Waiting for VM create task to finish")
                time.sleep(1)

            # Add CDROM to VM
            addVmCdrom(myHost, vm)

            # Add NIC/s to the VM
            addNicTask = addVmNic(myHost, vm, vms[vm])
            if addNicTask.info.state == "error":
                raise Exception("VM {0} had NIC creation error {1}".format(
                    vm["hostname"], addNicTask.info.error.__class__.__name))

            # Add Disk/s to the VM
            addDiskTask = addVmDisk(myHost, vm, vms[vm])
            if createVmTask.info.state == "error":
                raise Exception("VM {0} had disk creation error {1}".format(
                    vm["hostname"], addDiskTask.info.error.__class__.__name))
        else:
            print(vm, " already exists, skipping")

    print("Disconnecting from host")
    connect.Disconnect(myHost)
Exemple #21
0
def esxi_get_network(host, usr, pwd):
    """ Get the Network information of 1 ESXi. """
    network_list = []
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        views = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.Network], True)
        for view in views.view:
            network_list.append(view.name)
        connect.Disconnect(si)
    except Exception, e:
        return "Get Network failed!"
Exemple #22
0
def getvmconfig(hostIP, hostPass, vmIP):
    print("Host IP: " + hostIP + ", Host Password: "******", VM IP: " +
          vmIP)
    my_cluster = connect.ConnectNoSSL(hostIP, 443, "root", hostPass)
    searcher = my_cluster.content.searchIndex
    vm = searcher.FindByIp(ip=vmIP, vmSearch=True)
    print("VM Config Details for " + vmIP)
    print(vm.config.name)
    print(vm.config.guestFullName)

    # Disconnect from cluster or host
    connect.Disconnect(my_cluster)
Exemple #23
0
    def snapshot_end(self, context):
        self.middleware.call_sync('network.general.will_perform_activity',
                                  'vmware')

        vmsnapname = context["vmsnapname"]

        for elem in context["vmsnapobjs"]:
            vmsnapobj = elem["vmsnapobj"]

            try:
                ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                ssl_context.verify_mode = ssl.CERT_NONE
                si = connect.SmartConnect(host=vmsnapobj["hostname"],
                                          user=vmsnapobj["username"],
                                          pwd=vmsnapobj["password"],
                                          sslContext=ssl_context)
                self._delete_vmware_login_failed_alert(vmsnapobj)
            except Exception as e:
                self.logger.warning("VMware login failed to %s",
                                    vmsnapobj["hostname"])
                self._alert_vmware_login_failed(vmsnapobj, e)
                continue

            # vm is an object, so we'll dereference that object anywhere it's user facing.
            for vm_uuid in elem["snapvms"]:
                vm = si.content.searchIndex.FindByUuid(None, vm_uuid, True)
                if not vm:
                    self.logger.debug("Could not find VM %s", vm_uuid)
                    continue
                if [vm_uuid, vm.name] not in elem[
                        "snapvmfails"] and vm_uuid not in elem["snapvmskips"]:
                    # The test above is paranoia.  It shouldn't be possible for a vm to
                    # be in more than one of the three dictionaries.
                    snap = self._findVMSnapshotByName(vm, vmsnapname)
                    try:
                        if snap:
                            VimTask.WaitForTask(snap.RemoveSnapshot_Task(True))
                    except Exception as e:
                        self.logger.debug(
                            "Exception removing snapshot %s on %s",
                            vmsnapname,
                            vm.name,
                            exc_info=True)
                        self.middleware.call_sync(
                            "alert.oneshot_create",
                            "VMWareSnapshotDeleteFailed", {
                                "hostname": vmsnapobj["hostname"],
                                "vm": vm.name,
                                "snapshot": vmsnapname,
                                "error": self._vmware_exception_message(e),
                            })

            connect.Disconnect(si)
Exemple #24
0
    def smart_connect(self):
        # type: () -> None
        """
        Creates the connection object to the vSphere API using parameters supplied from the configuration.

        Docs for vim.ServiceInstance:
            https://vdc-download.vmware.com/vmwb-repository/dcr-public/b525fb12-61bb-4ede-b9e3-c4a1f8171510/99ba073a-60e9-4933-8690-149860ce8754/doc/vim.ServiceInstance.html
        """
        context = None
        if not self.config.ssl_verify:
            # Remove type ignore when this is merged https://github.com/python/typeshed/pull/3855
            context = ssl.SSLContext(ssl.PROTOCOL_TLS  # type: ignore
                                     )
            context.verify_mode = ssl.CERT_NONE
        elif self.config.ssl_capath:
            # Remove type ignore when this is merged https://github.com/python/typeshed/pull/3855
            context = ssl.SSLContext(ssl.PROTOCOL_TLS  # type: ignore
                                     )
            context.verify_mode = ssl.CERT_REQUIRED
            # `check_hostname` must be enabled as well to verify the authenticity of a cert.
            context.check_hostname = True
            context.load_verify_locations(capath=self.config.ssl_capath)

        try:
            # Object returned by SmartConnect is a ServerInstance
            # https://www.vmware.com/support/developer/vc-sdk/visdk2xpubs/ReferenceGuide/vim.ServiceInstance.html
            conn = connect.SmartConnect(host=self.config.hostname,
                                        user=self.config.username,
                                        pwd=self.config.password,
                                        sslContext=context)
            # Next line tries a simple API call to check the health of the connection.
            version_info = VersionInfo(conn.content.about)
        except Exception as e:
            err_msg = "Connection to {} failed: {}".format(
                self.config.hostname, e)
            raise APIConnectionError(err_msg)

        if not version_info.is_vcenter():
            # Connection was successful but to something that is not a VirtualCenter instance. The check won't
            # run correctly.
            # TODO: Raise an exception and stop execution here
            self.log.error(
                "%s is not a valid VirtualCenter (vCenter) instance, the vSphere API reports '%s'. "
                "Do not try to connect to ESXi hosts directly.",
                self.config.hostname,
                version_info.api_type,
            )

        if self._conn:
            connect.Disconnect(self._conn)

        self._conn = conn
        self.log.debug("Connected to %s", version_info.fullName)
Exemple #25
0
def esxi_get_datastores(host, usr, pwd):
    """ Get all datastore information of 1 ESXi. """
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)

        datacenter_obj = si.content.rootFolder.childEntity[0]
        datastore_list = datacenter_obj.datastoreFolder.childEntity
        dt_list = []
        for dt in datastore_list:
            dt_list.append(dt.name)
        connect.Disconnect(si)
    except Exception, e:
        return "Get Datastore Failed!"
Exemple #26
0
def esxi_list_hardware(host, usr, pwd):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        host_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.HostSystem], True)
        info = {
            "cores": host_view.view[0].hardware.cpuInfo.numCpuCores,
            "freq": host_view.view[0].hardware.cpuInfo.hz,
            "threads": host_view.view[0].hardware.cpuInfo.numCpuThreads,
            "memory": host_view.view[0].hardware.memorySize
        }
        connect.Disconnect(si)
    except Exception, e:
        return "Get ESXi Hardware Info Failed!"
Exemple #27
0
def esxi_change_memory(host, usr, pwd, vm_name, mem_size):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name

        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        spec = vim.vm.ConfigSpec()
        spec.memoryMB = int(mem_size) + 512
        task = vm.ReconfigVM_Task(spec)
        tasks.wait_for_tasks(si, [task])

        connect.Disconnect(si)
    except Exception, e:
        return "Change VM Memory on VM(%s) failed!" % vm_name
Exemple #28
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, vim.fault.NoPermission) 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 = {}

            if storage_system.fileSystemVolumeInfo is None:
                continue

            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
def main():
    args = get_args()
    ovfd = get_ovf_descriptor(args.ovf_path)
    try:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=args.port)
    except:
        error = "Unable to connect to" + " " + args.host
        print "Unable to connect to %s" % args.host
        send_error_mail_fn(error)
        raise SystemError("Error")
        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
            error_lease = "Lease error: " + lease.state.error
            send_error_mail_fn(error_lease)
            raise SystemError("Error")
            exit(1)
    connect.Disconnect(si)
Exemple #30
0
def main():
    args = get_args()
    try:
        dt = datetime.strptime(args.date, '%d/%m/%Y %H:%M')
    except ValueError:
        print('Unrecognized date format')
        raise
        return -1

    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    try:
        si = connect.SmartConnectNoSSL(host=args.host,
                                       user=args.user,
                                       pwd=password,
                                       port=int(args.port))
    except vim.fault.InvalidLogin:
        print("Could not connect to the specified host using specified "
              "username and password")
        return -1

    atexit.register(connect.Disconnect, si)

    view = si.content.viewManager.CreateContainerView(si.content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    vms = [vm for vm in view.view if vm.name == args.vmname]

    if not vms:
        print('VM not found')
        connect.Disconnect(si)
        return -1
    vm = vms[0]

    spec = vim.scheduler.ScheduledTaskSpec()
    spec.name = 'PowerOff vm %s' % args.vmname
    spec.description = ''
    spec.scheduler = vim.scheduler.OnceTaskScheduler()
    spec.scheduler.runAt = dt
    spec.action = vim.action.MethodAction()
    spec.action.name = vim.VirtualMachine.PowerOff
    spec.enabled = True

    si.content.scheduledTaskManager.CreateScheduledTask(vm, spec)