VMware {code} Community
uminewbie
Contributor
Contributor

How to get a list of all VMs running in a host

Hi,

Using VI SDK, how to get a list of all VMs running in a given host using the host name alone? I'm using VC-2.0.2, ESX 3.0.2 and VI SDK 2.0.1.

Thanks in advance,

Umi

Reply
0 Kudos
3 Replies
StefanPahrmann

Should do the trick (remember to put some value into datacenter_view):

my $datacenter_view = "";
my $new_vms = Vim::find_entity_views(view_type => "VirtualMachine",
                                     begin_entity => $datacenter_view ,
                                     filter => { 'runtime.powerState' => 'poweredOn' });
foreach(@$new_vms){
    print $_->name."\n";
}

-Stefan

niteshl
Contributor
Contributor

Hi

First get the HostMOR giving the hostname

hostMOR = cb.getServiceUtil().getDecendentMoRef(null,"HostSystem",host);

if( hostMOR == null){

System.out.println("Host Not found");

return null;

}

Then browse the host mor taken out to retrieve the VMs in the host

vmList = cb.getServiceUtil().getDecendentMoRefs(hostMOR,"VirtualMachine",null);

if(( vmList == null)||(vmList.size() == 0)){

System.out.println("NO Virtual Machine found");

}

Niket
Enthusiast
Enthusiast

Hi,

Please refer the attached code. This code is working with C# what you need to do add the VimService references in your application.

Class CertPolicy is being used to resolve the certificate issue if any.

Class VMListing is the giving the listing of the VM's in a datacenter of VC.

// Example script to clone a Virtual Machine from Vm\template.

// Parameters:

// -- args[0] Url of VC

// -- args[1] Userid

// -- args[2] Password

// -- args[3] Name of the datacenter

using System;

using System.Collections.Generic;

using System.IO;

using System.Reflection;

using System.Net;

using System.Text;

using System.Web.Services;

using System.Net.Security;

using System.Security.Cryptography.X509Certificates;

using System.Collections;

using VimApi;

namespace VMListApplication

{

public class CertPolicy : ICertificatePolicy

{

private enum CertificateProblem : uint

{

CertEXPIRED = 0x800B0101,

CertVALIDITYPERIODNESTING = 0x800B0102,

CertROLE = 0x800B0103,

CertPATHLENCONST = 0x800B0104,

CertCRITICAL = 0x800B0105,

CertPURPOSE = 0x800B0106,

CertISSUERCHAINING = 0x800B0107,

CertMALFORMED = 0x800B0108,

CertUNTRUSTEDROOT = 0x800B0109,

CertCHAINING = 0x800B010A,

CertREVOKED = 0x800B010C,

CertUNTRUSTEDTESTROOT = 0x800B010D,

CertREVOCATION_FAILURE = 0x800B010E,

CertCN_NO_MATCH = 0x800B010F,

CertWRONG_USAGE = 0x800B0110,

CertUNTRUSTEDCA = 0x800B0112

}

private static Hashtable problem2text_;

private Hashtable request2problems_; // WebRequest -> ArrayList of error codes

public CertPolicy()

{

if (problem2text_ == null)

{

problem2text_ = new Hashtable();

problem2text_.Add((uint)CertificateProblem.CertEXPIRED,

"A required certificate is not within its validity period.");

problem2text_.Add((uint)CertificateProblem.CertVALIDITYPERIODNESTING,

"The validity periods of the certification chain do not nest correctly.");

problem2text_.Add((uint)CertificateProblem.CertROLE,

"A certificate that can only be used as an end-entity is being used as a CA or visa versa.");

problem2text_.Add((uint)CertificateProblem.CertPATHLENCONST,

"A path length constraint in the certification chain has been violated.");

problem2text_.Add((uint)CertificateProblem.CertCRITICAL,

"An extension of unknown type that is labeled 'critical' is present in a certificate.");

problem2text_.Add((uint)CertificateProblem.CertPURPOSE,

"A certificate is being used for a purpose other than that for which it is permitted.");

problem2text_.Add((uint)CertificateProblem.CertISSUERCHAINING,

"A parent of a given certificate in fact did not issue that child certificate.");

problem2text_.Add((uint)CertificateProblem.CertMALFORMED,

"A certificate is missing or has an empty value for an important field, such as a subject or issuer name.");

problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDROOT,

"A certification chain processed correctly, but terminated in a root certificate which isn't trusted by the trust provider.");

problem2text_.Add((uint)CertificateProblem.CertCHAINING,

"A chain of certs didn't chain as they should in a certain application of chaining.");

problem2text_.Add((uint)CertificateProblem.CertREVOKED,

"A certificate was explicitly revoked by its issuer.");

problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDTESTROOT,

"The root certificate is a testing certificate and the policy settings disallow test certificates.");

problem2text_.Add((uint)CertificateProblem.CertREVOCATION_FAILURE,

"The revocation process could not continue - the certificate(s) could not be checked.");

problem2text_.Add((uint)CertificateProblem.CertCN_NO_MATCH,

"The certificate's CN name does not match the passed value.");

problem2text_.Add((uint)CertificateProblem.CertWRONG_USAGE,

"The certificate is not valid for the requested usage.");

problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDCA,

"Untrusted CA");

}

request2problems_ = new Hashtable();

}

// ICertificatePolicy

public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest request, int problem)

{

if (problem == 0)

{

// Check whether we have accumulated any problems so far:

ArrayList problemArray = (ArrayList)request2problems_request;

if (problemArray == null)

{

// No problems so far

return true;

}

string problemList = "";

foreach (uint problemCode in problemArray)

{

string problemText = (string)problem2text_problemCode;

if (problemText == null)

{

problemText = "Unknown problem";

}

problemList += "* " + problemText + "\n\n";

}

request2problems_.Remove(request);

System.Console.WriteLine("There were one or more problems with the server certificate:\n\n" + problemList);

return true;

}

else

{

// Stash the problem in the problem array:

ArrayList problemArray = (ArrayList)request2problems_request;

if (problemArray == null)

{

problemArray = new ArrayList();

request2problems_request = problemArray;

}

problemArray.Add((uint)problem);

return true;

}

}

}

public class VMListing

{

static VimService _service;

protected ManagedObjectReference _svcRef;

private UserSession _session;

ServiceContent _sic;

private void VMList(string url, string usid, string pwd, string dcName)

{

String datacenterName = dcName; // name of DataCenter

System.Net.ServicePointManager.CertificatePolicy = new CertPolicy();

ManagedObjectReference _svcRef = new ManagedObjectReference();

//Gets service contents

_svcRef.type = "ServiceInstance";

_svcRef.Value = "ServiceInstance";

_service = new VimService();

_service.Url = url;

_service.CookieContainer = new CookieContainer();

_sic = service.RetrieveServiceContent(svcRef);

service.LoginCompleted += new LoginCompletedEventHandler(service_LoginCompleted);

_session = service.Login(sic.sessionManager, usid, pwd, null);

BuildVMLists();

}

private TraversalSpec buildTSpec()

{

TraversalSpec rpToRp = new TraversalSpec();

rpToRp.type = "ResourcePool";

rpToRp.path = "resourcePool";

rpToRp.skip = false;

rpToRp.name = "rpToRp";

rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() };

rpToRp.selectSet[0].name = "rpToRp";

rpToRp.selectSet[1].name = "rpToVm";

TraversalSpec rpToVm = new TraversalSpec();

rpToVm.type = "ResourcePool";

rpToVm.path = "vm";

rpToVm.skip = false;

rpToVm.name = "rpToVm";

rpToVm.selectSet = new SelectionSpec[] { };

TraversalSpec crToRp = new TraversalSpec();

crToRp.type = "ComputeResource";

crToRp.path = "resourcePool";

crToRp.skip = false;

crToRp.name = "crToRp";

crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() };

crToRp.selectSet[1].name = "rpToVm";

TraversalSpec crToH = new TraversalSpec();

crToH.type = "ComputeResource";

crToH.path = "host";

crToH.skip = false;

crToH.name = "crToH";

crToH.selectSet = new SelectionSpec[] { };

TraversalSpec dcToHf = new TraversalSpec();

dcToHf.type = "Datacenter";

dcToHf.path = "hostFolder";

dcToHf.skip = false;

dcToHf.name = "dcToHf";

dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() };

dcToHf.selectSet[0].name = "visitFolders";

TraversalSpec dcToVmf = new TraversalSpec();

dcToVmf.type = "Datacenter";

dcToVmf.path = "vmFolder";

dcToVmf.skip = false;

dcToVmf.name = "dcToVmf";

dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() };

dcToVmf.selectSet[0].name = "visitFolders";

TraversalSpec HToVm = new TraversalSpec();

HToVm.type = "HostSystem";

HToVm.path = "vm";

HToVm.skip = false;

HToVm.name = "HToVm";

HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() };

HToVm.selectSet[0].name = "visitFolders";

TraversalSpec visitFolders = new TraversalSpec();

visitFolders.type = "Folder";

visitFolders.path = "childEntity";

visitFolders.skip = false;

visitFolders.name = "visitFolders";

visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, dcToVmf, crToH, crToRp, HToVm, rpToVm };

visitFolders.selectSet[0].name = "visitFolders";

return visitFolders;

}

private void BuildVMLists()

{

TraversalSpec tSpec = buildTSpec();

PropertySpec] propSpecArray = new PropertySpec[ { new PropertySpec() };

propSpecArray[0].type = "VirtualMachine";

propSpecArray[0].all = true;

propSpecArray[0].allSpecified = true;

PropertyFilterSpec spec = new PropertyFilterSpec();

spec.propSet = propSpecArray;

spec.objectSet = new ObjectSpec[] { new ObjectSpec() };

spec.objectSet[0].obj = _sic.rootFolder;

spec.objectSet[0].skip = false;

spec.objectSethttp://0.selectSet = new SelectionSpechttp://0].selectSet = new SelectionSpec[ ;

ObjectContent[] ocArray =

service.RetrieveProperties(sic.propertyCollector, new PropertyFilterSpec[] );

foreach (ObjectContent oc in ocArray)

{

DynamicProperty[] pcArray = oc.propSet;

foreach (DynamicProperty d in pcArray)

{

if (d.name.Equals("name"))

{

String n = (String)d.val;

//lstVM.Items.Add(n);

System.Console.WriteLine("VM name:" + n);

}

}

}

}

public static Object getObjectProperty(ManagedObjectReference moRef, String propertyName)

{

return getProperties(moRef, new String[] { propertyName })[0];

}

/*

  • getProperties --

  • Retrieves the specified set of properties for the given managed object

  • reference into an array of result objects (returned in the same oder

  • as the property list).

*/

public static Object] getProperties(ManagedObjectReference moRef, String[ properties)

{

// PropertySpec specifies what properties to

// retrieve and from type of Managed Object

PropertySpec pSpec = new PropertySpec();

pSpec.type = moRef.type;

pSpec.pathSet = properties;

// ObjectSpec specifies the starting object and

// any TraversalSpecs used to specify other objects

// for consideration

ObjectSpec oSpec = new ObjectSpec();

oSpec.obj = moRef;

// PropertyFilterSpec is used to hold the ObjectSpec and

// PropertySpec for the call

PropertyFilterSpec pfSpec = new PropertyFilterSpec();

pfSpec.propSet = new PropertySpec[] { pSpec };

pfSpec.objectSet = new ObjectSpec[] ;

ManagedObjectReference _svcRef1 = new ManagedObjectReference();

_svcRef1.type = "ServiceInstance";

_svcRef1.Value = "ServiceInstance";

ServiceContent sic1 = service.RetrieveServiceContent(svcRef1);

ObjectContent[] ocs = new ObjectContent20;

ocs = _service.RetrieveProperties(sic1.propertyCollector, new PropertyFilterSpec[] );

// Return value, one object for each property specified

Object[] ret = new Objecthttp://properties.Length;

if (ocs != null)

{

for (int i = 0; i < ocs.Length; ++i)

{

ObjectContent oc = ocs;

DynamicProperty[] dps = oc.propSet;

if (dps != null)

{

for (int j = 0; j < dps.Length; ++j)

{

DynamicProperty dp = dps[j];

// find property path index

for (int p = 0; p < ret.Length; ++p)

{

if (properties[p].Equals(dp.name))

{

ret[p] = dp.val;

}

}

}

}

}

}

return ret;

}

public static void Main(String[] args)

{

VMListing Vmlst = new VMListing();

Vmlst.VMList(args[0], args[1], args[2], args[3]);

}

void serviceLoginCompleted(object sender, LoginCompletedEventArgs e)

{

}

}

}

I hope it works for you.

Thanks

Niket

Reply
0 Kudos