通过VM虚拟机查找ESXi主机名称和IP

查看了VC API、SDK,并没有找到用虚拟机来查询虚拟机所在ESXi的直接用法.

所以采用遍历查找的本办法:

//根据虚拟机名称获取EXSi名称
public String getExsiName(String vmName) {
    private static final String VC_IP = "127.0.0.1";
    private static final String VC_USERNAME = "username";
    private static final String VC_PASSWORD = "password";
    
    URL url = new URL("https", VC_IP, "/sdk");
    //连接VC
    ServiceInstance si = new ServiceInstance(url, VC_USERNAME, VC_PASSWORD, true);
    Folder rootFolder = si.getRootFolder();
    //查找所有EXSi
    ManagedEntity[] hostSystems = new InventoryNavigator(rootFolder)
                                        .searchManagedManagedEntities("HostSystem");
    for (ManagedEntity me : hostSystems) {
        HostSystem hs = (HostSystem) me;
        VirtualMachine[] vms = hs.getVms();
        for (VirtualMachine vMa : vms) {
            if (vMa.getName().equals(vmName)) {
                return hs.getName;
            }
        }
    }
    return null;
}

怎么获取EXSi的IP?可以根据EXSi网卡信息,按照自己的规范来查找,比如我们是把IP配在网卡vmk0

沿用上面的代码:

HostSystem hs = (HostSystem) me;
HostVirtualNic[] nics = hs.getConfig().getNetWork().getVnic();
//我们默认网卡vmk0的IP是exsi的IP
String exsiIp = nics[0].getSpec().getIp().getIpAddress();

 

你可能感兴趣的:(VIjava,VMware)