从VC中获取VM信息的自动化脚本
pyVmomi is the Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter.
说明:
该脚本自动从VC中获取VM5个信息; hostname, ip, cpu, memory, owner
# -*- coding:utf-8 -*- """ Python program for listing the vms on an ESX / vCenter host """ import atexit import base64 import csv from pyVim import connect from pyVmomi import vim import ssl ssl._create_default_https_context = ssl._create_unverified_context def get_vm_info(vm_container): """ Co-routine, produce vm name and ipAddress """ for child in vm_container: if child.summary.runtime.powerState == "poweredOn": try: vm_owner = child.summary.customValue[0].value except IndexError as e: vm_owner = "No_config" yield (child.summary.config.name, child.summary.guest.ipAddress, int(child.summary.config.memorySizeMB/1024), child.summary.config.numCpu, vm_owner) def get_owner(filename): """Get User email and ad account, return User dict""" user_dict = {} with open(filename, encoding="utf-8") as f_obj: for row in f_obj: email, account = row.split() user_dict[account] = email return user_dict def write_to_file(vm_container, server, filename): """ Through the co-routine get vm name and ip, then output to txt and csv file """ user = get_owner(filename) vm_yield = get_vm_info(vm_container) f1_obj = open("vm_list.txt", "a") f2_obj = open("vm_list.csv", "w", newline='') csv_writer = csv.writer(f2_obj) csv_writer.writerow(["hostname", "ip", "memory", "cpu", "owner"]) try: while True: hostname, ip, memory, cpu, owner = vm_yield.__next__() f1_obj.write("%s,%s,%s,%s,%s\n" % (hostname, ip, memory, cpu, user.get(owner, "No_config"))) csv_writer.writerow([hostname, ip, memory, cpu, user.get(owner, "No_config")]) except StopIteration: print("Get all vms complete on %s!" % server) f1_obj.close() f2_obj.close() def main(server, filename): """ Simple command-line program for listing the virtual machines on a system. """ service_instance = connect.SmartConnect(host=server, user="administrator@vsphere.local", pwd=base64.decodebytes(b'VkdDbG9jYWxhZG1pbkAyMDEy\n').decode(), ) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() container = content.rootFolder # starting point to look into view_type = [vim.VirtualMachine] # object types to look for recursive = True # whether we should look into it recursively container_view = content.viewManager.CreateContainerView( container, view_type, recursive) children = container_view.view write_to_file(children, server, filename) if __name__ == "__main__": vc_server_list = ("10.120.137.37", "10.120.137.38", "10.120.137.39") # vc_server_list = ("10.120.137.37",) user_file = input("Please input user list filename:") for vc_server in vc_server_list: main(vc_server, user_file)