设为首页 收藏本站
查看: 2470|回复: 0

[经验分享] 用JAVA控制ESXi虚拟机

[复制链接]

尚未签到

发表于 2016-1-8 09:01:20 | 显示全部楼层 |阅读模式
  免费版的VMWare ESXi 从v3.5 u3开始,禁止了SDK和vCli的“写”调用。
也就是说,从ESXi 3.5u3开始,我们不能用SDK或者vCLI命令行,控制免费版ESXi上运行的虚拟机了,不能对其进行重起,关机等任何“写”操作。
后来无意中在网上发现了一个叫esxi-control.pl的脚本,可以用来控制免费版ESXi上的虚拟机,地址如下
http://blog.peacon.co.uk/esxi-control-pl-script-vm-actions-on-free-licensed-esxi/


脚本是用Perl写的,通过模拟vSphere Client发出的SOAP消息来控制ESXi.但是这个Perl脚本 仍然需要调用Perl-vCLI去获得虚拟机的id信息。我想既然能够模拟SOAP的控制消息,那也一定能模拟读取虚拟机信息的消息啊,但是平时用Perl很少,所以干脆就用JAVA写了一个实现。


先说说程序的原理,
程序调用Apache的httpclient来完成SOAP消息的发送与接受。


第一步,发送下列SOAP消息来建立连接与身份认证,$USERNAME$和$PASSWORD$为ESXi主机的登陆用户名和密码

  • <soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  • <soap:Body>
  • <Login xmlns="urn:internalvim25">
  • <_this xsi:type="SessionManager"type="SessionManager"serverGuid="">ha-sessionmgr</_this>
  • <userName>$USERNAME$</userName>
  • <password>$PASSWORD$</password>
  • <locale>en_US</locale>
  • </Login>
  • </soap:Body>
  • </soap:Envelope>


第二步,获取当前已连接主机上的虚拟机列表,SOAP消息如下

  • <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  • <soapenv:Body>
  • <RetrieveProperties xmlns="urn:vim25">
  • <_this type="PropertyCollector">ha-property-collector</_this>
  • <specSet>
  • <propSet>
  • <type>HostSystem</type>
  • <all>0</all>
  • <pathSet>vm</pathSet>
  • </propSet>
  • <objectSet>
  • <obj type="HostSystem">ha-host</obj>
  • </objectSet>
  • </specSet>
  • </RetrieveProperties>
  • </soapenv:Body>
  • </soapenv:Envelope>


第三步,第二步返回的消息里面只有虚拟机的ID,但是用户一般是不知道虚拟机的ID是干啥的,所以,我们需要虚拟机的名称等其它信息,所以发送下面的消息用来获取虚拟机其它的信息,包括虚拟机的名称,虚拟机的网络名称,IP地址,开关机状态以及VMWareTool的运行情况。
其中的$VMID$就是要获取具体信息的虚拟机ID
可以有多个<objectSet>,用来一次性获取多台虚拟机的信息

  • <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  • <soapenv:Body>
  • <RetrieveProperties xmlns="urn:vim25">
  • <_this type="PropertyCollector">ha-property-collector</_this>
  • <specSet>
  • <propSet>
  • <type>VirtualMachine</type>
  • <all>0</all>
  • <pathSet>name</pathSet>
  • <pathSet>guest.hostName</pathSet>
  • <pathSet>runtime.powerState</pathSet>
  • <pathSet>guest.ipAddress</pathSet>
  • <pathSet>guest.toolsRunningStatus</pathSet>
  • </propSet>
  • <objectSet>
  • <obj type="VirtualMachine">$VM1ID$</obj>
  • </objectSet>
  • <objectSet>
  • <obj type="VirtualMachine">$VM2ID$</obj>
  • </objectSet>
  • </specSet>
  • </RetrieveProperties>
  • </soapenv:Body>
  • </soapenv:Envelope>


第四步,到这里,我们的准备工作就结束了,可以发送SOAP的控制消息,控制虚拟机的开关机/重起等操作了,这部分SOAP消息esxi-control.pl做得比较深入,值得借鉴。
这里只举一个重起虚拟机的SOAP消息做例子, $VMID$就是要被重起的虚拟机的ID

  • <soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  • <soap:Body>
  • <ResetVM_Task xmlns="urn:internalvim25">
  • <_this xsi:type="VirtualMachine"type="VirtualMachine"serverGuid="">$VMID$</_this>
  • </ResetVM_Task>
  • </soap:Body>
  • </soap:Envelope>


第五步,断开连接

  • <soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  • <soap:Body>
  • <Logout xmlns="urn:internalvim25">
  • <_this xsi:type="ManagedObjectReference"type="SessionManager"serverGuid="">ha-sessionmgr</_this>
  • </Logout>
  • </soap:Body>
  • </soap:Envelope>




JAVA实现代码如下

  • packagejava_vc;


  • /**

  • *
  • * @author yyz_tj_cn@sina.com.cn
  • */

  • importorg.apache.http.Header;
  • importorg.apache.http.HttpEntity;
  • importorg.apache.http.HttpResponse;
  • importorg.apache.http.client.methods.HttpPost;
  • importorg.apache.http.impl.client.DefaultHttpClient;
  • importorg.apache.http.util.EntityUtils;
  • importjavax.net.ssl.SSLContext;
  • importorg.apache.http.conn.ssl.SSLSocketFactory;
  • importjavax.net.ssl.TrustManager;
  • importjavax.net.ssl.X509TrustManager;
  • importjava.security.cert.X509Certificate;
  • importjava.security.cert.CertificateException;
  • importorg.apache.http.conn.scheme.Scheme;
  • importorg.apache.http.entity.StringEntity;
  • importorg.apache.http.client.params.ClientPNames;
  • importorg.apache.http.client.params.CookiePolicy;
  • importorg.w3c.dom.Document;
  • importorg.w3c.dom.NodeList;
  • importjavax.xml.parsers.*;
  • importjava.util.*;


  • publicclassVmoperation {

  • //This Embeded Class is used to store Virtual Machine information
  • publicclassVminfo {
  • privateStringid=null;
  • privateStringname=null;
  • privateStringnetworkName =null;
  • privateStringipv4 =null;
  • privateStringpowerState =null;
  • privateStringvmToolRunningSattus =null;

  • publicVminfo(){

  • }
  • publicStringgetID(){
  • returnid;
  • }
  • publicvoidsetID(Stringval){
  • id=val.trim();
  • }

  • publicStringgetName(){
  • returnname;
  • }
  • publicvoidsetName(Stringval){
  • name=val.trim();
  • }

  • publicStringgetNetworkName(){
  • returnnetworkName;
  • }
  • publicvoidsetNetworkName(Stringval){
  • networkName=val.trim();
  • }

  • publicStringgetIpAddress(){
  • returnipv4;
  • }
  • publicvoidsetIpAddress(Stringval){
  • ipv4=val.trim();
  • }

  • publicStringgetPowerState(){
  • returnpowerState;
  • }
  • publicvoidsetPowerState(Stringval){
  • powerState=val.trim();
  • }

  • publicStringgetVMToolRunningSattus(){
  • returnvmToolRunningSattus;
  • }
  • publicvoidsetVMToolRunningSattus(Stringval){
  • vmToolRunningSattus=val.trim();
  • }
  • }

  • //Vmoperation Class start...
  • privatebooleandebug =true;
  • privatebooleanconnected =false;
  • privateDefaultHttpClient httpclient =null;
  • privateTrustManagereasyTrustManager =null;
  • privateArrayListvmList =null;
  • privateStringhostURL =null;
  • privateStringxml_login ="<soap:Envelopexmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//"> "+
  • "<soap:Body>"+
  • "<Login xmlns=/"urn:internalvim25/">"+
  • "<_this xsi:type=/"SessionManager/" type=/"SessionManager/" serverGuid=/"/">ha-sessionmgr</_this>"+
  • "<userName>$USERNAME$</userName>"+
  • "<password>$PASSWORD$</password>"+
  • "<locale>en_US</locale>"+
  • "</Login>"+
  • "</soap:Body>"+
  • "</soap:Envelope>";
  • privateStringxml_logout ="<soap:Envelopexmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">"+
  • "<soap:Body>"+
  • "<Logout xmlns=/"urn:internalvim25/">"+
  • "<_this xsi:type=/"ManagedObjectReference/" type=/"SessionManager/" serverGuid=/"/">ha-sessionmgr</_this>"+
  • "</Logout>"+
  • "</soap:Body>"+
  • "</soap:Envelope>";
  • privateStringxml_poweroff ="<soap:Envelopexmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">"+
  • "<soap:Body>"+
  • "<PowerOffVM_Task xmlns=/"urn:internalvim25/">"+
  • "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>"+
  • "</PowerOffVM_Task>"+
  • "</soap:Body>"+
  • "</soap:Envelope>";
  • privateStringxml_poweron ="<soap:Envelopexmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">"+
  • "<soap:Body>"+
  • "<PowerOnVM_Task xmlns=/"urn:internalvim25/">"+
  • "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>"+
  • "</PowerOnVM_Task>"+
  • "</soap:Body>"+
  • "</soap:Envelope>";
  • privateStringxml_reset ="<soap:Envelopexmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">"+
  • "<soap:Body>"+
  • "<ResetVM_Task xmlns=/"urn:internalvim25/">"+
  • "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>"+
  • "</ResetVM_Task>"+
  • "</soap:Body>"+
  • "</soap:Envelope>";

  • privateStringxml_getVMIDs ="<soapenv:Envelopexmlns:soapenv=/"http://schemas.xmlsoap.org/soap/envelope//" xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/">"+
  • "<soapenv:Body>"+
  • "<RetrieveProperties xmlns=/"urn:vim25/">"+
  • "<_this type=/"PropertyCollector/">ha-property-collector</_this>"+
  • "<specSet>"+
  • "<propSet>"+
  • "<type>HostSystem</type>"+
  • "<all>0</all>"+
  • "<pathSet>vm</pathSet>"+
  • "</propSet>"+
  • "<objectSet>"+
  • "<obj type=/"HostSystem/">ha-host</obj>"+
  • "</objectSet>"+
  • "</specSet>"+
  • "</RetrieveProperties>"+
  • "</soapenv:Body>"+
  • "</soapenv:Envelope>";

  • privateStringxml_getVMInfo ="<soapenv:Envelopexmlns:soapenv=/"http://schemas.xmlsoap.org/soap/envelope//" xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/">"+
  • "<soapenv:Body>"+
  • "<RetrieveProperties xmlns=/"urn:vim25/">"+
  • "<_this type=/"PropertyCollector/">ha-property-collector</_this>"+
  • "<specSet>"+
  • "<propSet>"+
  • "<type>VirtualMachine</type>"+
  • "<all>0</all>"+
  • "<pathSet>name</pathSet>"+
  • "<pathSet>guest.hostName</pathSet>"+
  • "<pathSet>runtime.powerState</pathSet>"+
  • "<pathSet>guest.ipAddress</pathSet>"+
  • "<pathSet>guest.toolsRunningStatus</pathSet>"+
  • "</propSet>"+
  • "$VMIDLISTOBJ$"+
  • "</specSet>"+
  • "</RetrieveProperties>"+
  • "</soapenv:Body>"+
  • "</soapenv:Envelope>";


  • //Connect to ESXi Host
  • publicStringConnect(StringIPAddress,StringUsername,StringPassword)throwsException{

  • //Clear previous connection, if any.
  • if(connected){
  • Disconnect();
  • finalCleanup();
  • }

  • debugOutput("Connecting to host "+ip2URL(IPAddress));
  • //Init new connection
  • hostURL =ip2URL(IPAddress);
  • httpclient =newDefaultHttpClient();
  • //Init a customer X509TrustManager to trust any certificates
  • easyTrustManager =newX509TrustManager(){
  • @Override
  • publicvoidcheckClientTrusted(
  • X509Certificate[]chain,
  • StringauthType)throwsCertificateException{
  • // Oh, I am easy!
  • }
  • @Override
  • publicvoidcheckServerTrusted(
  • X509Certificate[]chain,
  • StringauthType)throwsCertificateException{
  • // Oh, I am easy!
  • }
  • @Override
  • publicX509Certificate[]getAcceptedIssuers(){
  • returnnull;
  • }
  • };

  • SSLContextsslcontext=SSLContext.getInstance("TLS");
  • sslcontext.init(null,newTrustManager[]{easyTrustManager },null);
  • //Init SSLSocketFactory to accept any hostname and any certificates
  • SSLSocketFactorysf =newSSLSocketFactory(sslcontext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  • Scheme sch =newScheme("https",443,sf);
  • httpclient.getConnectionManager().getSchemeRegistry().register(sch);
  • httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);

  • //Send Hello Message
  • xml_login =xml_login.replace("$USERNAME$",Username);
  • xml_login =xml_login.replace("$PASSWORD$",Password);
  • HttpResponse result;
  • result=sendXML(hostURL,xml_login);
  • if(debug)dispalyHttpResponse(result);elseEntityUtils.consume(result.getEntity());

  • //If not HTTP 200 returned, error occured.
  • if(result.getStatusLine().toString().trim().equals("HTTP/1.1 200 OK"))connected=true;

  • //Get Virtual Machine List
  • if(connected)vmList=getVMList();

  • //Return connect result
  • returnresult.getStatusLine().toString();
  • }

  • //disconnect from ESXi Host
  • publicStringDisconnect()throwsException{
  • Stringret =null;
  • if(debug)System.out.println("Disconnecting from host "+hostURL);
  • if(connected){
  • HttpResponse result=null;
  • result=sendXML(hostURL,xml_logout);
  • if(debug)dispalyHttpResponse(result);elseEntityUtils.consume(result.getEntity());
  • //If not HTTP 200 returned, error occured.
  • if(result.getStatusLine().toString().trim().equals("HTTP/1.1 200 OK")){
  • finalCleanup();
  • }
  • ret =result.getStatusLine().toString();
  • }
  • //Return connect result
  • returnret;
  • }

  • //Display Virtual Machine List on connected ESXi Host
  • publicvoidDisplayVMList (){
  • debugOutput("Displaying Virtual Machine List...");
  • //init Column Width
  • intwidth1=3,width2=12,width3=12,width4=10,width5=12,width6=21;

  • if(vmList !=null){
  • //Get Col width
  • for(inti=0;i<vmList.size();i++){
  • Vminfo VMNode=null;
  • VMNode=(Vminfo)vmList.get(i);
  • if(VMNode.getID()!=null)width1 =Math.max(VMNode.getID().length(),width1);
  • if(VMNode.getName()!=null)width2 =Math.max(VMNode.getName().length(),width2);
  • if(VMNode.getNetworkName()!=null)width3 =Math.max(VMNode.getNetworkName().length(),width3);
  • if(VMNode.getIpAddress()!=null)width4 =Math.max(VMNode.getIpAddress().length(),width4);
  • if(VMNode.getPowerState()!=null)width5 =Math.max(VMNode.getPowerState().length(),width5);
  • if(VMNode.getVMToolRunningSattus()!=null)width6 =Math.max(VMNode.getVMToolRunningSattus().length(),width6);
  • }
  • //Output Result
  • //Title
  • Stringtitle ="";
  • title +=formatData("ID",width1);
  • title +=formatData("Machine Name",width2);
  • title +=formatData("Network Name",width3);
  • title +=formatData("IP Address",width4);
  • title +=formatData("Power Status",width5);
  • title +=formatData("VMTool running Status",width6);
  • title +="/n";
  • for(inti=0;i<=width1+width2+width3+width4+width5+width6+6;i++){
  • title +="-";
  • }
  • System.out.println(title);
  • //Data
  • for(inti=0;i<vmList.size();i++){
  • Vminfo VMNode=null;
  • Stringoutput="";
  • VMNode=(Vminfo)vmList.get(i);
  • output+=formatData(VMNode.getID(),width1);
  • output+=formatData(VMNode.getName(),width2);
  • output+=formatData(VMNode.getNetworkName(),width3);
  • output+=formatData(VMNode.getIpAddress(),width4);
  • output+=formatData(VMNode.getPowerState(),width5);
  • output+=formatData(VMNode.getVMToolRunningSattus(),width6);
  • System.out.println(output);
  • }
  • }
  • }

  • //Power-Off virtual machine on connected ESXi host
  • publicStringPowerOffVM (StringVMName)throwsException{
  • Stringret =null;
  • debugOutput("Powering Off "+VMName);
  • if(connected){
  • Stringxmldata =xml_poweroff.replace("$VMID$",getVMId(VMName));
  • HttpResponse result;
  • result=sendXML(hostURL,xmldata);
  • if(debug)dispalyHttpResponse(result);elseEntityUtils.consume(result.getEntity());
  • ret =result.getStatusLine().toString();
  • }
  • //Return result
  • returnret;
  • }

  • //Power-On virtual machine on connected ESXi host
  • publicStringPowerOnVM (StringVMName)throwsException{
  • Stringret =null;
  • debugOutput("Powering On "+VMName);
  • if(connected){
  • Stringxmldata =xml_poweron.replace("$VMID$",getVMId(VMName));
  • HttpResponse result;
  • result=sendXML(hostURL,xmldata);
  • if(debug)dispalyHttpResponse(result);elseEntityUtils.consume(result.getEntity());
  • ret =result.getStatusLine().toString();
  • }
  • //Return result
  • returnret;
  • }

  • //Reset virtual machine on connected ESXi host
  • publicStringResetVM (StringVMName)throwsException{
  • Stringret =null;
  • debugOutput("Reseting "+VMName);
  • if(connected){
  • Stringxmldata =xml_reset.replace("$VMID$",getVMId(VMName));
  • HttpResponse result;
  • result=sendXML(hostURL,xmldata);
  • if(debug)dispalyHttpResponse(result);elseEntityUtils.consume(result.getEntity());
  • ret =result.getStatusLine().toString();
  • }
  • //Return result
  • returnret;
  • }

  • publicbooleangetConnected(){
  • returnthis.connected;
  • }

  • privatevoidfinalCleanup(){
  • if(httpclient!=null)httpclient.getConnectionManager().shutdown();
  • connected=false;
  • vmList=null;
  • httpclient =null;
  • easyTrustManager =null;
  • hostURL =null;
  • }
  • //Get VMID from given virtual machine name
  • privateStringgetVMId(StringVMName){
  • Stringresult=null;
  • Iteratorit =vmList.iterator();
  • while(it.hasNext()){
  • Vminfo VMNode =null;
  • VMNode =(Vminfo)it.next();
  • if(VMName.toLowerCase().trim().equals(VMNode.getName().toLowerCase())){
  • result=VMNode.getID();
  • break;
  • }
  • }
  • returnresult;
  • }
  • //Get All Virtual Machine Information on connected ESXi host
  • privateArrayListgetVMList()throwsException{
  • ArrayListresult=newArrayList();
  • Vminfo VMNode =null;
  • HttpResponse rspVMList =sendXML(hostURL,genXML_getVMInfo(getVMIDs ()));
  • //Parse returned XML and store information in vmList
  • //NEED MORE SMART!!!

  • //Returned XML sample
  • /*

  • <returnval>
  • <obj type="VirtualMachine">128</obj>
  • <propSet><name>guest.hostName</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  • <propSet><name>guest.ipAddress</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  • <propSet><name>guest.toolsRunningStatus</name><valxsi:type="xsd:string">guestToolsRunning</val></propSet>
  • <propSet><name>name</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  • <propSet><name>runtime.powerState</name><valxsi:type="VirtualMachinePowerState">poweredOn</val></propSet>
  • </returnval>


  • <returnval>
  • <obj type="VirtualMachine">240</obj>
  • <propSet><name>guest.toolsRunningStatus</name><valxsi:type="xsd:string">guestToolsNotRunning</val></propSet>
  • <propSet><name>name</name><val xsi:type="xsd:string">vSphere Management Assistant (vMA)</val></propSet>
  • <propSet><name>runtime.powerState</name><valxsi:type="VirtualMachinePowerState">poweredOff</val></propSet>
  • </returnval>
  • *
  • *
  • */
  • DocumentBuilderFactorydbf =DocumentBuilderFactory.newInstance();
  • DocumentBuilderdb =dbf.newDocumentBuilder();
  • Documentdoc=db.parse(rspVMList.getEntity().getContent());
  • NodeListnl1 =doc.getElementsByTagName("returnval");
  • //<returnval>
  • for(inti=0;i<nl1.getLength();i++){
  • if(nl1.item(i).hasChildNodes()){
  • VMNode =newVminfo();
  • NodeListnl2 =nl1.item(i).getChildNodes();
  • //<obj>&<proSet>
  • for(intj=0;j<nl2.getLength();j++){
  • if(nl2.item(j).getNodeName().trim().equals("obj")){
  • VMNode.setID(nl2.item(j).getTextContent());
  • }
  • else{
  • if(nl2.item(j).hasChildNodes()){
  • NodeListnl3 =nl2.item(j).getChildNodes();
  • //<proset>
  • //There are 2 childnodes in <proset>, one is for value name, another is value, it's a pair. so k+=2
  • for(intk=0;k<nl3.getLength();k+=2){
  • if(nl3.item(k).getTextContent().trim().toLowerCase().equals("name")&&nl3.item(k+1).getNodeName().trim().toLowerCase().equals("val")){
  • VMNode.setName(nl3.item(k+1).getTextContent());
  • }elseif(nl3.item(k).getTextContent().trim().toLowerCase().equals("guest.hostname")&&nl3.item(k+1).getNodeName().trim().toLowerCase().equals("val")){
  • VMNode.setNetworkName(nl3.item(k+1).getTextContent());
  • }elseif(nl3.item(k).getTextContent().trim().toLowerCase().equals("runtime.powerstate")&&nl3.item(k+1).getNodeName().trim().toLowerCase().equals("val")){
  • VMNode.setPowerState(nl3.item(k+1).getTextContent());
  • }elseif(nl3.item(k).getTextContent().trim().toLowerCase().equals("guest.toolsrunningstatus")&&nl3.item(k+1).getNodeName().trim().toLowerCase().equals("val")){
  • VMNode.setVMToolRunningSattus(nl3.item(k+1).getTextContent());
  • }elseif(nl3.item(k).getTextContent().trim().toLowerCase().equals("guest.ipaddress")&&nl3.item(k+1).getNodeName().trim().toLowerCase().equals("val")){
  • VMNode.setIpAddress(nl3.item(k+1).getTextContent());
  • }
  • }
  • }
  • }
  • }
  • result.add(VMNode);
  • debugOutput ("1 VM Added. VMID="+VMNode.getID()+" VMName="+VMNode.getName()+" VMNetworkName="+VMNode.getNetworkName()+" VMIP="+VMNode.getIpAddress()+" VMPower="+VMNode.getPowerState()+" ToolStatus="+VMNode.getVMToolRunningSattus());
  • }
  • }
  • returnresult;
  • }

  • privatevoiddebugOutput (Stringmsg){
  • if(debug)System.out.println("/n<DEBUG TYPE=MSG>/n"+msg+"/n</DEBUG>");
  • }
  • //Get VMID list on a connected ESXi
  • privateString[]getVMIDs ()throwsException{
  • String[]result=null;
  • //Sent xml to host to get VM ID list
  • HttpResponse rspVMIDList =sendXML(hostURL,xml_getVMIDs);
  • //Parse returned XML
  • DocumentBuilderFactorydbf =DocumentBuilderFactory.newInstance();
  • DocumentBuilderdb =dbf.newDocumentBuilder();
  • Documentdoc=db.parse(rspVMIDList.getEntity().getContent());
  • NodeListnl1 =doc.getElementsByTagName("ManagedObjectReference");
  • //init the return value array
  • result=newString[nl1.getLength()];
  • //set return array
  • for(inti=0;i<nl1.getLength();i++){
  • //make sure the ID is for Virtual Machine
  • if(nl1.item(i).hasChildNodes()&&
  • nl1.item(i).getAttributes().getNamedItem("type").toString().trim().equals("type=/"VirtualMachine/"")){
  • result[i]=nl1.item(i).getFirstChild().getNodeValue().toString().trim();
  • debugOutput("VMID="+result[i]);
  • }
  • }
  • returnresult;
  • }
  • privateStringgenXML_getVMInfo(String[]vmIDList){
  • Stringresult;
  • Stringtmpxml="";
  • for(inti=0;i<vmIDList.length;i++){
  • tmpxml +="<objectSet><obj type=/"VirtualMachine/">"+vmIDList[i]+"</obj></objectSet>";
  • }
  • result=xml_getVMInfo.replace("$VMIDLISTOBJ$",tmpxml);
  • debugOutput(result);
  • returnresult;
  • }
  • privatevoiddispalyHttpResponse (HttpResponse rsp)throwsException{
  • HttpEntity entity=rsp.getEntity();
  • System.out.println("********************<HTTP Response>********************");
  • System.out.println("----------------------<HEADERS>------------------------");
  • System.out.println(rsp.getStatusLine());
  • Header[]headers =rsp.getAllHeaders();
  • for(inti =0;i <headers.length;i++){
  • System.out.println(headers[i]);
  • }
  • System.out.println("-----------------------<BODYS>-------------------------");
  • if(entity!=null){
  • System.out.println(EntityUtils.toString(entity));
  • }
  • System.out.println("************************<END>*************************");
  • System.out.println();
  • System.out.println();
  • }
  • privateHttpResponse sendXML(StringURL,Stringxml)throwsException{
  • HttpPost httppost =newHttpPost(URL);
  • StringEntity myEntity =newStringEntity(xml);
  • httppost.addHeader("Content-Type","text/xml; charset=/"utf-8/"");
  • httppost.addHeader("User-Agent","VMware VI Client/4.1.0");
  • httppost.addHeader("SOAPAction","/"urn:internalvim25/4.0/"");
  • httppost.setEntity(myEntity);
  • if(debug)System.out.println("executing request to "+httppost);
  • HttpResponse rsp =httpclient.execute(httppost);
  • returnrsp;
  • }
  • privateStringip2URL (StringIPAddress){
  • return"HTTPS://"+IPAddress+"/sdk/";
  • }
  • privateStringformatData (Stringdata,intwidth){
  • Stringresult;

  • if(data!=null){
  • result=data;
  • }else{
  • result="N/A";
  • }
  • //Append space
  • for(inti=result.length();i<=width;i++){
  • result+=" ";
  • }
  • returnresult;
  • }

  • publicstaticvoidmain(String[]args)throwsException{

  • Vmoperation temp =newVmoperation();


  • System.out.println(temp.Connect("<Your ESXi IP>","<Username>","<Password>"));
  • System.in.read();
  • System.out.println(temp.PowerOffVM("New Virtual Machine"));
  • System.in.read();
  • temp.DisplayVMList();
  • System.in.read();
  • System.out.println(temp.PowerOnVM("New Virtual Machine"));
  • System.in.read();
  • System.out.println(temp.ResetVM("New Virtual Machine"));
  • System.in.read();
  • System.out.println(temp.Disconnect());

  • }
  • }




注:以上仅用于学术研究,禁止用于实际生产环境。否则将导致违反VMWare License Agreement. VMWare可能随时改变XML的定义,导致程序不能正常工作。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-161682-1-1.html 上篇帖子: ESXi 和 ESX 许可证的区别 下篇帖子: How to Clone VMs in ESXi
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表