I had written a simple search script for an earlier post. When I was working on another script to install the vRealize Operations application monitoring agent, I thought it would be useful to search for virtual machines with varying methods. With the search script below, I wrote it to search for the virtual machine name, the vCenter managed object ID (MOID) or the vRealize Operations Instance ID. Thanks to John Dias for his search suggestions.
A sample of inputs:
jwhite@vm-linux:~/bin$ ./searchv2.py --name vm-win7
vm-win7: c836c3bd-a7b9-4b93-91a6-200a3f974e3a vm-352
jwhite@vm-linux:~/bin$ ./searchv2.py --moid vm-352
vm-win7: c836c3bd-a7b9-4b93-91a6-200a3f974e3a vm-352
jwhite@vm-linux:~/bin$ ./searchv2.py --opsid c836c3bd-a7b9-4b93-91a6-200a3f974e3a
vm-win7: c836c3bd-a7b9-4b93-91a6-200a3f974e3a vm-352
The search by name and the search by moid can be broad searches as well. For example, to search for any virtual machine where the MODI contains vm-3, you will see the following:
jwhite@vm-linux:~/bin$ ./searchv2.py --moid vm-3
vm-lcm: 1b5146d6-719f-4100-84f2-49b88c673d28 vm-351
vm-idm: 20ffd1d5-21a4-45fa-95ea-73e256470dbf vm-350
vm-linux: 32b35c09-8878-4a3a-947e-fcab2e3c4186 vm-354
or to broadly search for any virtual machine that contains 'win' in its name:
jwhite@vm-linux:~/bin$ ./searchv2.py --name win
VM-WIN10: 8d37e9eb-19fa-43c1-8e8a-902597322efb vm-324
Win2012: b9bc6577-d645-42b1-a32a-2640f2840cc9 vm-401
vm-win7: c836c3bd-a7b9-4b93-91a6-200a3f974e3a vm-352
The search for 'opsid' is an exact search. You will need the entire OPs ID to have a successful search.
jwhite@vm-linux:~/bin$ ./searchv2.py --opsid c836c3bd-a7b9-4b93-91a6-200a3f974e3a
vm-win7: c836c3bd-a7b9-4b93-91a6-200a3f974e3a vm-352
jwhite@vm-linux:~/bin$ ./searchv2.py --opsid c836c3bd
jwhite@vm-linux:~/bin$
FYI: The script below uses configparser which allows a developer to use an input file for parameters. You can replace the usrName, usrPass and srvName with you own values or configure your own configuration parameter file. The usrName references a vRealize Operations local account.
Here is a sample configuration file
jwhite@vm-linux:~/bin$ cat config.ini
[vrops user]
usrName=vrops-user
usrPass=P@ssw0rd
[vrops server]
srvName=vm-vrops.corp.local
#!/usr/bin/python3
#imports
import getopt, sys, json, requests, configparser
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Authenticate (vROps local user - consider updating script to allow for IDM)
def Authenticate():
#Read Config parameters
config = configparser.ConfigParser()
config.read('config.ini')
#Your vROps environment parameters
usrName = config['vrops user']['usrName']
usrPass = config['vrops user']['usrPass']
srvName = config['vrops server']['srvName']
global baseURL
baseURL = "https://" + srvName
tokenURL = baseURL + "/suite-api/api/auth/token/acquire"
authJSON = {"username": usrName,"authSource": "Local","password": usrPass,"others": [],"otherAttributes": {}}
authHeaders = {"Content-Type":"application/json","Accept":"application/json"}
authResponse = requests.post(tokenURL,data=json.dumps(authJSON),headers=authHeaders,verify=False)
if (authResponse.status_code != 200):
print('probably invalid credentials')
print('Returned Status Code: ' + authResponse.status_code)
sys.exit
else:
authToken = "vRealizeOpsToken " + authResponse.json()['token']
return authToken
# Search vROps database for the MOID
def SearchMOID(token, vm_name):
Headers = {"Content-Type":"application/json","Authorization":token,"Accept":"application/json"}
vropsURL = baseURL+"/suite-api/api/adapterkinds/VMWARE/resourcekinds/virtualmachine/resources?identifiers[VMEntityObjectID]="+vm_name
response = requests.get(vropsURL,headers=Headers,verify=False)
if response.json()['pageInfo']['totalCount'] == 0:
return ('Searched term not found')
else:
for x in range(int(response.json()['pageInfo']['totalCount'])):
msg = response.json()['resourceList'][x]['resourceKey']['name']+": "
msg += response.json()['resourceList'][x]['identifier']+" "
msg += response.json()['resourceList'][x]['resourceKey']['resourceIdentifiers'][2]['value']
print(msg)
return ('Searched term was successful')
# Search vROps database for the VM Name
def SearchName(token, vm_name):
Headers = {"Content-Type":"application/json","Authorization":token,"Accept":"application/json"}
vropsURL = baseURL+"/suite-api/api/adapterkinds/VMWARE/resourcekinds/virtualmachine/resources?name="+vm_name
response = requests.get(vropsURL,headers=Headers,verify=False)
if response.json()['pageInfo']['totalCount'] == 0:
return ('Searched term not found')
else:
for x in range(int(response.json()['pageInfo']['totalCount'])):
msg = response.json()['resourceList'][x]['resourceKey']['name']+": "
msg += response.json()['resourceList'][x]['identifier']+" "
msg += response.json()['resourceList'][x]['resourceKey']['resourceIdentifiers'][2]['value']
print(msg)
return ('Searched term was successful')
# Search vROps database for the vROPS ID
def SearchOPSID(token, vm_name):
Headers = {"Content-Type":"application/json","Authorization":token,"Accept":"application/json"}
vropsURL = baseURL+"/suite-api/api/resources/"+vm_name
response = requests.get(vropsURL,headers=Headers,verify=False)
if response.status_code != 200:
return ('Searched term not found')
else:
msg = response.json()['resourceKey']['name']+": "+response.json()['identifier']+" "
msg += response.json()['resourceKey']['resourceIdentifiers'][2]['value']
print(msg)
return ('Searched term was successful')
def Logout(token):
releaseURL = baseURL + "/suite-api/api/auth/token/release"
authHeaders = {"Content-Type":"application/json","Authorization":token,"Accept":"application/json"}
authResponse = requests.post(releaseURL,headers=authHeaders,verify=False)
def Usage():
print("We need either:")
print(" -M <vCenter MOID>")
print("or")
print(" -N <VM Name>")
print("for parameters")
def main():
# Check for passed arguments
if len(sys.argv)==1:
Usage()
sys.exit()
try:
opts, args = getopt.getopt(sys.argv[1:], "hM:N:I:",["help","moid=","name=","opsid="])
except getopt.GetoptError as err:
print(err)
Usage()
sys.exit(2)
authToken = Authenticate()
for key,value in opts:
if key == ("-h", "--help"):
Usage()
sys.exit()
elif key in ("-M", "--moid"):
SearchMOID(authToken, value)
elif key in ("-N", "--name"):
SearchName(authToken, value)
elif key in ("-I", "--opsid"):
SearchOPSID(authToken, value)
else:
Usage()
Logout(authToken)
# Script Starts Here
if __name__ == "__main__":
main()
No comments:
Post a Comment