#!/usr/local/python
# -*- coding: utf-8 -*-
import requests
import json
import logging
# Function to get the vCenter server session
def get_vc_session(vcip, username, password):
s.post('https://' + vcip + '/rest/com/vmware/cis/session', auth=(username, password))
return s
# Function to get all the VMs from vCenter inventory
def get_vms(vcip,host=''):
vms = s.get('https://' + vcip + '/rest/vcenter/vm'+"?filter.hosts="+str(host))
return vms
def get_hosts(vcip,cluster=''):
result = s.get('https://' + vcip + '/rest/vcenter/host'+"?filter.clusters="+str(cluster))
return result
def get_clusters(vcip,dc=''):
clusters = s.get('https://' + vcip + '/rest/vcenter/cluster'"?filter.datacenters="+str(dc))
return clusters
def get_clusterinfo(vcip,cluster):
clusterinfo = s.get('https://' + vcip + '/rest/vcenter/cluster/'+cluster)
return clusterinfo
def get_datacenters(vcip):
datacenters = s.get('https://' + vcip + '/rest/vcenter/datacenter')
return datacenters
def get_datacenterinfo(vcip,datacenter):
datacenterinfo = s.get('https://' + vcip + '/rest/vcenter/datacenter/'+datacenter)
return datacenterinfo
# Function to power on particular VM
def poweron_vm(vmmoid, vcip):
s.post('https://' + vcip + '/rest/vcenter/vm/' + vmmoid + '/power/start')
# Function to power off particular VM
def poweroff_vm(vmmoid, vcip):
s.post('https://' + vcip + '/rest/vcenter/vm/' + vmmoid + '/power/stop')
def getfolder(vcip):
folderinfo = s.get('https://' + vcip + '/rest/vcenter/folder')
print(folderinfo)
print(dir(folderinfo))
return json.loads(folderinfo.content).values()[0]
def gethostlistinfo(vcip):
info=get_datacenters(vcip)
for dc in json.loads(info.content).values()[0]:
dcname=dc.get("name")
dcvalue = dc.get("datacenter")
#print(dcname,dcvalue)
info=get_clusters(vcip, dc=dcvalue)
for cls in json.loads(info.content).values()[0]:
clustername=cls.get("name")
clustervalue = cls.get("cluster")
#print(dcname,clustername,clustervalue)
info=get_hosts(vcip,cluster=clustervalue)
for h in json.loads(info.content).values()[0]:
hostip=h.get("name")
hostvalue = h.get("host")
constate = h.get("connection_state")
hostPowerState = h.get("power_state")
#print(vcip,dcname,clustername,hostip,constate,power_state)
info=get_vms(vcip,hostvalue)
for v in json.loads(info.content).values()[0]:
vmname = v.get("name")
vmvalue = v.get("vm")
vmMemSize = v.get("memory_size_MiB")
vmCpuCount = v.get("cpu_count")
vmPowerState = v.get("power_state")
print(vcip,dcname,clustername,hostip,constate,hostPowerState,vmname,vmMemSize,vmCpuCount,vmPowerState)
###main####
vcip='172.**.***.***'
username="administrator@vsphere.local"
password="YVd5********"
logging.captureWarnings(True)
global s
s = requests.Session()
s.verify = False
s = get_vc_session(vcip, username, password)
info=gethostlistinfo(vcip)
技术分享,个人收藏,并非原著,并非商用。
浙公网安备 33010602011771号