1.连接
pom使用yavijava,vsphere 7.0+之后vijava会报错,前言不允许有内容
<dependency>
<groupId>com.toastcoders</groupId>
<artifactId>yavijava</artifactId>
<version>6.0.05</version>
</dependency>
private static ServiceInstance getServiceInstanceConnection() {
// 连接逻辑
ServiceInstance si = null;
try {
si = new ServiceInstance(
new URL("https:/你的vsphere ip地址/sdk"),
"账户",
"密码.",
true);
;
} catch (Exception e) {
e.printStackTrace();
}
return si;
}
2.获取虚拟机列表
private static void getVMInfo() {
// 假设你已经有了连接到ESXi宿主机的ServiceInstance实例
try {
ServiceInstance si = getServiceInstanceConnection();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
System.out.println("VM Name: " + vm.getName());
}
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
3.获取虚拟机信息
private static void getVMInfo(String vmName) {
// 假设你已经有了连接到ESXi宿主机的ServiceInstance实例
try {
ServiceInstance si = getServiceInstanceConnection();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
if (vm.getName().equals(vmName)){
System.out.println("VM Name: " + vm.getName());
System.out.println("VM CPU Usage: " + vm.getSummary().getQuickStats().getOverallCpuUsage());
System.out.println("VM Memory Usage: " + vm.getSummary().getQuickStats().getGuestMemoryUsage());
System.out.println("VM Power State: " + vm.getRuntime().getPowerState());
}
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
4.重置虚拟机
vmName是你需要重装的虚拟机名字
private static void resetVM(String vmName) {
// 假设你已经有了连接到ESXi宿主机的ServiceInstance实例
try {
ServiceInstance si = getServiceInstanceConnection();
// 获取根文件夹
Folder rootFolder = si.getRootFolder();
// 通过文件夹的子集获取所有的虚拟机
VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmName);
if (vm != null) {
// 重置虚拟机资源
vm.resetVM_Task();
System.out.println("虚拟机资源已重置。");
} else {
System.out.println("未找到虚拟机。");
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
5.获取虚拟机快照名字
private static void getSnapshotName() {
try {
ServiceInstance si = getServiceInstanceConnection();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
if (vm.getSnapshot()!=null){
for (VirtualMachineSnapshotTree snapshotTree: vm.getSnapshot().rootSnapshotList ){
System.out.println("VM snapshot "+snapshotTree.getSnapshot());
}
}
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
6.恢复快照
private static void revertVM(String vmName) {
try {
// 连接到ESXi主机
ServiceInstance si = getServiceInstanceConnection();
// 指定需要恢复快照的虚拟机名称
// // 获取根Folder
Folder rootFolder = si.getRootFolder();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
if (vm.getSnapshot()!=null){
if (vm.getName().equals(vmName)){
System.out.println("VM Snapshot name: " + vm.getSnapshot().rootSnapshotList[0].getName());
HostSystem hostSystem=new HostSystem(si.getServerConnection(),vm.getRuntime().getHost());
vm.revertToCurrentSnapshot_Task(hostSystem,false);
System.out.println("虚拟机已恢复到当前快照。");
}
}
}
powerOnVM(vmName);
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
7.开机/关机
private static void powerOnVM(String vmName) {
try {
ServiceInstance si = getServiceInstanceConnection();
// 获取根文件夹
Folder rootFolder = si.getRootFolder();
// 通过文件夹的子集获取所有的虚拟机
VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmName);
if (vm != null) {
// 关闭虚拟机
vm.powerOffVM_Task();
// 打开虚拟机
vm.powerOnVM_Task(null);
System.out.println("虚拟机电源已打开。");
} else {
System.out.println("未找到虚拟机。");
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
8.创建快照
private static void createSnapshot(String vmName, String snapshotName,String description,Boolean memory,Boolean quiesce) {
try {
// 连接到ESXi主机
ServiceInstance si = getServiceInstanceConnection();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
if (vm.getName().equals(vmName)){
vm.createSnapshot_Task(snapshotName,description,memory,quiesce);
System.out.println("虚拟机创建快照成功。");
return;
}
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
9.删除快照
删除是删除指定虚拟机的所有快照
private static void deleteSnapshot(String vmName) {
try {
// 连接到ESXi主机
ServiceInstance si = getServiceInstanceConnection();
Object content[] = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("VirtualMachine");
for (Object obj : content) {
VirtualMachine vm = (VirtualMachine) obj;
if (vm.getSnapshot()!=null){
if (vm.getName().equals(vmName)){
vm.removeAllSnapshots_Task();
System.out.println("虚拟机删除快照成功。");
}
}
}
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
10.查询数据中心信息
查询有多少盘,已使用多少空间,空余多少空间。
private static void getDatacenterInfo() {
ServiceInstance si = getServiceInstanceConnection();
Datastore ds =null;
try {
ManagedEntity[] mes = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("Datastore");
for (ManagedEntity me : mes) {
ds = (Datastore) me;
System.out.println("Name: " + ds.getName());
System.out.println("Capacity: " + ds.getSummary().getCapacity()/ 1024 / 1024 / 1024 + " GB");
System.out.println("Free Space: " + ds.getSummary().getFreeSpace() / 1024 / 1024 / 1024 + " GB");
System.out.println("---------------------------");
}
// 关闭服务实例
si.getServerConnection().logout();
} catch (Exception e) {
e.printStackTrace();
}
}
11.查询模版信息
private List getTemplateInfo() {
ServiceInstance si=getServiceInstanceConnection();
VirtualMachine templateVM = null;
List list=new ArrayList();
InventoryNavigator inventoryNavigator = new InventoryNavigator(si.getRootFolder());
try {
si = getServiceInstanceConnection();
// 获取根Folder
Folder rootFolder = si.getRootFolder();
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");// ManagedObjectReference managedObjectReference=getDatacenterInfo(si);
for (ManagedEntity me : mes) {
templateVM= (VirtualMachine) me;
if (templateVM != null) {
list.add(templateVM.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
12.克隆虚拟机
public class StartCloudClone {
//模版机名字
private String templateName;
//新虚拟机名字
private String virtualMachineName;
//储存空间名字
private String dataStoreName;
// 虚拟机描述
private String VirtualMachineAnnotation;
//cpu核数
private int numCPUs;
//磁盘大小(kb)
private long diskSize;
// 设置内存大小
private Long memoryMB;
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getVirtualMachineName() {
return virtualMachineName;
}
public void setVirtualMachineName(String virtualMachineName) {
this.virtualMachineName = virtualMachineName;
}
public String getDataStoreName() {
return dataStoreName;
}
public void setDataStoreName(String dataStoreName) {
this.dataStoreName = dataStoreName;
}
public String getVirtualMachineAnnotation() {
return VirtualMachineAnnotation;
}
public void setVirtualMachineAnnotation(String virtualMachineAnnotation) {
VirtualMachineAnnotation = virtualMachineAnnotation;
}
public int getNumCPUs() {
return numCPUs;
}
public void setNumCPUs(int numCPUs) {
this.numCPUs = numCPUs;
}
public long getDiskSize() {
return diskSize;
}
public void setDiskSize(long diskSize) {
this.diskSize = diskSize;
}
public Long getMemoryMB() {
return memoryMB;
}
public void setMemoryMB(Long memoryMB) {
this.memoryMB = memoryMB;
}
public StartCloudClone(String templateName, String virtualMachineName, String dataStoreName, String virtualMachineAnnotation, int numCPUs, long diskSize, Long memoryMB) {
this.templateName = templateName;
this.virtualMachineName = virtualMachineName;
this.dataStoreName = dataStoreName;
VirtualMachineAnnotation = virtualMachineAnnotation;
this.numCPUs = numCPUs;
this.diskSize = diskSize;
this.memoryMB = memoryMB;
}
public StartCloudClone() {
}
}
public static String cloneVM(StartCloudClone startCloudClone) {
ServiceInstance si = getServiceInstanceConnection();
VirtualMachine templateVM = null;
ResourcePool pool = null;
HostSystem system=null;
Datastore datastore = null;
ComputeResource computerResource = null;
InventoryNavigator inventoryNavigator =new InventoryNavigator(si.getRootFolder());
Task task = null;
String poolname="Resources";
String hostname="";
long diskSize=startCloudClone.getDiskSize();
String diskmode="persistent";
// 逻辑处理
try {
si=getServiceInstanceConnection();
if(si!=null){
System.out.println("vmware 连接成功");
}else{
return ("vmware 连接失败,请检查vmware连接相关配置信息");
}
Folder rootFolder = si.getRootFolder();
inventoryNavigator = new InventoryNavigator(rootFolder);
try {
templateVM = (com.vmware.vim25.mo.VirtualMachine) inventoryNavigator
.searchManagedEntity("VirtualMachine", startCloudClone.getTemplateName());
if(templateVM!=null){
System.out.println("template 查询成功");
}else{
return ("template 查询失败,请仔细检查配置模板是否存在");
}
} catch (RemoteException e) {
e.printStackTrace();
return ("虚拟机模板文件存在问题:" + e.getMessage());
}
try{
datastore=(com.vmware.vim25.mo.Datastore) inventoryNavigator
.searchManagedEntity("Datastore", startCloudClone.getDataStoreName());
}catch (Exception e){
e.printStackTrace();
return ("指定Datastore存在问题:" + e.getMessage());
}
VirtualMachineRelocateSpec virtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
if (null != poolname && !"".equals(poolname)) {
try {
pool = (com.vmware.vim25.mo.ResourcePool) inventoryNavigator
.searchManagedEntity("ResourcePool", poolname);
virtualMachineRelocateSpec.setPool(pool.getMOR());
virtualMachineRelocateSpec.setPool(pool.getMOR());
virtualMachineRelocateSpec.setDatastore(datastore.getMOR());
if(pool!=null){
System.out.println("pool 查询成功");
}else{
return("pool 查询失败,请仔细检查配置资源池是否存在");
}
} catch (RemoteException e) {
return("Vcenter资源池存在问题:" + e.getMessage());
}
} else {
try {
computerResource = (ComputeResource) inventoryNavigator.searchManagedEntity("ComputeResource", hostname);
if(computerResource!=null){
if(computerResource.getResourcePool()!=null){
virtualMachineRelocateSpec.setPool(computerResource.getResourcePool().getMOR());
}
virtualMachineRelocateSpec.setDatastore(datastore.getMOR());
virtualMachineRelocateSpec.setHost(computerResource.getHosts()[0].getMOR());
}
} catch (RemoteException e) {
e.printStackTrace();
return("Vcenter下Esxi存在问题:" + e.getMessage());
}
}
//虚拟机CPU和内存配置信息
VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
// 设置CPU核数
configSpec.setNumCPUs(startCloudClone.getNumCPUs());
// 设置内存大小
configSpec.setMemoryMB(startCloudClone.getMemoryMB());
// 设置虚拟机名称
configSpec.setName(startCloudClone.getVirtualMachineName());
// 设置虚拟机描述
configSpec.setAnnotation(startCloudClone.getVirtualMachineAnnotation());
//更改磁盘大小
VirtualDeviceConfigSpec virtualDeviceConfigSpec = new VirtualDeviceConfigSpec();
VirtualDeviceConfigSpec diskSpec = createDiskSpec(
templateVM, "local02-2",
diskSize, diskmode);
if (diskSpec != null) {
System.out.println("创建disk不为空");
} else {
return("创建disk为空");
}
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
cloneSpec.setLocation(virtualMachineRelocateSpec);
cloneSpec.setPowerOn(true);
cloneSpec.setTemplate(false);
cloneSpec.setConfig(configSpec);
try {
task = templateVM.cloneVM_Task((Folder) templateVM.getParent(),
startCloudClone.getVirtualMachineName(), cloneSpec);
String result = task.waitForTask();
if (result.equals(Task.SUCCESS)) {
return ("模板生成虚拟机成功");
} else {
return ("模板生成虚拟机失败,请查询Vcenter 上相关日志信息");
}
} catch (RemoteException e) {
return ("创建任务失败:" + e.getMessage());
}
}catch(Exception e){
e.printStackTrace();
}
return ("模板生成虚拟机成功");
}
13.查询最近任务列表
查询指定虚拟机的近期任务列表
可以查看当前任务是否执行成功,进度等信息
"state": "success" or "running" or "err",
如果 state 值为 running json 将出现进度参数 "progress": 12,
public static JSONObject getTaskInfo(String vmName) {
Task [] task=null;
JSONObject jsonObject=new JSONObject();
try {
ServiceInstance si = getServiceInstanceConnection();
// 获取根Folder
Folder rootFolder = si.getRootFolder();
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
for (ManagedEntity me : mes) {
if (me.getName().equals(vmName)){
task= me.getRecentTasks();
if (task != null && task.length>0) {
System.out.println("task length:"+task.length);
jsonObject.put("taskInfo",task[0].getTaskInfo());
return jsonObject;
}else {
jsonObject.put("taskInfo","近期任务为空");
return jsonObject;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
jsonObject.put("taskInfo","查询任务失败");
return jsonObject;
}