vmware vcenter java操作实例demo
时间: 2023-07-13 09:33:06 浏览: 155
以下是一个简单的 Java 示例代码,用于连接到 vCenter 并获取虚拟机信息:
```java
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import com.vmware.vim25.Description;
import com.vmware.vim25.GuestInfo;
import com.vmware.vim25.HostSystemConnectionState;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.*;
import com.vmware.vim25.mo.util.*;
public class VmwareDemo {
private static final String VCENTER_URL = "https://<vCenter_Server>/sdk/vimService";
private static final String VCENTER_USERNAME = "<vCenter_Username>";
private static final String VCENTER_PASSWORD = "<vCenter_Password>";
public static void main(String[] args) throws Exception {
ServiceInstance si = new ServiceInstance(new URL(VCENTER_URL), VCENTER_USERNAME, VCENTER_PASSWORD, true);
Folder rootFolder = si.getRootFolder();
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
if(mes==null || mes.length ==0) {
System.out.println("No Virtual Machine Found!");
return;
}
List<String> vmList = new ArrayList<String>();
for(int i=0; i<mes.length; i++) {
VirtualMachine vm = (VirtualMachine) mes[i];
GuestInfo gi = vm.getGuest();
Description desc = vm.getConfig().getAnnotation();
if(gi!=null && gi.getIpAddress()!=null && !gi.getIpAddress().isEmpty()) {
vmList.add(vm.getName() + " - IP Address: " + gi.getIpAddress() + " - Description: " + desc.getSummary());
}
}
System.out.println("Virtual Machines:");
for(String vm : vmList) {
System.out.println(vm);
}
si.getServerConnection().logout();
}
}
```
该示例代码连接到 vCenter,获取虚拟机列表并输出虚拟机的名称、IP 地址和注释。您需要替换 `<vCenter_Server>`、`<vCenter_Username>` 和 `<vCenter_Password>` 为您的 vCenter 服务器地址、用户名和密码。同时,您需要将 `vim25.jar` 文件添加到您的项目类路径中才能编译和运行该示例代码。
阅读全文