Python3 used to query vCenter server v8 for virtual Machines and their provisioned CPU, Memory, Disk space and Network information. The results are saved as CSV file. Hopefully can help someone getting started. Nothing complicated with the search for the bound IP address. Since the network interfaces are stored as an array with each interface having an array of IP addresses, I settled on the first IPv4 address that is retrieved. There may be better ways to do this such as using Powershell or other API calls. The intent is show the possibility of using python with vCenter server.
import requests
import csv
import json
import configparser
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def get_vm_netInterface(auth,vcip,vm):
try:
response = requests.get("https://"+vcip+"/api/vcenter/vm/"+vm+"/guest/networking/interfaces", headers={"vmware-api-session-id": auth}, verify=False)
except requests.exceptions.RequestException as Err:
raise SystemExit(Err)
if response.ok:
i = 0;
while i < len(response.json()):
if (response.json()[i]['ip']['ip_addresses']):
j = 0;
while j < len(response.json()[i]['ip']['ip_addresses']):
if "." in response.json()[i]['ip']['ip_addresses'][j]['ip_address']:
guestIP = response.json()[i]['ip']['ip_addresses'][j]['ip_address']
guestPrefix = response.json()[i]['ip']['ip_addresses'][j]['prefix_length']
message = guestIP+"/"+str(guestPrefix)
return (message)
j += 1;
i += 1;
return ("")
def get_vm_netinfo(auth,vcip,vm):
try:
response = requests.get("https://"+vcip+"/api/vcenter/vm/"+vm+"/guest/networking", headers={"vmware-api-session-id": auth}, verify=False)
except requests.exceptions.RequestException as Err:
raise SystemExit(Err)
if response.ok and 'dns' in response.json():
# print(response.json())
HostName = response.json()['dns_values']['host_name']
HostDomain = response.json()['dns_values']['domain_name']
if "." in HostName:
message = HostName.split('.')[0]+"."+HostDomain
else:
message = HostName+"."+HostDomain
return (message)
return ("")
def get_vm_config(outFile,auth,vcip,vm):
try:
response = requests.get("https://"+vcip+"/api/vcenter/vm/"+vm, headers={"vmware-api-session-id": auth}, verify=False)
except requests.exceptions.RequestException as Err:
raise SystemExit(Err)
if response.ok:
vmFQDN = ""
vmNet = ""
capB = 0
dict = response.json()['disks']
for keys,item in dict.items():
capB += dict[keys]['capacity']
Identity = response.json()['identity']['name']
cpuCount= response.json()['cpu']['count']
memGB = response.json()['memory']['size_MiB']/1024
capGB = capB / (1024 ** 3)
guestOS = response.json()['guest_OS']
if (response.json()['power_state'] == 'POWERED_ON'):
vmFQDN = get_vm_netinfo(auth,vcip,vm)
vmNet = get_vm_netInterface(auth,vcip,vm)
else:
raise Exception ("Unable to retrieve VM config.")
with open(outFile, 'a', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow([Identity,vcip,str(int(memGB))+" GB",cpuCount,str(int(capGB))+" GB",vmFQDN,vmNet,guestOS])
def list_vm_names(outFile,auth,vcip,jsonData):
x = 0;
while x < len(jsonData):
# print (jsonData[x])
get_vm_config(outFile,auth,vcip,jsonData[x]['vm'])
x += 1;
def get_vms(auth,vcip):
try:
response = requests.get("https://"+vcip+"/api/vcenter/vm", headers={"vmware-api-session-id": auth}, verify=False)
except requests.exceptions.RequestException as Err:
raise SystemExit(Err)
if response.ok:
return response.json()
# Get the vCenter server session
def get_vc_session(vcip,username,password):
try:
response = requests.post("https://"+vcip+"/api/session", auth=(username, password), verify=False)
except requests.exceptions.RequestException as Err:
raise SystemExit(Err)
if response.ok:
return response.json()
def main():
outFile = 'Inventory.csv'
f = open(outFile,"w")
f.close()
#Read Config parameters
config = configparser.ConfigParser()
config.read('config.ini')
usrName = config['vCenter']['usrName']
usrPass = config['vCenter']['usrPass']
srvName = config['vCenter']['srvName']
vcList = srvName.split(',')
for vcServ in vcList:
auth=get_vc_session(vcServ,usrName,usrPass)
vmList=get_vms(auth,vcServ)
list_vm_names(outFile,auth,vcServ,vmList)
# Script Starts Here
if __name__ == "__main__":
main()
I use configparser to store credentials and other variables. Here is an example of the config.ini file referenced in the script:
[vCenter]
srvName=VCserverName1,VCserverName2,VCserverName3
usrName=vcenter-user-name
usrPass=vcenter-user-password