Vijava 学习笔记之(HostSystem 关联VirtualMachine)

熊孩纸 阅读:684 2021-03-31 22:35:58 评论:0

源代码:

Server

package com.vmware.client; 
 
import com.vmware.vim25.mo.*; 
 
import java.util.ArrayList; 
import java.util.List; 
 
/** 
 * Created by vixuan-008 on 2015/5/21. 
 */ 
public class HostSystemVirtualMachine { 
    public List<String> getVirtualMachines( ServiceInstance serviceInstance,String hostName){ 
        List<String> list=new ArrayList<String>(); 
        try{ 
            Folder rootFolder = serviceInstance.getRootFolder(); 
            ManagedEntity mes =new InventoryNavigator(rootFolder).searchManagedEntity("HostSystem",hostName); 
            if(mes!=null){ 
                HostSystem systems=(HostSystem)mes; 
                VirtualMachine[] virtualMachines=systems.getVms(); 
                if(virtualMachines!=null &&virtualMachines.length>0){ 
                    for(VirtualMachine virtualMachine:virtualMachines){ 
                        String virtualMachineName=virtualMachine.getName(); 
                        list.add(virtualMachineName); 
                    } 
                } 
            } 
        }catch (Exception e) { 
            serviceInstance.getServerConnection().logout(); 
            return list; 
        }finally { 
            serviceInstance.getServerConnection().logout(); 
        } 
        return list; 
 
    } 
} 
测试代码:

package com.vmware.main; 
 
import com.vmware.client.HostSystemVirtualMachine; 
import com.vmware.util.Session; 
import com.vmware.vim25.mo.ServiceInstance; 
 
import java.util.List; 
 
/** 
 * Created by vixuan-008 on 2015/5/21. 
 */ 
public class HostSystemVirtualMachineTest { 
    public static void main(String[] args){ 
        try{ 
            ServiceInstance serviceInstance= Session.getInstance("****", "root", "vmware"); 
            String hostname="rack07.emcwh.local"; 
            HostSystemVirtualMachine hostSystemVirtualMachine=new HostSystemVirtualMachine(); 
            List<String> list=hostSystemVirtualMachine.getVirtualMachines(serviceInstance,hostname); 
            if(list !=null && list.size()>0){ 
                for(int i=0;i<list.size();i++){ 
                    String hostName=list.get(i); 
                    System.out.println("name is:"+hostName); 
                } 
            }else{ 
                System.out.println("list data is null or list.length is zero:"); 
            } 
 
        }catch (Exception e){ 
            e.printStackTrace(); 
        } 
    } 
} 




声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号