def main():
    try:
        si = SmartConnectNoSSL(host=ho, user=us, pwd=password)
        atexit.register(Disconnect, si)
        content = si.content
        objView = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.VirtualMachine], True)
        vmList = objView.view
    except Exception as e:
        print("Caught Exception : " + str(e))
    des_Vm = None
    try:
        for vm in vmList:
            if (vm.summary.config.name == vm_name):
                des_Vm = vm
                print(vm)
                break
    except Exception as e:
        print(str(e))
    if des_Vm is None:
        print(-1)
        return
    print("The current powerState is: {0}".format(des_Vm.runtime.powerState))
    if format(des_Vm.runtime.powerState) == "poweredOn":
        TASK = des_Vm.PowerOffVM_Task()
        wait_for_task(TASK)
        print("{0}".format(TASK.info.state))

    print("Destroying VM from vSphere.")
    TASK = des_Vm.Destroy_Task()
    wait_for_task(TASK)
    print("Done.")
示例#2
0
def main():
  argument_spec = vmware_argument_spec()
 
  argument_spec.update(
        dict(hostname= dict(required=True, type='str'),
            username=dict(required=True, type='str'),
            password=dict(required=True, type='str'),
            datacenter=dict(required=True, type='str'),
            cluster=dict(required=True, type='str'),
            datastore=dict(required=True,type='str'),
            portgroup1= dict(required=True,type='str'),
            portgroup2= dict(required=True, type='str'),
            portgroup3=dict(required=True, type='str')))

  module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
  try:
	logger.info("Trying to connect to VCENTER SERVER . . .")
	si = SmartConnectNoSSL(host=module.params['hostname'],
						   user=module.params['username'],
						   pwd=module.params['password'],
						   port=443)
        logger.info("Connected to VCENTER SERVER !")
  except IOError, e:
	#pass
	#atexit.register(Disconnect, si)
	logger.info("Connection failed {0}")
        module.fail_json(changed=False, msg="Failed to connect vCenter")
def main():
    args = get_args()

    # create the service instance
    si = None
    if args.disable_ssl_verification:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=args.port)
    else:
        si = SmartConnect(host=args.host,
                          user=args.user,
                          pwd=args.password,
                          port=args.port)

    # disconnect the service instance at program exit
    atexit.register(Disconnect, si)

    vm = None
    if args.uuid:
        search_index = si.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = si.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_raw_disk(vm, si, args.device_name, args.disk_mode,
                     args.compatibility_mode)
    else:
        print "VM not found"
示例#4
0
文件: clone_vm.py 项目: hutepa/myV
def start(vmname, template_str, cpus, mem, vm_folder, nicnum,nics):
    """
    Let this thing fly

    args = get_args()
    """
    # connect this thing
    si =  SmartConnectNoSSL(host='xx.xx.xx.xx',
                            user='******',
                            pwd='password',
                            port='443')
    # disconnect this thing
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    template = None

    template = get_obj(content, [vim.VirtualMachine], template_str)

    guestid = template.config.guestId

    dc_name, ds_name, cluster_name, ds_cluster_name = (None for i in range(4))
    ds_name = "datastore2"
    power_on = True
    #print "one"
    if template:
        clone_vm(
            content, template, vmname,
            dc_name, vm_folder,
            ds_name, cluster_name,
             power_on, ds_cluster_name,cpus, mem, guestid,nicnum,nics)
    else:
        print "template not found"
 def hello_vcenter(self):
     try:
         self.si = SmartConnectNoSSL(host=self._vchost,
                                     user=self._username,
                                     pwd=self._password,
                                     port=self._port)
         hello_content = self.si.RetrieveContent()
         for datacenter in hello_content.rootFolder.childEntity:
             for ds in datacenter.datastore:
                 self._vcenter_status['datastore'].append(ds.name)
             if hasattr(datacenter.hostFolder, 'childEntity'):
                 hostFolder = datacenter.hostFolder
                 computeResourceList = []
                 computeResourceList = self._getComputeResource(
                     hostFolder, computeResourceList)
                 for computeResource in computeResourceList:
                     for host in computeResource.host:
                         self._vcenter_status['esxi'].append(host.name)
         obj = hello_content.viewManager.CreateContainerView(
             hello_content.rootFolder, [vim.VirtualMachine], True)
         for vm in obj.view:
             self._vcenter_status['vm'].append(vm.name)
         return True, json.dumps(self._vcenter_status, indent=4)
     except vmodl.MethodFault as error:
         return False, error.msg
     except Exception as e:
         return False, str(e)
示例#6
0
def main():
    esxi_host = {}
    args = get_args()
    print(args)
    # connect this thing
    si = SmartConnectNoSSL(host=args['host'],
                           user=args['user'],
                           pwd=args['password'],
                           port=args['port'])
    # disconnect this thing
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    esxi_obj = get_obj(content, [vim.HostSystem])
    for esxi in esxi_obj:
        esxi_host[esxi.name] = {
            'esxi_info': {},
            'datastore': {},
            'network': {},
            'vm': {}
        }

        esxi_host[esxi.name]['esxi_info']['厂商'] = esxi.summary.hardware.vendor
        esxi_host[esxi.name]['esxi_info']['型号'] = esxi.summary.hardware.model
        for i in esxi.summary.hardware.otherIdentifyingInfo:
            if isinstance(i, vim.host.SystemIdentificationInfo):
                esxi_host[esxi.name]['esxi_info']['SN'] = i.identifierValue
        esxi_host[esxi.name]['esxi_info'][
            '处理器'] = '数量:%s 核数:%s 线程数:%s 频率:%s(%s) ' % (
                esxi.summary.hardware.numCpuPkgs,
                esxi.summary.hardware.numCpuCores,
                esxi.summary.hardware.numCpuThreads,
                esxi.summary.hardware.cpuMhz, esxi.summary.hardware.cpuModel)
        esxi_host[esxi.name]['esxi_info']['处理器使用率'] = '%.1f%%' % (
            esxi.summary.quickStats.overallCpuUsage /
            (esxi.summary.hardware.numCpuPkgs *
             esxi.summary.hardware.numCpuCores * esxi.summary.hardware.cpuMhz)
            * 100)
        esxi_host[esxi.name]['esxi_info'][
            '内存(MB)'] = esxi.summary.hardware.memorySize / 1024 / 1024
        esxi_host[esxi.name]['esxi_info']['可用内存(MB)'] = '%.1f MB' % (
            (esxi.summary.hardware.memorySize / 1024 / 1024) -
            esxi.summary.quickStats.overallMemoryUsage)
        esxi_host[esxi.name]['esxi_info']['内存使用率'] = '%.1f%%' % (
            (esxi.summary.quickStats.overallMemoryUsage /
             (esxi.summary.hardware.memorySize / 1024 / 1024)) * 100)
        esxi_host[esxi.name]['esxi_info'][
            '系统'] = esxi.summary.config.product.fullName

        for ds in esxi.datastore:
            esxi_host[esxi.name]['datastore'][ds.name] = {}
            esxi_host[esxi.name]['datastore'][ds.name]['总容量(G)'] = int(
                (ds.summary.capacity) / 1024 / 1024 / 1024)
            esxi_host[esxi.name]['datastore'][ds.name]['空闲容量(G)'] = int(
                (ds.summary.freeSpace) / 1024 / 1024 / 1024)
            esxi_host[esxi.name]['datastore'][ds.name]['类型'] = (
                ds.summary.type)
        pprint(esxi_host[esxi.name]['datastore'])
        for nt in esxi.network:
            esxi_host[esxi.name]['network'][nt.name] = {}
            esxi_host[esxi.name]['network'][nt.name]['标签ID'] = nt.name
示例#7
0
def run(exsi,user,pwd,interval):
    try:
        si = SmartConnectNoSSL(host=exsi, user=user, pwd=pwd, port=443)
        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        vchtime = si.CurrentTime()

        perf_dict = {}
        perfList = content.perfManager.perfCounter
        for counter in perfList:
            counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
            perf_dict[counter_full] = counter.key
        
        for datacenter in content.rootFolder.childEntity:
            datacenter_name = datacenter.name.encode("utf8")
            datastores = datacenter.datastore
            for ds in datastores:
                DatastoreInformation(ds,datacenter_name)

            if hasattr(datacenter.hostFolder, 'childEntity'):
                hostFolder = datacenter.hostFolder
                computeResourceList = []
                computeResourceList = getComputeResource(hostFolder,computeResourceList)
                for computeResource in computeResourceList:
                    ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval,exsi)

    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return False, error.msg
    return True, "ok"
示例#8
0
文件: vm_manage.py 项目: voltage12/vm
    def connect(self, user, password):
        try:
            self.service_instance = SmartConnect(host=self.ipadd, user=user, pwd=password)
        except vim.fault.InvalidLogin:
            logging.error("用户名或密码错误,无法登入ip为%s的ESXi主机" % self.ipadd)
            return 1
        except:
            logging.info("使用SmartConnect方法连接失败,ESXi主机没有受认证的SSL证书")
            logging.info("尝试使用SmartConnectNoSSL方法连接")
            try:
                self.service_instance = SmartConnectNoSSL(host=self.ipadd, user=user, pwd=password)
            except vim.fault.Invali  dLogin:
                logging.error("用户名或密码错误,无法登入ip为%s的ESXi主机" % self.ipadd)
                return 1

        if self.service_instance != None:
            logging.info("成功与ip地址为%s的ESXi主机建立连接" % self.ipadd)
            # 在程序关闭后关闭连接
            atexit.register(Disconnect, self.service_instance)
            self.get_all_vm(self.service_instance.RetrieveContent().rootFolder)
            self.is_connect = True
            return 0
        else:
            logging.error("由于未知错误,无法与ip地址为%s的ESXi主机建立连接" % self.ipadd)
            return 2
示例#9
0
    def connect(self):
        """Connect to vCenter server"""
        try:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            if self.config['no_ssl_verify']:
                requests.packages.urllib3.disable_warnings()
                context.verify_mode = ssl.CERT_NONE
                self.si = SmartConnectNoSSL(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    certFile=None,
                    keyFile=None,
                )
            else:
                self.si = SmartConnect(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    sslContext=context,
                    certFile=None,
                    keyFile=None,
                )
        except Exception as e:
            print('Unable to connect to vsphere server.')
            print(e)
            sys.exit(1)

        # add a clean up routine
        atexit.register(Disconnect, self.si)

        self.content = self.si.RetrieveContent()
示例#10
0
def main():

    args = get_args()

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

        atexit.register(Disconnect, service_instance)

        # call configuration of dvs port group
        configure_dvs_pg(service_instance, args.dvs_name, args.dvs_pg_name)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : {0}".format(error.msg))
        return -1

    return 0
def main():
    try:
        si = SmartConnectNoSSL(host=ho, user=us, pwd=password)
        atexit.register(Disconnect, si)
        content = si.content
        objView = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.HostSystem], True)
        hostList = objView.view
    except Exception as e:
        print("Caught Exception : " + str(e))
    des_host = None
    ip = find_host_ip
    try:
        for host in hostList:
            if isinstance(host,
                          vim.HostSystem) and host.summary.config.name == ip:
                des_host = host
                break
    except Exception as e:
        print(str(e))
        exit()
    if des_host is None:
        print(0)
        return
    TASK = None
    if isinstance(des_host.parent, vim.ClusterComputeResource):
        TASK = des_host.Destroy()
    else:
        TASK = des_host.parent.Destroy()
    wait_for_task(TASK)
    print(1)
示例#12
0
def main():
    args = get_args()
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    search_index = content.searchIndex

    vm = None
    if args.uuid:
        vm = search_index.FindByUuid(None, args.uuid, True, True)
    elif args.ip:
        vm = search_index.FindByIp(None, args.ip, True)
    else:
        vm = get_obj(content, [vim.VirtualMachine], args.name)
   
    if not vm:
        print(u"Could not find a virtual machine to examine.")
        exit(1)

    perf=perfdata()
    counters=perf.perfcounters()
    for counter in counters:
        p = Thread(target=perf.run, args=(content,vm,counter,))
        p.start()
示例#13
0
 def discover_clusters_vcenter(address, username, password, ret):
   """
   Args:
     address (str): Address of the management server.
     username (str): Name of user of the management server.
     password (str): Password of user of the management server
     ret (DiscoverClustersV2Ret): Return proto to be populated.
   """
   conn = None
   try:
     conn = SmartConnectNoSSL(host=address, user=username, pwd=password)
     log.debug("Connected to vCenter %s", address)
     vim_inventory_map = \
         DiscoveryUtil.compute_vcenter_cluster_inventory(conn.content.rootFolder)
     DiscoveryUtil._fill_vcenter_cluster_inventory_v2(
       vim_inventory_map, ret)
     for cluster_collection in ret.cluster_inventory.cluster_collection_vec:
       for cluster in cluster_collection.cluster_vec:
         cluster.management_server.type = cluster.management_server.kVcenter
         cluster.management_server.version = conn.content.about.version
   except socket.error:
     # The plain old socket errors don't indicate which connection.
     raise CurieException(CurieError.kInternalError,
       "Could not connect to vCenter at %s" % address)
   except vim.fault.InvalidLogin:
     # The failures back from vSphere don't provide the best experience.
     raise CurieException(CurieError.kInternalError,
       "Incorrect username or password for vCenter at %s" %address)
   finally:
     if conn is not None:
       Disconnect(conn)
def main():
    """
    Simple command-line program for listing the virtual machines on a host.
    """

    args = setup_args()
    si = None
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)
    except vim.fault.InvalidLogin:
        raise SystemExit("Unable to connect to host "
                         "with supplied credentials.")

    content = si.RetrieveContent()

    if args.folder == "":
        for child in content.rootFolder.childEntity:
            if hasattr(child, 'vmFolder'):
                datacenter = child
                vmfolder = datacenter.vmFolder
                vmlist = vmfolder.childEntity
                for vm in vmlist:
                    shutdown(vm)
    else:
        vmfolder = get_obj(content, [vim.Folder], args.folder)
        vmlist = vmfolder.childEntity
        for vm in vmlist:
            shutdown(vm)
示例#15
0
def main():
    args = get_args()

    # connect this thing
    serviceInstance = None
    if args.no_ssl:
        serviceInstance = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    else:
        serviceInstance = SmartConnect(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, serviceInstance)

    vm = None
    if args.uuid:
        search_index = serviceInstance.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = serviceInstance.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_nic(serviceInstance, vm, args.port_group)
    else:
        print("VM not found")
示例#16
0
def clone_vm_from_no(vm_no, temp_no):

    si = SmartConnectNoSSL(host='172.16.1.200',
                           user='******',
                           pwd='Cisc0123,,..//',
                           port=443)

    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    template = None

    if temp_no == 1:
        template = get_obj(content, [vim.VirtualMachine], 'vm_temp_cpu1_mem1')

    elif temp_no == 2:
        template = get_obj(content, [vim.VirtualMachine], 'vm_temp_cpu1_mem2')

    elif temp_no == 3:
        template = get_obj(content, [vim.VirtualMachine], 'vm_temp_cpu2_mem1')

    elif temp_no == 4:
        template = get_obj(content, [vim.VirtualMachine], 'vm_temp_cpu2_mem2')

    vm_name = 'CentOS_' + str(vm_no)

    clone_vm(content, template, vm_name, si, None, 'vm_cloned_from_template',
             None, None, None, False, None)

    return None
示例#17
0
def get_token_url(vmname):

    si = SmartConnectNoSSL(host=vcip, user=username, pwd=password)
    # si = SmartConnectNoSSL(host=vcip, user=user1, pwd=pass1)

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

    vmobj = None
    for vm in vmList:
        if vm.name in vmname:
            vmobj = vm
            break

    if not vmobj:
        return None

    ticket = vmobj.AcquireTicket(ticketType='webmks')

    return 'wss://{0}:{1}/ticket/{2}'.format(ticket.host, ticket.port,
                                             ticket.ticket)
示例#18
0
def start(template_str):
    """
    Let this thing fly

    args = get_args()
    """
    # connect this thing
    si = SmartConnectNoSSL(host='xx.xx.xx.xx',
                           user='******',
                           pwd='anamishhinA@2',
                           port='443')
    # disconnect this thing
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    template = None

    template = get_obj(content, [vim.VirtualMachine], template_str)

    vmname = template_str + ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits)
        for _ in range(8))
    dc_name, vm_folder, ds_name, cluster_name, resource_pool, ds_cluster_name = (
        None for i in range(6))
    power_on = True

    if template:
        clone_vm(content, template, vmname, si, dc_name, vm_folder, ds_name,
                 cluster_name, resource_pool, power_on, ds_cluster_name)
    else:
        print "template not found"
示例#19
0
def main():
    try:
        si = SmartConnectNoSSL( host = ho, user = us, pwd = password)
        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        objview = content.viewManager.CreateContainerView(content.rootFolder,[vim.HostSystem],True)
        esxi_hosts = objview.view
        datastores = content.viewManager.CreateContainerView(content.rootFolder,[vim.Datastore],True).view
        for esxi_host in esxi_hosts:
            state = esxi_host.summary.runtime.connectionState
            powerstate = esxi_host.summary.runtime.powerState
            print("{}\t{}\t{}".format("ESXi Host:    ", esxi_host.name,state))
            if(state == "connected" and powerstate=="poweredon"):
                storage_system = esxi_host.configManager.storageSystem
                host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo
                for host_fs in host_file_sys_vol_mount_info:
                    if host_fs.volume.type == "VMFS":
                        for dt in datastores:
                            if(host_fs.volume.name == dt.summary.name):
                                print("{}\t{}".format("Datastore:     ", host_fs.volume.name))
                                print("{}\t{}".format("Capacity:      ", sizeof_fmt(host_fs.volume.capacity)))
                                print("{}\t{}".format("Free space:    ", sizeof_fmt(dt.summary.freeSpace)))
            else:
                print('poweredoff')
    except Exception as e:
        print(str(e),'\n')
        return -1
    return 0
示例#20
0
def main():
    try:
        si = SmartConnectNoSSL(host=ho, user=us, pwd=password)
        atexit.register(Disconnect, si)
    except Exception as e:
        print(str(e))
        return -1
    s = False
    content = si.RetrieveContent()
    object_view = content.viewManager.CreateContainerView(
        content.rootFolder, [vim.HostSystem], True).view
    for obj in object_view:
        if obj.summary.config.name == find_host_ip:
            host = obj
            s = True
            break
    if s:
        if host.runtime.powerState == 'poweredOn':
            host.Reboot(force=True)
            print(1)
        else:
            print(0)
    else:
        print('Not Found!')
    # host = si.content.searchIndex.FindByDnsName(None,find_host_ip,False)
    # if host is not None:
    #     print('1')
    # else:
    # 	print('0')
    return 0
示例#21
0
def FindVMIP(IP, usern, passw, vIP="10.160.111.161"):
    def find_IP(virtual_machine, IPLook):

        summary = virtual_machine.summary
        for nic in virtual_machine.guest.net:

            if nic.ipConfig is not None:
                addresses = nic.ipConfig.ipAddress

                for adr in addresses:
                    #print(adr.ipAddress)
                    if IPLook == adr.ipAddress:
                        print("IP being used by: " + summary.config.name)
        return

    c = SmartConnectNoSSL(host=vIP, user=usern, pwd=passw)

    content = c.RetrieveContent()
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True
    containerView = content.viewManager.CreateContainerView(
        container, viewType, recursive)
    children = containerView.view

    for child in children:
        find_IP(child, IP)
def main():
    args = setup_args()
    filter_key = "summary.config.guestId"
    value = "crxPod1Guest"
    memory_threshold_utilization = 0.5
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    # Start with all the VMs from container, which is easier to write than
    # PropertyCollector to retrieve them.
    vms = get_obj(si, si.content.rootFolder, [vim.VirtualMachine])

    pc = si.content.propertyCollector
    filter_spec = create_filter_spec(pc, vms, filter_key)
    options = vmodl.query.PropertyCollector.RetrieveOptions()
    result = pc.RetrievePropertiesEx([filter_spec], options)
    vms = filter_results(result, value)
    hpa_vms = hpa_algo(vms, memory_threshold_utilization)
    for vm in hpa_vms:
        #print(vm['pod_name'])
        deployment = vm['pod_name']
        replica_count = "--replicas=" + str(vm['desired_replicas'])
        subprocess.call(
            ["kubectl", "scale", "deployments", deployment, replica_count])

    Disconnect(si)
def get_vds_uuid(vds_name, host, user, pwd):

    try:
        service_instance = SmartConnectNoSSL(host=host,
                                             user=user,
                                             pwd=pwd,
                                             port='443')
        atexit.register(Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Get VDS object
        vds = get_obj(content, [vim.DistributedVirtualSwitch], vds_name)
        if vds is None:
            logging.error("Distributed Switch: %s Not found in vCenter." %
                          vds_name)
            print("ERROR: Distributed Switch: %s Not found in vCenter." %
                  vds_name)
            sys.exit(2)

    except vmodl.MethodFault as error:
        logging.error(
            "Unable to connect to vCenter: Caught vmodl fault: {0}".format(
                error.msg))
        print("Unable to connect to vCenter: Caught vmodl fault: {0}".format(
            error.msg))
        sys.exit(2)

    vds_uuid = vds.config.uuid
    logging.debug("VDS %s has UUID: %s" % (vds_name, vds_uuid))

    return vds_uuid
def main():
    args = get_args()

    # connect this thing
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, si)

    vm = None
    if args.uuid:
        search_index = si.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = si.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_disk(vm, si, args.disk_size, args.disk_type)
        return 0
    else:
        print "VM not found"
        return 1
def main():
    """
    Let this thing fly
    """
    args = get_args()

    # connect this thing
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    template = None

    template = get_obj(content, [vim.VirtualMachine], args.template)

    if template:
        clone_vm(content, template, args.vm_name, si, args.datacenter_name,
                 args.vm_folder, args.datastore_name, args.cluster_name,
                 args.resource_pool, args.power_on, args.datastorecluster_name)
    else:
        print("template not found")
示例#26
0
    def connect(self, exit_on_fault=True):
        """
        Connect to VCenter.

        Currently doesn't use certificate, as it not used in the most installations or self-signed used.

        :param bool exit_on_fault: Perform exit on connection fault if True, otherwise returns None.
        :return: VMWare ServiceInstance object or None in case of connection fault.
        """
        logging.info(f'Connecting to {self._address} ...')
        try:
            si = SmartConnectNoSSL(host=self._address,
                                   user=self._username,
                                   pwd=self._password)
            self.si = si
            self.content = si.RetrieveServiceContent()
            atexit.register(Disconnect, si)
            logging.info(f'Connected to {self._address}')
            return si

        except vim.fault.InvalidLogin as e:
            logging.info(e.msg)
            if exit_on_fault:
                exit(1)
            else:
                return None
        except Exception:
            logging.info('Unable to connect. Check address and credentials.')
            if exit_on_fault:
                exit(1)
            else:
                return None
示例#27
0
def main():
    args = GetArgs()
    si = None
    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt="Enter password for host {} and user {}: ".format(args.host, args.user))
    try:
        if args.skip_ssl_validation:
            si = SmartConnectNoSSL(host=args.host,
                                   user=args.user,
                                   pwd=password,
                                   port=int(args.port))
        else:
            si = SmartConnect(host=args.host,
                              user=args.user,
                              pwd=password,
                              port=int(args.port))
    except IOError as e:
        pass
    if not si:
        print('Could not connect to the specified host using specified username and password')
        return -1

    atexit.register(Disconnect, si)
    content = si.RetrieveContent()

    # Get all the performance counters
    perf_dict = {}
    perf_list = content.perfManager.perfCounter
    for counter in perf_list:
        counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
        perf_dict[counter_full] = {'key': counter.key, 'summary': counter.nameInfo.summary}
    with open('perf_dict.json', 'w') as out:
        json.dump(perf_dict, out, indent=2)
示例#28
0
class legacy:

    HOST = 'umwvcenter01.ad.umassmed.edu'
    PASSWORD = getpass.getpass('Enter password')
    PORT = 443
    USER = '******'
    connection = SmartConnectNoSSL(host=HOST,
                                   user=USER,
                                   pwd=PASSWORD,
                                   port=PORT)
    content = connection.RetrieveContent()

    datastore_map = {}
    host_map = {}

    #retrieves objects in vcenter
    def get_vim_objects(self, content, vim_type):
        return [
            item for item in content.viewManager.CreateContainerView(
                content.rootFolder, [vim_type], recursive=True).view
        ]

    #datastores mapped to hosts,hosts mapped to VMs
    def datastoreMap(self, content):
        for datastore in self.get_vim_objects(content, vim.Datastore):
            self.datastore_map[datastore] = datastore.host
            for host in datastore.host:
                self.host_map[host.key.summary.host] = host.key.vm
        return self.datastore_map, self.host_map
示例#29
0
def main():
    """
    Simple command-line program for listing the virtual machines on a host.
    """

    args = setup_args()
    si = None
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)
    except vim.fault.InvalidLogin:
        raise SystemExit("Unable to connect to host "
                         "with supplied credentials.")

    content = si.RetrieveContent()
    vm_collect = {}

    for child in content.rootFolder.childEntity:
        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmfolder = datacenter.vmFolder
            vmlist = vmfolder.childEntity
            for vm in vmlist:
                printvminfo(vm_collect, vm)
    print(vm_collect)
    with open("/home/annie/CloudTides/Tools/Information.json", "w") as f:
        json.dump(vm_collect, f)
示例#30
0
def connect(args, config_dict, sec_dict):
    """
    Simple command-line program for listing the virtual machines on a host.
    """
    host = sec_dict.get('vc_config', {}).get('vc_hostname', args.host)
    user = sec_dict.get('vc_config', {}).get('vc_username', args.user)
    pwd = sec_dict.get('secs', {}).get('vc_pass', args.password)
    if not pwd:
        pwdprompt = "Password for " + args.user + "\n"
        pwd = getpass.getpass(prompt=pwdprompt)

    si = None
    try:
        si = SmartConnectNoSSL(host=host, user=user, pwd=pwd,
                               port=443)  #int(args.port))
        atexit.register(Disconnect, si)
    except AttributeError:
        raise SystemExit("Must specify host, user and pwd")
        return

    except vim.fault.InvalidLogin:
        raise SystemExit("Unable to connect to host "
                         "with supplied credentials.")
        return
    return si