python脚本自动统计vcenter数据
#!/usr/bin/python3 # -*- coding:utf-8 -*- # @Time : 2021-06-17 # @Author : huss # 通过vcenter api获取所有数据中心、集群、物理机、VM虚拟机以及虚拟机IP地址、电源状态、主机名和备注名信息 from pyVmomi import vim from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL import atexit import argparse import datetime import re def get_args(): parser = argparse.ArgumentParser( description='Arguments for talking to vCenter') # -s 10.210.194.250 -u 'monitor@bnqc.local' -p 'Bnqc!@2020' parser.add_argument('-s', '--host', #required=True, default='10.210.xx.xx', action='store', help='vSpehre service to connect to') parser.add_argument('-o', '--port', type=int, default=443, action='store', help='Port to connect on') parser.add_argument('-u', '--user', #required=True, default='xxxxxxxx@bnqc.local', action='store', help='User name to use') parser.add_argument('-p', '--password', #required=True, default='xxxxxxxx', action='store', help='Password to use') args = parser.parse_args() return args def get_obj(content, vimtype, name=None): ''' 列表返回,name 可以指定匹配的对象 ''' container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True) obj = [ view for view in container.view] return obj def get_all_object(): # args = get_args() # print(args) # connect this thing #si = SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=args.port) si = SmartConnectNoSSL(host='10.210.194.250', user='monitor@bnqc.local', pwd='Bnqc!@2020', port=443) # disconnect this thing atexit.register(Disconnect, si) content = si.RetrieveContent() #dc = content.rootFolder.childEntity #print(content.rootFolder.childEntity[0].hostFolder.childEntity[0].host[0].name) datacenter = [] cluster = [] esxi = [] vms = [] vm_details = [] for i in content.rootFolder.childEntity: datacenter.append(i.name) #获取所有数据中心(机房)名称 #if i.name == 'Datacenter-AoFei': #print(i.hostFolder.childEntity) for j in i.hostFolder.childEntity: cluster.append(j.name) #获取所有集群名称 #print(j.host) for k in j.host: esxi.append(k) #获取所有esxi物理机IP #print(k.vm) for m in k.vm: #vms.append(m.guest.ipAddress) #获取所有VM虚拟机IP if m.guest.ipAddress: vm_ipaddress = m.guest.ipAddress for p in m.guest.net: for q in p.ipAddress: if re.match('10.2', q): vm_ipaddress = q break else: continue break else: vm_ipaddress = '0.0.0.0' vm_details.append(vm_ipaddress + ':' + m.runtime.powerState + ':' + str(m.guest.hostName) + ':' + m.name) vms.append(vm_ipaddress) print('datacenter:', datacenter) print('cluster:', cluster) print('esxi:', esxi) print('ESXI物理机总数:', len(esxi)) print(vms) print('虚拟机总数', len(vms)) return vm_details if __name__ == '__main__': vm_details = get_all_object() filehead = '#---' + str(datetime.datetime.now()) + '同步vcenter api数据' for i in vm_details: print(i) # 把所有VMS数据写入文件存档 # f = open("cmdb.conf", "w+") # f.write(filehead + '\n') # for line in vm_list: # f.write(line + '\n') # f.close()