def index(): si = SmartConnectNoSSL(host=host, user=user, pwd=pswd, port=443) content = si.RetrieveContent() dc = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datacenter], True) counter = 0 datacenters = list(dc.view) events = [] for dc in datacenters: alarms = dc.triggeredAlarmState for alarm in alarms: counter += 1 events.append((alarm.entity.name, alarm.alarm.info.description, alarm.entity.overallStatus, str(alarm.time))) if counter >= 1: color = 'red' else: color = 'green' return render_template('index.html', color=color, counter=counter, events=events)
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")
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
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)
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
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"
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 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
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
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"
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()
def main(): """ Simple command-line program for creating host and VM folders in a datacenter. """ args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) si = SmartConnectNoSSL(host=args.host, user=args.user, pwd=password, port=int(args.port)) 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() dc = get_obj(content, [vim.Datacenter], args.datacenter) if (get_obj(content, [vim.Folder], args.folder)): print("Folder '%s' already exists" % args.folder) return 0 #create_folder(content, dc.hostFolder, args.folder) #print("Successfully created the host folder '%s'" % args.folder) create_folder(content, dc.vmFolder, args.folder) print("Successfully created the VM folder '%s'" % args.folder) return 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 content = si.RetrieveContent() host = None 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 break if host is not None: if isinstance(host.parent,vim.ClusterComputeResource): tp = host.parent.name+' (Cluster)' else: tp= 'Datacenter' print("Location: ", tp) print("Host: ", host.summary.config.name) print("Host OS: ", host.summary.config.product.fullName) print("Con State: ", host.summary.runtime.connectionState) print("Power: ", host.summary.runtime.powerState) print("Maintenance mode: ", host.summary.runtime.inMaintenanceMode) else: print('0') return 0
def main(): si = SmartConnectNoSSL(host=ho, user=us, pwd=password) atexit.register(Disconnect, si) content = si.RetrieveContent() vms = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True).view vm = None if vm_name: for x in vms: if (x.summary.config.name == vm_name): vm = x elif find_vm_ip: for x in vms: if (x.summary.guest.ipAddress == find_vm_ip): vm = x else: print('Argument is not given') return 0 print('''Name: %s Path to VM: %s VM state: %s Ip: %s Guest OS name: %s Host name: %s''' % (vm.summary.config.name, vm.summary.config.vmPathName, vm.summary.runtime.powerState, summary.guest.ipAddress, vm.summary.config.guestFullName, vm.runtime.host.name)) return 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() for child in content.rootFolder.childEntity: if hasattr(child, 'vmFolder'): datacenter = child vmfolder = datacenter.vmFolder vmlist = vmfolder.childEntity for vm in vmlist: printvminfo(vm)
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"
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
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
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 = 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 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(): """ 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) else: print "template not found"
def main(): args = get_args() si = SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=args.port) atexit.register(Disconnect, si) content = si.RetrieveContent() vm = get_obj(content, [vim.VirtualMachine], args.vm) if vm: count = 36 while count: sleep(5) count -= 1 if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: if count == 35: print("Waiting VM '{}' shutdown.".format(vm.name)) if count == 12: print("Shutdown VM '{}' now.".format(vm.name)) vm.ShutdownGuest() if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff: ChangeCDDrive(si, vm, args.unit, args.iso) device_change = args.iso if args.iso else 'Client Device' print("Change CDROM {} to '{}' on VM '{}'.".format( args.unit, device_change, vm.name)) vm.PowerOn() print("Power ON VM '{}' now.".format(vm.name)) break if count == 0: print("ERROR: Timeout power state VM '{}' !".format(vm.name)) else: print("ERROR: VM '{}' not found !".format(args.name))
def main(): """ Iterate through all datacenters and list VM info. """ args = GetArgs() logging.info("Connecting VC..") if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) si = SmartConnectNoSSL(host=args.vcip, user=args.user, pwd=password, port=int(args.port)) if not si: print("Could not connect to the specified host using specified " "username and password") return -1 # atexit.register(Disconnect, si) # throws exception not sure why logging.info("Retrieving Content..") content = si.RetrieveContent() container = content.rootFolder # starting point to look into viewType = [vim.HostSystem] recursive = True containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view for host in children: # Iterate through Hosts in the Cluster hostname = host.summary.config.name if hostname != args.host_ip_to_restart: continue all_vms = host.vm vms = [m for m in all_vms if m.runtime.powerState == "poweredOn"] vms_ips = [ m.name for m in all_vms if m.runtime.powerState == "poweredOn" ] logging.info("VMs IN POWERED ON state {} ".format(vms_ips)) if len(vms) == 0: break logging.info("Powering Off all VMs on host {}".format(host.name)) for vm in vms: # Iterate through each VM on the host power_down(vm) host_enter_maintenance_mode(host) host_reboot(host) host_exit_maintenance_mode(host) logging.info("Powering ON all VMs on host {}".format(host.name)) for vm in vms: # Iterate through each VM on the host power_up(vm)
def main(): """ Let this thing fly """ args = get_args() try: # connect this thing if args.disable_ssl_verification: si = SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: context = None if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() si = SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port), sslContext=context) # disconnect this thing atexit.register(Disconnect, si) content = si.RetrieveContent() # clone template = None template = get_obj(content, [vim.VirtualMachine], args.template) if not template: raise Exception("template not found") clone_vm(content, template, args.vm_name, args.datacenter_name, args.vm_folder, args.datastore_name, args.cluster_name, args.resource_pool, args.host_name, args.power_on, args.datastorecluster_name) # automation configuration vm = None vm = get_nic_obj(content, [vim.VirtualMachine], args.vm_name) if not vm: raise Exception("VM not found") reconfig_nic(content, template, vm, args.port_group, args.cpus, args.memory) # add disk if args.disk_size > 0: add_disk(content, vm, args.disk_size, args.disk_type) customize_network(content, vm, args.ip, args.gateway, args.mask, args.hostname) power_on(vm) time.sleep(10) info = get_info(vm) except Exception as e: print(str(e)) sys.exit(-1) print(info)
def clone_vm_from_no(vm_no, temp_no): # """ # 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") 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') from random import randint #vm_name_no = randint(1,100) vm_name = 'CentOS_' + str(vm_no) clone_vm(content, template, vm_name, si, None, 'vm_cloned_from_template', None, None, None, False, None) return vm_name
def __init__(self, host, user, password, port): self.si = SmartConnectNoSSL(host=host, user=user, pwd=password, port=port) # disconnect this thing atexit.register(Disconnect, self.si) self.content = self.si.RetrieveContent()
def main(): """Generate HTML5 console for a specific VM""" args = get_args() try: if args.disable_ssl_verification: service_instance = SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) except Exception as e: print("Could not connect to vSphere host") print(repr(e)) sys.exit(1) atexit.register(Disconnect, service_instance) content = service_instance.RetrieveContent() vm = get_vm(content, args.name) vm_moid = vm._moId vcenter_data = content.setting vcenter_settings = vcenter_data.setting console_port = '7331' for item in vcenter_settings: key = getattr(item, 'key') if key == 'VirtualCenter.FQDN': vcenter_fqdn = getattr(item, 'value') session_manager = content.sessionManager session = session_manager.AcquireCloneTicket() vc_cert = ssl.get_server_certificate((args.host, int(args.port))) vc_pem = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, vc_cert) vc_fingerprint = vc_pem.digest('sha1') print("\nOpen the following URL in your browser to access the" + " remote console.\n") print("You have 60 seconds to open the URL, or the session" + " will be terminted.\n") print("http://" + args.host + ":" + console_port + "/console/?vmId=" + str(vm_moid) + "&vmName=" + args.name + "&host=" + vcenter_fqdn + "&sessionTicket=" + session + "&thumbprint=" + vc_fingerprint.decode('utf-8')) print("\nWaiting 60 seconds, then exit") time.sleep(60)
def main(): #connect info host = '192.168.9.242' #vSpehre service to connect to user = '******' pwd = 'infohold123ABC@' port = '443' no_ssl = True # connect this thing si = None if no_ssl: si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port) else: si = SmartConnect(host=host, user=user, pwd=pwd, port=port) # disconnect this thing # 程序退出时断开连接。 atexit.register(Disconnect, si) content = si.RetrieveContent() #虚拟机参数 vm_name = 'test2' # 虚拟机名称 templatename = 'centos-7.7-1908-zabbix-1-234' # 模板 datacenter_name = 'center' # 数据中心 vm_folder = 'Test' # 文件夹 datastore_name = 'SAS-196' # 存储 cluster_name = 'cluster' # 集群 resource_pool = '' # 资源池 power_on = False # 'power on the VM after creation datastorecluster_name = '' #数据存储群集 vm = get_obj(content, [vim.VirtualMachine], vm_name) #return if vm: print('Virtual machine {0} already exists'.format(vm.name)) return datacenter = get_obj(content, [vim.Datacenter], datacenter_name) if not datacenter: print('datecenter not found!') return template = get_obj(content, [vim.VirtualMachine], templatename) if not template: print('template not found!') return destfolder = get_obj(content, [vim.Folder], vm_folder) if not destfolder: print('folder not found!') return #print('template:{0} datacenter:{1} destfolder:{2}'.format(template.name, datacenter.name, destfolder.name)) clone_vm(content, template, vm_name, si, datacenter_name, vm_folder, datastore_name, cluster_name, power_on, resource_pool, datastorecluster_name)
def run(host, user, pwd, port): try: si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port) sitime = si.CurrentTime() atexit.register(Disconnect, si) content = si.RetrieveContent() except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return False, error.msg return content