python vmware esxi接口
2020-04-26 本文已影响0人
路破格
依赖包,pyVmomi(兼容python2.x和3.x)和pysphere(python3.x会报错)都是取vmware接口,由于之前没研究透,两个混用,有时间再拆分成单个库
pip install pyVmomi
pip install pysphere
get_vmware_info.py
#-*- coding=utf-8 -*-
#-*- encoding:utf-8 -*-
import re
import sys
import ssl
import traceback
import atexit
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL
from pysphere import VIServer
from pysphere import VIException, VIApiException, FaultTypes
default_encoding = "utf-8"
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
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_vmware_vcenter_server():
'''
需要自行修改
'''
vmware_vcenter_server = {
"host": "{yourhost}",
"user": "{youruser}",
"pwd": "{yourpasswd}",
"port": 443
}
return vmware_vcenter_server
def get_vmware_hosts():
'''
获取宿主机资产
'''
vmware_vcenter_server = get_vmware_vcenter_server()
si = SmartConnectNoSSL(
host = vmware_vcenter_server['host'],
user = vmware_vcenter_server['user'],
pwd = vmware_vcenter_server['pwd'],
port = vmware_vcenter_server['port'],
)
atexit.register(Disconnect, si)
content = si.RetrieveContent()
esxi_obj = get_obj(content, [vim.HostSystem])
hosts = {}
for esxi in esxi_obj:
sn = esxi.name
for i in esxi.summary.hardware.otherIdentifyingInfo:
if isinstance(i, vim.host.SystemIdentificationInfo):
sn = i.identifierValue
hosts[sn] = {}
hosts[sn]['product'] = esxi.summary.hardware.vendor
hosts[sn]['model'] = esxi.summary.hardware.model
hosts[sn]['ip'] = esxi.name
hosts[sn]['cpu_model'] = esxi.summary.hardware.cpuModel
hosts[sn]['cpu_physicals'] = esxi.summary.hardware.numCpuPkgs
hosts[sn]['cpu_cores'] = esxi.summary.hardware.numCpuThreads
hosts[sn]['mem_total'] = "%.1f" % (float(esxi.summary.hardware.memorySize) / 1024 / 1024 / 1024)
disk_total = 0.0
disks = ""
for ds in esxi.datastore:
disk_total = disk_total + float((ds.summary.capacity) / 1024 / 1024 / 1024)
disks = disks + "%s: %dGB" % (ds.name, disk_total)
hosts[sn]['disk_total'] = disk_total
hosts[sn]['disks'] = disks
hosts[sn]['os'] = esxi.summary.config.product.fullName
print(json.dumps(hosts), indent = "2")
def get_vmware_virtual_hosts(idc = ""):
'''
获取虚拟机资产
'''
vmware_vcenter_server = get_vmware_vcenter_server()
ssl._create_default_https_context = ssl._create_unverified_context
server = VIServer()
server.connect(
vmware_vcenter_server['host'],
vmware_vcenter_server['user'],
vmware_vcenter_server['pwd']
)
vms_list = server.get_registered_vms()
re_ip = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
re_exclude_ip = re.compile(r'^172\.17\.')
vms_hosts = {}
for vms in vms_list:
try:
vms_object = server.get_vm_by_path(vms)
vms_info = vms_object.__dict__
ip = ""
if 'ip_address' in vms_info['_properties'] and (not re_exclude_ip.match(vms_info['_properties']['ip_address'])):
ip = vms_info['_properties']['ip_address']
else:
if re_ip.match(vms.split(" ")[1]):
ip = re_ip.findall(vms.split(" ")[1])[0]
if ip in old_vms_copy and old_vms_copy[ip]['vname'] != vms_name:
print(vms + ", ip conflict.")
continue
else:
print(vms + ", ip not found.")
continue
vms_hosts[ip] = {}
status = 2
if vms_object.get_status() == "POWERED ON":
status = 1
vms_hosts[ip]['status'] = status
vms_hosts[ip]['physics_host'] = re_ip.findall(vms.split(" ")[0])[0]
vms_hosts[ip]['vms_name'] = vms_info['_properties']['name']
vms_hosts[ip]['cpu'] = vms_info['_properties']['num_cpu']
vms_hosts[ip]['memory'] = "%.1f" % (float(vms_info['_properties']['memory_mb']) / 1024)
disk = 0.0
for disk_file in vms_info['_disks']:
try:
disk += float(disk_file['device']['capacityInKB']) / 1024 / 1024
except Exception, e:
print(e)
vms_hosts[ip]['disk'] = disk
hostname = ""
if 'hostname' in vms_info['_properties']:
hostname = vms_info['_properties']['hostname']
vms_hosts[ip]['hostname'] = hostname
server.disconnect()
print(json.dumps(vms_hosts, indent = 2))
if __name__ == "__main__":
try:
get_vmware_virtual_hosts()
get_vmware_hosts()
except Exception as e:
traceback.print_exc()