def dosnmp(self): """ Simple command-line program for listing the virtual machines on a system. """ if not self.v_host or not self.v_pass or not self.v_user: return "" context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE si = SmartConnect(host=self.v_host, user=self.v_user, pwd=self.v_pass, port=int(self.v_port), sslContext=context) if not si: return "" atexit.register(Disconnect, si) content = si.RetrieveContent() result = [] for child in content.rootFolder.childEntity: if hasattr(child, 'vmFolder'): datacenter = child vmFolder = datacenter.vmFolder vmList = vmFolder.childEntity for vm in vmList: item_res = self.ReturnVmInfo(vm) result.append(item_res) return result
def connect_to_vcenter(self): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE self.service_instance = SmartConnect(host=self.vcenter_server, user=self.vcenter_username, pwd=self.vcenter_password, port=self.port, sslContext=context) self.content = self.service_instance.RetrieveContent() atexit.register(Disconnect, self.service_instance)
def main(): args = getargs() criticals = {} warnings = {} normals = {} perf = [] si = SmartConnect(host=args.host, user=args.username, pwd=args.password, port=443) atexit.register(Disconnect, si) content = si.RetrieveContent() ds_obj_list = get_obj(content) for datastore in ds_obj_list: name, perc = print_datastore_info(datastore) if args.warning > perc > args.critical: warnings[name] = str(perc) elif perc <= args.critical: criticals[name] = str(perc) else: normals[name] = str(perc) if len(criticals) > 0: print('Critical: Some Datastores have low space') for name in criticals: print('Critical: ' + name + ' has ' + criticals[name] + '%') perf.append(name + '_' + 'Free_space=%s' % criticals[name]) if len(warnings) > 0: for name in warnings: print('Warning: ' + name + ' has ' + warnings[name] + '%') perf.append(name + '_' + 'Free_space=%s' % warnings[name]) for name in normals: print('Normal: ' + name + ' has ' + normals[name] + '%') perf.append(name + '_' + 'Free_space=%s' % normals[name]) print('|' + ' '.join(perf)) exit(2) elif len(warnings) > 0: print('Warning: Some Datastores have warning space') for name in warnings: print('Warning: ' + name + ' has ' + warnings[name] + '%') perf.append(name + '_' + 'Free_space=%s' % warnings[name]) for name in normals: print('Normal: ' + name + ' has ' + normals[name] + '%') perf.append(name + '_' + 'Free_space=%s' % normals[name]) print('|' + ' '.join(perf)) exit(1) else: print('Normal: All Datastores have Normal space') for name in normals: print('Normal: ' + name + ' has ' + normals[name] + '%') perf.append(name + '_' + 'Free_space=%s' % normals[name]) print('|' + ' '.join(perf)) exit(0)
def connect(): try: if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() si = SmartConnect(host=ConnectionSettings.hostname(), user= ConnectionSettings.username() , pwd=ConnectionSettings.password(), port=443, sslContext=None) if not si: return -1 # Disconnect from server atexit.register(Disconnect, si) content = si.RetrieveContent() return content except: return "Connection Failed"
def ds_beat(host, user, pwd, port): si = SmartConnect( host=host, user=user, pwd=pwd, port=port) atexit.register(Disconnect, si) content = si.RetrieveContent() ds_obj_list = get_obj(content, [vim.Datastore], None) info_list = [] for ds_obj in ds_obj_list: ds = {} summary = ds_obj.summary ds_capacity = summary.capacity ds_freespace = summary.freeSpace ds_uncommitted = summary.uncommitted if summary.uncommitted else 0 ds_provisioned = ds_capacity - ds_freespace + ds_uncommitted ds['bk_stora_name'] = summary.name ds['bk_stora_cap'] = sizeof_fmt(ds_capacity) ds['bk_free_spa'] = sizeof_fmt(ds_freespace) ds['bk_prem_spa'] = sizeof_fmt(ds_provisioned) ds['bk_stora_path'] = summary.url info_list.append(ds) #补充数据获取 objview = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) esxi_hosts = objview.view objview.Destroy() for esxi_host in esxi_hosts: # 遍历所有主机挂载的存储节点 storage_system = esxi_host.configManager.storageSystem host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo for host_mount_info in host_file_sys_vol_mount_info: for ds in info_list: if ds['bk_stora_name'] == host_mount_info.volume.name: ds['bk_file_system'] = host_mount_info.volume.type + host_mount_info.volume.version ds['bk_fs_block'] = host_mount_info.volume.blockSizeMb ds['bk_dir_type'] = 'HDD' if host_mount_info.volume.ssd else 'SSD' return info_list
def main(): args = GetArgs() service_instance = None context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE try: service_instance = SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port), sslContext=context) if not service_instance: print("Could not authenticate with the specified ESXi host using " "the supplied credentials") return -1 atexit.register(Disconnect, service_instance) content = service_instance.RetrieveContent() # Search for all VMs container = content.viewManager.CreateContainerView( content.rootFolder, [], True) view = container.view for object in view: if str(object).startswith("'vim.HostSystem"): print(object) print(object.summary.managementServerIp) for vm in object.vm: print(vm) container.DestroyView() except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1
def main(): """ Simple command-line program for listing the virtual machines on a system. """ 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)) context = None if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) 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() for child in content.rootFolder.childEntity: if hasattr(child, 'vmFolder'): datacenter = child vmFolder = datacenter.vmFolder vmList = vmFolder.childEntity for vm in vmList: PrintVmInfo(vm) return 0
def auth_vcenter_soap(): print('Authenticating to vCenter SOAP API, user: {}'.format(username)) context = None if sys.version_info[:3] > (2, 7, 8): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE pattern = '(?:http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' parsed = re.search(pattern, url) host = parsed.group('host') si = SmartConnect(host=host, user=username, pwd=password, port=443, sslContext=context) atexit.register(Disconnect, si) return si
class VCenter: def __init__(self): self.pyVmomi = __import__("pyVmomi") self.vcenter_server = '192.168.51.20' self.vcenter_username = '******' self.vcenter_password = '******' self.port = 443 # self.isDHCP=False, # self.vm_ip = '10.7.42.91', self.subnet = '255.255.255.0', # self.gateway= '10.7.42.40', # self.dns= ['company.com', 'company.com'], # self.domain= 'esx10g.company.com' def connect_to_vcenter(self): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE self.service_instance = SmartConnect( host = self.vcenter_server, user = self.vcenter_username, pwd = self.vcenter_password, port = self.port, sslContext = context) self.content = self.service_instance.RetrieveContent() atexit.register(Disconnect, self.service_instance) def wait_for_task(self, task, actionName='job', hideResult=False): while task.info.state == (self.pyVmomi.vim.TaskInfo.State.running or self.pyVmomi.vim.TaskInfo.State.queued): time.sleep(2) if task.info.state == self.pyVmomi.vim.TaskInfo.State.success: if task.info.result is not None and not hideResult: out = '%s completed successfully, result: %s' % (actionName, task.info.result) print out else: out = '%s completed successfully.' % actionName print out elif task.info.state == self.pyVmomi.vim.TaskInfo.State.error: out = 'Error - %s did not complete successfully: %s' % (actionName, task.info.error) raise ValueError(out) return task.info.result def list_obj(self, vimtype): container = self.content.viewManager.CreateContainerView(self.content.rootFolder, vimtype, True) return container.view def get_obj(self, vimtype, name): obj = None container = self.content.viewManager.CreateContainerView(self.content.rootFolder, vimtype, True) for c in container.view: if c.name == name: obj = c break return obj def get_folder(self, folder_name=''): """获取文件夹""" folder_list = [] if folder_name == '': listOBJ = self.list_obj([vim.Folder]) else: listOBJ = self.get_obj([vim.Folder],folder_name) for each in listOBJ: folder_list.append(each) return folder_list def get_vcenters(self): """获取所有数据中心""" listOBJ = self.list_obj([vim.Datacenter]) vcenters_list = [] for each in listOBJ: vcenters_list.append(each) return each def get_datastore(self, datastore_name=''): """获取存储""" datastore_list = [] if datastore_name == '': listOBJ = self.list_obj([vim.Datastore]) else: listOBJ = self.get_obj([vim.Datastore],datastore_name) for each in listOBJ: datastore_list.append(each.name) return datastore_list def get_clusters(self,clusters_name=''): """获取所有的集群""" clusters_list = [] if clusters_name == '': listOBJ = self.list_obj([vim.ClusterComputeResource]) else: listOBJ = self.get_obj([vim.ClusterComputeResource],clusters_name) for each in listOBJ: clusters_list.append(each.name) return clusters_list def get_resource_pool(self,resource_pool_name=''): """获取所有的资源池""" resource_pool_list = [] if resource_pool_name == '': listOBJ = self.list_obj([vim.ResourcePool]) else: listOBJ = self.get_obj([vim.ResourcePool],resource_pool_name) for each in listOBJ: resource_pool_list.append(each.name) return resource_pool_list def get_hosts(self): """获取所有的宿主机""" listOBJ = self.list_obj([vim.HostSystem]) index = 0 for each in listOBJ: tupleVNic=sys._getframe().f_code.co_name, index, each.config.network.vnic for eachvnic in tupleVNic[2]: index = index + 1 print sys._getframe().f_code.co_name, \ index, \ each, \ eachvnic.portgroup, \ eachvnic.spec.mac, \ eachvnic.spec.ip.ipAddress, eachvnic.spec.ip.subnetMask def get_pnic(self): """获取所有的上行口""" listOBJ = self.list_obj([vim.HostSystem]) index = 0 for each in listOBJ: tuplePNic=sys._getframe().f_code.co_name, index, each.config.network.pnic for eachpnic in tuplePNic[2]: index = index + 1 print sys._getframe().f_code.co_name, index, each, eachpnic.device def get_vswitchs(self): """获取所有的交换机(包括标准交换机和分布式交换机)""" return self.list_obj([vim.HostSystem]) def get_portgroups(self): """获取所有的交换机端口组(包括标准交换机和分布式交换机)""" listOBJ = self.list_obj([vim.Network]) for each in listOBJ: print sys._getframe().f_code.co_name, each def get_vns(self): """获取所有的虚拟网络(包括标准交换机端口组和分布式交换机端口组)""" try: return self.list_obj([vim.Network]) except Exception as e: print e def get_dvswitchs(self): """获取所有的分布式交换机""" return self.list_obj([vim.DistributedVirtualSwitch]) def get_dvportgroups(self): """获取所有的分布式交换机端口组""" listOBJ = self.list_obj([vim.DistributedVirtualSwitch]) index = 0 for each in listOBJ: for eachportgroup in each.portgroup: index = index + 1 print sys._getframe().f_code.co_name,index,eachportgroup def get_vnic(self): """获取所有的虚拟网卡""" listOBJ = self.list_obj([vim.VirtualMachine]) index = 0 for each in listOBJ: index = index + 1 vmdeviceList = each.config.hardware.device for eachdevice in vmdeviceList: index = index + 1 if isinstance(eachdevice, vim.vm.device.VirtualEthernetCard ): if isinstance( eachdevice.backing,vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo ): print sys._getframe().f_code.co_name,\ index, \ eachdevice.deviceInfo.label, \ eachdevice.macAddress, \ eachdevice.deviceInfo.summary, \ eachdevice.backing.port.portgroupKey else: print sys._getframe().f_code.co_name,\ index, \ eachdevice.deviceInfo.label, \ eachdevice.macAddress, \ eachdevice.backing.deviceName, \ eachdevice.backing.network def get_allvms(self): """获取所有的虚机""" listOBJ = self.list_obj([vim.VirtualMachine]) index = 0 for each in listOBJ: index = index + 1 print sys._getframe().f_code.co_name,index,each.name def print_vm_info(self, virtual_machine, depth=1): """打印虚机信息""" maxdepth = 10 if hasattr(virtual_machine, 'childEntity'): if depth > maxdepth: return vmList = virtual_machine.childEntity for c in vmList: self.print_vm_info(c, depth + 1) return summary = virtual_machine.summary print "Name : ", summary.config.name print "Path : ", summary.config.vmPathName print "Guest : ", summary.config.guestFullName annotation = summary.config.annotation if annotation: print "Annotation : ", annotation print "State : ", summary.runtime.powerState if summary.guest is not None: ip_address = summary.guest.ipAddress if ip_address: print "IP : ", ip_address if summary.runtime.question is not None: print "Question : ", summary.runtime.question.text print "" def get_acquireTicket(self,virtual_machine): """获取主机Console授权""" acquireTickets_dict = {} listOBJ = self.get_obj([vim.VirtualMachine],virtual_machine) try: acquireTickets = listOBJ.AcquireTicket('webmks') except Exception as err: print 'acquireTickets_err:',err acquireTickets_dict['host'] = acquireTickets.host acquireTickets_dict['port'] = acquireTickets.port acquireTickets_dict['ticket'] = acquireTickets.ticket print acquireTickets_dict return acquireTickets_dict def get_hosts_exsi_version(self,virtual_machine): """获得主机Esxi版本""" try: hosts_name = self.get_obj([vim.VirtualMachine],virtual_machine).summary.runtime.host for i in self.list_obj([vim.HostSystem]): if i == hosts_name: hosts_ip = i.name listOBJ = self.get_obj([vim.HostSystem],hosts_ip) try: exsi_version = listOBJ.summary.config.product.fullName except Exception as err: print err exsi_version = '' except Exception as err: print err exsi_version = '' return exsi_version
def _get_instances(self, inkwargs): ''' Make API calls ''' instances = [] try: si = SmartConnect(**inkwargs) except ssl.SSLError as connection_error: if '[SSL: CERTIFICATE_VERIFY_FAILED]' in str( connection_error) and self.validate_certs: sys.exit("Unable to connect to ESXi server due to %s, " "please specify validate_certs=False and try again" % connection_error) except Exception as exc: self.debugl("Unable to connect to ESXi server due to %s" % exc) sys.exit("Unable to connect to ESXi server due to %s" % exc) self.debugl('retrieving all instances') if not si: sys.exit("Could not connect to the specified host using specified " "username and password") atexit.register(Disconnect, si) content = si.RetrieveContent() # Create a search container for virtualmachines self.debugl('creating containerview for virtualmachines') container = content.rootFolder viewType = [vim.VirtualMachine] recursive = True containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view for child in children: # If requested, limit the total number of instances if self.args.max_instances: if len(instances) >= self.args.max_instances: break instances.append(child) self.debugl("%s total instances in container view" % len(instances)) if self.args.host: instances = [x for x in instances if x.name == self.args.host] instance_tuples = [] for instance in sorted(instances): if self.guest_props: ifacts = self.facts_from_proplist(instance) else: ifacts = self.facts_from_vobj(instance) instance_tuples.append((instance, ifacts)) self.debugl('facts collected for all instances') try: cfm = content.customFieldsManager if cfm is not None and cfm.field: for f in cfm.field: if not f.managedObjectType or f.managedObjectType == vim.VirtualMachine: self.custom_fields[f.key] = f.name self.debugl('%d custom fields collected' % len(self.custom_fields)) except vmodl.RuntimeFault as exc: self.debugl("Unable to gather custom fields due to %s" % exc.msg) except IndexError as exc: self.debugl("Unable to gather custom fields due to %s" % exc) if self.include_tags: instance_tuples_with_tags = [] vcenter_url = self.get_rest_vcenter_url() vcenter_vm_tags = vcenter_url + "/com/vmware/cis/tagging/tag-association?~action=list-attached-tags" session_id = self.get_rest_session_id() for instance in instance_tuples: vmuid = instance[0] vm = str(vmuid).strip("'") type, vmid = vm.split(':') type = type.split('.')[-1] vmobj = {"object_id": {"type": type, "id": vmid}} resp = requests.post(vcenter_vm_tags, data=json.dumps(vmobj), headers={ 'vmware-api-session-id': session_id, 'content-type': 'application/json' }, verify=self.validate_certs) tag_ids = resp.json()['value'] instance_tags = {} if len(tag_ids) > 0: for tag_id in tag_ids: tag_category = self.tags[tag_id]['category']['name'] tag_name = self.tags[tag_id]['name'] if tag_category not in instance_tags: instance_tags[tag_category] = [] instance_tags[tag_category].append(tag_name) instance[1].update({"tags": instance_tags}) return instance_tuples
def main() : opts=validate_options() hostDataFrame = pd.DataFrame() dsDataFrame = pd.DataFrame() vmSummaryDataFrame = pd.DataFrame() vmSummaryErrorDataFrame = pd.DataFrame() # check SSL certificates s=ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode=ssl.CERT_NONE try: si= SmartConnect(host=opts.shost,user=opts.username,pwd=opts.password ,sslContext=s ) print_green('Valid certificate') content = si.RetrieveContent() #print about information : function call about_information(si.content.about ,si.content.rootFolder.childEntity[0].hostFolder.childEntity[0].host[0] ) #disconnect the connection when program exists atexit.register(Disconnect, si) ds_count = 0 for datacenter in content.rootFolder.childEntity: print("Data Center Name : ", datacenter.name ) #print(type(datacenter)) ds_count += 1 if printVM: if hasattr(datacenter.vmFolder, 'childEntity'): vmFolder = datacenter.vmFolder vmList = vmFolder.childEntity for vm in vmList: printVmInformation(vm) if printDatastore: datastores = datacenter.datastore for ds in datastores: printDatastoreInformation(ds) if printHost: if hasattr(datacenter.vmFolder, 'childEntity'): hostFolder = datacenter.hostFolder computeResourceList = hostFolder.childEntity for computeResource in computeResourceList: printComputeResourceInformation(computeResource) print("Total Data Center(s) : ", ds_count ) dsDataFrame = pd.DataFrame(list(zip(ds_name, ds_capacity, ds_provisionedSpace,ds_freeSpace,ds_freeSpacePercentage)), columns=["ds_name", "ds_capacity", "ds_provisionedSpace","ds_freeSpace","ds_freeSpacePercentage"]) dsDataFrame.to_csv("C:/Users/joshia2/Desktop/esxi_akhilesh/output_files/DataStore_Data.csv",index=False) hostDataFrame = pd.DataFrame(list(zip(host_name, host_CPUusage, host_memoryCapacity,host_memoryUsage,host_freeMemoryPercentage)), columns=["host_name", "host_CPUusage", "host_memoryCapacity","host_memoryUsage","host_freeMemoryPercentage"]) #print(hostDataFrame) hostDataFrame.to_csv("C:/Users/joshia2/Desktop/esxi_akhilesh/output_files/hostData.csv",index=False) vmSummaryDataFrame = pd.DataFrame(list(zip(vmSummaryName, vmSummaryMoRef, vmSummaryPowerState)), columns=["vmSummaryName", "vmSummaryMoRef", "vmSummaryPowerState"]) vmSummaryDataFrame.to_csv("C:/Users/joshia2/Desktop/esxi_akhilesh/output_files/vmSummary.csv",index=False) vmSummaryErrorDataFrame = pd.DataFrame(list(zip(notAccessibleVM, error_notAccessibleVM)), columns=["notAccessibleVM", "error_notAccessibleVM"]) vmSummaryErrorDataFrame.to_csv("C:/Users/joshia2/Desktop/esxi_akhilesh/output_files/vmSummaryError.csv",index=False) except: print_red('Unable to connect to host : invalid credentials or invalid/untrusted certificate') print_red("Please try connecting again")
print("Oops ..! The operation is forbidden :(") return "Done.. Checking..!!" try: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE vms = {} msg = "Is this the VM to reboot (y/n)?" ############################################################################## # update the values of host user pwd accordingly ############################################################################## connect = SmartConnect(host="host", user="******", pwd='password', sslContext=context) content = connect.content container = content.viewManager.CreateContainerView( content.rootFolder, [vim.VirtualMachine], True) arg = getArgs() for managed_object_ref in container.view: vms.update({managed_object_ref: managed_object_ref.name}) print(performOperation(vms, arg)) except Exception as e: print('Error: ' + str(e)) finally:
if "\\" in FOLDER: FOLDER = FOLDER.split("\\")[1] if parser.parse_args().s: SERVER = parser.parse_args().s roots = Tk() try: Client = SmartConnect(host=SERVER, user=USER, pwd=PASSWORD, port=PORT, sslContext=ssl._create_unverified_context()) except: roots.title("Error connecting") roots.geometry("300x100") Label(roots, text="Couldn't connect to server").pack(side="top") Label(roots, text="Please verify credentials and connectivity").pack(side="top") if getattr(sys, 'frozen', False):