您的位置:首页 > 编程语言 > Java开发

用JAVA控制ESXi虚拟机

2011-06-17 16:04 134 查看

免费版的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主机的登陆用户名和密码
  1. < 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/" >
  2. < soap:Body>
  3. < Login xmlns= "urn:internalvim25" >
  4. < _this xsi:type= "SessionManager" type= "SessionManager" serverGuid= "" > ha-sessionmgr< / _this>
  5. < userName> $ USERNAME$< / userName>
  6. < password> $ PASSWORD$< / password>
  7. < locale> en_US< / locale>
  8. < / Login>
  9. < / soap:Body>
  10. < / soap:Envelope>
第二步,获取当前已连接主机上的虚拟机列表,SOAP消息如下
  1. < 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" >
  2. < soapenv:Body>
  3. < RetrieveProperties xmlns= "urn:vim25" >
  4. < _this type= "PropertyCollector" > ha-property-collector< / _this>
  5. < specSet>
  6. < propSet>
  7. < type> HostSystem< / type>
  8. < all> 0< / all>
  9. < pathSet> vm< / pathSet>
  10. < / propSet>
  11. < objectSet>
  12. < obj type= "HostSystem" > ha-host< / obj>
  13. < / objectSet>
  14. < / specSet>
  15. < / RetrieveProperties>
  16. < / soapenv:Body>
  17. < / soapenv:Envelope>
第 三步,第二步返回的消息里面只有虚拟机的ID,但是用户一般是不知道虚拟机的ID是干啥的,所以,我们需要虚拟机的名称等其它信息,所以发送下面的消息用 来获取虚拟机其它的信息,包括虚拟机的名称,虚拟机的网络名称,IP地址,开关机状态以及VMWareTool的运行情况。 其中的$VMID$就是要获取具体信息的虚拟机ID 可以有多个 <objectSet>,用来一次性获取多台虚拟机的信息
  1. < 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" >
  2. < soapenv:Body>
  3. < RetrieveProperties xmlns= "urn:vim25" >
  4. < _this type= "PropertyCollector" > ha-property-collector< / _this>
  5. < specSet>
  6. < propSet>
  7. < type> VirtualMachine< / type>
  8. < all> 0< / all>
  9. < pathSet> name< / pathSet>
  10. < pathSet> guest. hostName< / pathSet>
  11. < pathSet> runtime. powerState< / pathSet>
  12. < pathSet> guest. ipAddress< / pathSet>
  13. < pathSet> guest. toolsRunningStatus< / pathSet>
  14. < / propSet>
  15. < objectSet>
  16. < obj type= "VirtualMachine" > $ VM1ID$< / obj>
  17. < / objectSet>
  18. < objectSet>
  19. < obj type= "VirtualMachine" > $ VM2ID$< / obj>
  20. < / objectSet>
  21. < / specSet>
  22. < / RetrieveProperties>
  23. < / soapenv:Body>
  24. < / soapenv:Envelope>
第四步,到这里,我们的准备工作就结束了,可以发送SOAP的控制消息,控制虚拟机的开关机/重起等操作了,这部分SOAP消息esxi-control.pl做得比较深入,值得借鉴。 这里只举一个重起虚拟机的SOAP消息做例子, $VMID$就是要被重起的虚拟机的ID
  1. < 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/" >
  2. < soap:Body>
  3. < ResetVM_Task xmlns= "urn:internalvim25" >
  4. < _this xsi:type= "VirtualMachine" type= "VirtualMachine" serverGuid= "" > $ VMID$< / _this>
  5. < / ResetVM_Task>
  6. < / soap:Body>
  7. < / soap:Envelope>
第五步,断开连接
  1. < 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/" >
  2. < soap:Body>
  3. < Logout xmlns= "urn:internalvim25" >
  4. < _this xsi:type= "ManagedObjectReference" type= "SessionManager" serverGuid= "" > ha-sessionmgr< / _this>
  5. < / Logout>
  6. < / soap:Body>
  7. < / soap:Envelope>

JAVA实现代码如下
  1. package java_vc;
  2. /**
  3. *
  4. * @author yyz_tj_cn@sina.com.cn
  5. */
  6. import org . apache. http. Header;
  7. import org . apache. http. HttpEntity;
  8. import org . apache. http. HttpResponse;
  9. import org . apache. http. client. methods. HttpPost;
  10. import org . apache. http. impl. client. DefaultHttpClient;
  11. import org . apache. http. util . EntityUtils;
  12. import javax . net . ssl . SSLContext ;
  13. import org . apache. http. conn. ssl . SSLSocketFactory ;
  14. import javax . net . ssl . TrustManager ;
  15. import javax . net . ssl . X509TrustManager ;
  16. import java . security . cert . X509Certificate ;
  17. import java . security . cert . CertificateException ;
  18. import org . apache. http. conn. scheme. Scheme;
  19. import org . apache. http. entity . StringEntity;
  20. import org . apache. http. client. params . ClientPNames;
  21. import org . apache. http. client. params . CookiePolicy;
  22. import org . w3c . dom . Document ;
  23. import org . w3c . dom . NodeList ;
  24. import javax . xml . parsers . * ;
  25. import java . util . * ;
  26. public class Vmoperation {
  27. //This Embeded Class is used to store Virtual Machine information
  28. public class Vminfo {
  29. private String id = null ;
  30. private String name = null ;
  31. private String networkName = null ;
  32. private String ipv4 = null ;
  33. private String powerState = null ;
  34. private String vmToolRunningSattus = null ;
  35. public Vminfo( ) {
  36. }
  37. public String getID ( ) {
  38. return id ;
  39. }
  40. public void setID ( String val) {
  41. id = val. trim ( ) ;
  42. }
  43. public String getName ( ) {
  44. return name ;
  45. }
  46. public void setName ( String val) {
  47. name = val. trim ( ) ;
  48. }
  49. public String getNetworkName( ) {
  50. return networkName;
  51. }
  52. public void setNetworkName( String val) {
  53. networkName= val. trim ( ) ;
  54. }
  55. public String getIpAddress( ) {
  56. return ipv4;
  57. }
  58. public void setIpAddress( String val) {
  59. ipv4= val. trim ( ) ;
  60. }
  61. public String getPowerState( ) {
  62. return powerState;
  63. }
  64. public void setPowerState( String val) {
  65. powerState= val. trim ( ) ;
  66. }
  67. public String getVMToolRunningSattus( ) {
  68. return vmToolRunningSattus;
  69. }
  70. public void setVMToolRunningSattus( String val) {
  71. vmToolRunningSattus= val. trim ( ) ;
  72. }
  73. }
  74. //Vmoperation Class start...
  75. private boolean debug = true;
  76. private boolean connected = false;
  77. private DefaultHttpClient httpclient = null ;
  78. private TrustManager easyTrustManager = null ;
  79. private ArrayList vmList = null ;
  80. private String hostURL = null ;
  81. private String xml_login = "<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//"> " +
  82. "<soap:Body>" +
  83. "<Login xmlns=/"urn:internalvim25/">" +
  84. "<_this xsi:type=/"SessionManager/" type=/"SessionManager/" serverGuid=/"/">ha-sessionmgr</_this>" +
  85. "<userName>$USERNAME$</userName>" +
  86. "<password>$PASSWORD$</password>" +
  87. "<locale>en_US</locale>" +
  88. "</Login>" +
  89. "</soap:Body>" +
  90. "</soap:Envelope>" ;
  91. private String xml_logout = "<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//">" +
  92. "<soap:Body>" +
  93. "<Logout xmlns=/"urn:internalvim25/">" +
  94. "<_this xsi:type=/"ManagedObjectReference/" type=/"SessionManager/" serverGuid=/"/">ha-sessionmgr</_this>" +
  95. "</Logout>" +
  96. "</soap:Body>" +
  97. "</soap:Envelope>" ;
  98. private String xml_poweroff = "<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//">" +
  99. "<soap:Body>" +
  100. "<PowerOffVM_Task xmlns=/"urn:internalvim25/">" +
  101. "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>" +
  102. "</PowerOffVM_Task>" +
  103. "</soap:Body>" +
  104. "</soap:Envelope>" ;
  105. private String xml_poweron = "<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//">" +
  106. "<soap:Body>" +
  107. "<PowerOnVM_Task xmlns=/"urn:internalvim25/">" +
  108. "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>" +
  109. "</PowerOnVM_Task>" +
  110. "</soap:Body>" +
  111. "</soap:Envelope>" ;
  112. private String xml_reset = "<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//">" +
  113. "<soap:Body>" +
  114. "<ResetVM_Task xmlns=/"urn:internalvim25/">" +
  115. "<_this xsi:type=/"VirtualMachine/" type=/"VirtualMachine/" serverGuid=/"/">$VMID$</_this>" +
  116. "</ResetVM_Task>" +
  117. "</soap:Body>" +
  118. "</soap:Envelope>" ;
  119. private String xml_getVMIDs = "<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/">" +
  120. "<soapenv:Body>" +
  121. "<RetrieveProperties xmlns=/"urn:vim25/">" +
  122. "<_this type=/"PropertyCollector/">ha-property-collector</_this>" +
  123. "<specSet>" +
  124. "<propSet>" +
  125. "<type>HostSystem</type>" +
  126. "<all>0</all>" +
  127. "<pathSet>vm</pathSet>" +
  128. "</propSet>" +
  129. "<objectSet>" +
  130. "<obj type=/"HostSystem/">ha-host</obj>" +
  131. "</objectSet>" +
  132. "</specSet>" +
  133. "</RetrieveProperties>" +
  134. "</soapenv:Body>" +
  135. "</soapenv:Envelope>" ;
  136. private String xml_getVMInfo = "<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/">" +
  137. "<soapenv:Body>" +
  138. "<RetrieveProperties xmlns=/"urn:vim25/">" +
  139. "<_this type=/"PropertyCollector/">ha-property-collector</_this>" +
  140. "<specSet>" +
  141. "<propSet>" +
  142. "<type>VirtualMachine</type>" +
  143. "<all>0</all>" +
  144. "<pathSet>name</pathSet>" +
  145. "<pathSet>guest.hostName</pathSet>" +
  146. "<pathSet>runtime.powerState</pathSet>" +
  147. "<pathSet>guest.ipAddress</pathSet>" +
  148. "<pathSet>guest.toolsRunningStatus</pathSet>" +
  149. "</propSet>" +
  150. "$VMIDLISTOBJ$" +
  151. "</specSet>" +
  152. "</RetrieveProperties>" +
  153. "</soapenv:Body>" +
  154. "</soapenv:Envelope>" ;
  155. //Connect to ESXi Host
  156. public String Connect ( String IPAddress, String Username, String Password) throws Exception {
  157. //Clear previous connection, if any.
  158. if ( connected) {
  159. Disconnect ( ) ;
  160. finalCleanup( ) ;
  161. }
  162. debugOutput( "Connecting to host " + ip2URL( IPAddress) ) ;
  163. //Init new connection
  164. hostURL = ip2URL( IPAddress) ;
  165. httpclient = new DefaultHttpClient( ) ;
  166. //Init a customer X509TrustManager to trust any certificates
  167. easyTrustManager = new X509TrustManager ( ) {
  168. @Override
  169. public void checkClientTrusted (
  170. X509Certificate [ ] chain,
  171. String authType) throws CertificateException {
  172. // Oh, I am easy!
  173. }
  174. @Override
  175. public void checkServerTrusted (
  176. X509Certificate [ ] chain,
  177. String authType) throws CertificateException {
  178. // Oh, I am easy!
  179. }
  180. @Override
  181. public X509Certificate [ ] getAcceptedIssuers ( ) {
  182. return null ;
  183. }
  184. } ;
  185. SSLContext sslcontext = SSLContext . getInstance ( "TLS" ) ;
  186. sslcontext . init ( null , new TrustManager [ ] { easyTrustManager } , null ) ;
  187. //Init SSLSocketFactory to accept any hostname and any certificates
  188. SSLSocketFactory sf = new SSLSocketFactory ( sslcontext , SSLSocketFactory . ALLOW_ALL_HOSTNAME_VERIFIER) ;
  189. Scheme sch = new Scheme( "https" , 443, sf) ;
  190. httpclient. getConnectionManager( ) . getSchemeRegistry( ) . register ( sch) ;
  191. httpclient. getParams ( ) . setParameter ( ClientPNames. COOKIE_POLICY, CookiePolicy. BROWSER_COMPATIBILITY) ;
  192. //Send Hello Message
  193. xml_login = xml_login. replace ( "$USERNAME$" , Username) ;
  194. xml_login = xml_login. replace ( "$PASSWORD$" , Password) ;
  195. HttpResponse result ;
  196. result = sendXML( hostURL, xml_login) ;
  197. if ( debug) dispalyHttpResponse( result ) ; else EntityUtils. consume ( result . getEntity ( ) ) ;
  198. //If not HTTP 200 returned, error occured.
  199. if ( result . getStatusLine( ) . toString ( ) . trim ( ) . equals ( "HTTP/1.1 200 OK" ) ) connected= true;
  200. //Get Virtual Machine List
  201. if ( connected) vmList= getVMList( ) ;
  202. //Return connect result
  203. return result . getStatusLine( ) . toString ( ) ;
  204. }
  205. //disconnect from ESXi Host
  206. public String Disconnect ( ) throws Exception {
  207. String ret = null ;
  208. if ( debug) System . out. println ( "Disconnecting from host " + hostURL) ;
  209. if ( connected) {
  210. HttpResponse result = null ;
  211. result = sendXML( hostURL, xml_logout) ;
  212. if ( debug) dispalyHttpResponse( result ) ; else EntityUtils. consume ( result . getEntity ( ) ) ;
  213. //If not HTTP 200 returned, error occured.
  214. if ( result . getStatusLine( ) . toString ( ) . trim ( ) . equals ( "HTTP/1.1 200 OK" ) ) {
  215. finalCleanup( ) ;
  216. }
  217. ret = result . getStatusLine( ) . toString ( ) ;
  218. }
  219. //Return connect result
  220. return ret;
  221. }
  222. //Display Virtual Machine List on connected ESXi Host
  223. public void DisplayVMList ( ) {
  224. debugOutput( "Displaying Virtual Machine List..." ) ;
  225. //init Column Width
  226. int width1= 3, width2= 12, width3= 12, width4= 10, width5= 12, width6= 21;
  227. if ( vmList ! = null ) {
  228. //Get Col width
  229. for ( int i= 0; i< vmList. size ( ) ; i+ + ) {
  230. Vminfo VMNode= null ;
  231. VMNode= ( Vminfo) vmList. get ( i) ;
  232. if ( VMNode. getID ( ) ! = null ) width1 = Math . max ( VMNode. getID ( ) . length ( ) , width1) ;
  233. if ( VMNode. getName ( ) ! = null ) width2 = Math . max ( VMNode. getName ( ) . length ( ) , width2) ;
  234. if ( VMNode. getNetworkName( ) ! = null ) width3 = Math . max ( VMNode. getNetworkName( ) . length ( ) , width3) ;
  235. if ( VMNode. getIpAddress( ) ! = null ) width4 = Math . max ( VMNode. getIpAddress( ) . length ( ) , width4) ;
  236. if ( VMNode. getPowerState( ) ! = null ) width5 = Math . max ( VMNode. getPowerState( ) . length ( ) , width5) ;
  237. if ( VMNode. getVMToolRunningSattus( ) ! = null ) width6 = Math . max ( VMNode. getVMToolRunningSattus( ) . length ( ) , width6) ;
  238. }
  239. //Output Result
  240. //Title
  241. String title = "" ;
  242. title + = formatData( "ID" , width1) ;
  243. title + = formatData( "Machine Name" , width2) ;
  244. title + = formatData( "Network Name" , width3) ;
  245. title + = formatData( "IP Address" , width4) ;
  246. title + = formatData( "Power Status" , width5) ;
  247. title + = formatData( "VMTool running Status" , width6) ;
  248. title + = "/n" ;
  249. for ( int i= 0; i< = width1+ width2+ width3+ width4+ width5+ width6+ 6; i+ + ) {
  250. title + = "-" ;
  251. }
  252. System . out. println ( title) ;
  253. //Data
  254. for ( int i= 0; i< vmList. size ( ) ; i+ + ) {
  255. Vminfo VMNode= null ;
  256. String output = "" ;
  257. VMNode= ( Vminfo) vmList. get ( i) ;
  258. output + = formatData( VMNode. getID ( ) , width1) ;
  259. output + = formatData( VMNode. getName ( ) , width2) ;
  260. output + = formatData( VMNode. getNetworkName( ) , width3) ;
  261. output + = formatData( VMNode. getIpAddress( ) , width4) ;
  262. output + = formatData( VMNode. getPowerState( ) , width5) ;
  263. output + = formatData( VMNode. getVMToolRunningSattus( ) , width6) ;
  264. System . out. println ( output ) ;
  265. }
  266. }
  267. }
  268. //Power-Off virtual machine on connected ESXi host
  269. public String PowerOffVM ( String VMName) throws Exception {
  270. String ret = null ;
  271. debugOutput( "Powering Off " + VMName) ;
  272. if ( connected) {
  273. String xmldata = xml_poweroff. replace ( "$VMID$" , getVMId ( VMName) ) ;
  274. HttpResponse result ;
  275. result = sendXML( hostURL, xmldata) ;
  276. if ( debug) dispalyHttpResponse( result ) ; else EntityUtils. consume ( result . getEntity ( ) ) ;
  277. ret = result . getStatusLine( ) . toString ( ) ;
  278. }
  279. //Return result
  280. return ret;
  281. }
  282. //Power-On virtual machine on connected ESXi host
  283. public String PowerOnVM ( String VMName) throws Exception {
  284. String ret = null ;
  285. debugOutput( "Powering On " + VMName) ;
  286. if ( connected) {
  287. String xmldata = xml_poweron. replace ( "$VMID$" , getVMId ( VMName) ) ;
  288. HttpResponse result ;
  289. result = sendXML( hostURL, xmldata) ;
  290. if ( debug) dispalyHttpResponse( result ) ; else EntityUtils. consume ( result . getEntity ( ) ) ;
  291. ret = result . getStatusLine( ) . toString ( ) ;
  292. }
  293. //Return result
  294. return ret;
  295. }
  296. //Reset virtual machine on connected ESXi host
  297. public String ResetVM ( String VMName) throws Exception {
  298. String ret = null ;
  299. debugOutput( "Reseting " + VMName) ;
  300. if ( connected) {
  301. String xmldata = xml_reset. replace ( "$VMID$" , getVMId ( VMName) ) ;
  302. HttpResponse result ;
  303. result = sendXML( hostURL, xmldata) ;
  304. if ( debug) dispalyHttpResponse( result ) ; else EntityUtils. consume ( result . getEntity ( ) ) ;
  305. ret = result . getStatusLine( ) . toString ( ) ;
  306. }
  307. //Return result
  308. return ret;
  309. }
  310. public boolean getConnected( ) {
  311. return this . connected;
  312. }
  313. private void finalCleanup( ) {
  314. if ( httpclient!=null) httpclient. getConnectionManager( ) . shutdown ( ) ;
  315. connected= false;
  316. vmList= null ;
  317. httpclient = null ;
  318. easyTrustManager = null ;
  319. hostURL = null ;
  320. }
  321. //Get VMID from given virtual machine name
  322. private String getVMId ( String VMName) {
  323. String result = null ;
  324. Iterator it = vmList. iterator ( ) ;
  325. while ( it. hasNext ( ) ) {
  326. Vminfo VMNode = null ;
  327. VMNode = ( Vminfo) it. next ( ) ;
  328. if ( VMName. toLowerCase ( ) . trim ( ) . equals ( VMNode. getName ( ) . toLowerCase ( ) ) ) {
  329. result = VMNode. getID ( ) ;
  330. break ;
  331. }
  332. }
  333. return result ;
  334. }
  335. //Get All Virtual Machine Information on connected ESXi host
  336. private ArrayList getVMList( ) throws Exception {
  337. ArrayList result = new ArrayList ( ) ;
  338. Vminfo VMNode = null ;
  339. HttpResponse rspVMList = sendXML( hostURL, genXML_getVMInfo( getVMIDs ( ) ) ) ;
  340. //Parse returned XML and store information in vmList
  341. //NEED MORE SMART!!!
  342. //Returned XML sample
  343. /*
  344. <returnval>
  345. <obj type="VirtualMachine">128</obj>
  346. <propSet><name>guest.hostName</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  347. <propSet><name>guest.ipAddress</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  348. <propSet><name>guest.toolsRunningStatus</name><val xsi:type="xsd:string">guestToolsRunning</val></propSet>
  349. <propSet><name>name</name><val xsi:type="xsd:string">aaa.ccc.bbb</val></propSet>
  350. <propSet><name>runtime.powerState</name><val xsi:type="VirtualMachinePowerState">poweredOn</val></propSet>
  351. </returnval>
  352. <returnval>
  353. <obj type="VirtualMachine">240</obj>
  354. <propSet><name>guest.toolsRunningStatus</name><val xsi:type="xsd:string">guestToolsNotRunning</val></propSet>
  355. <propSet><name>name</name><val xsi:type="xsd:string">vSphere Management Assistant (vMA)</val></propSet>
  356. <propSet><name>runtime.powerState</name><val xsi:type="VirtualMachinePowerState">poweredOff</val></propSet>
  357. </returnval>
  358. *
  359. *
  360. */
  361. DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ;
  362. DocumentBuilder db = dbf. newDocumentBuilder ( ) ;
  363. Document doc = db. parse ( rspVMList. getEntity ( ) . getContent ( ) ) ;
  364. NodeList nl1 = doc . getElementsByTagName ( "returnval" ) ;
  365. //<returnval>
  366. for ( int i= 0; i< nl1. getLength ( ) ; i+ + ) {
  367. if ( nl1. item ( i) . hasChildNodes ( ) ) {
  368. VMNode = new Vminfo( ) ;
  369. NodeList nl2 = nl1. item ( i) . getChildNodes ( ) ;
  370. //<obj>&<proSet>
  371. for ( int j= 0; j< nl2. getLength ( ) ; j+ + ) {
  372. if ( nl2. item ( j) . getNodeName ( ) . trim ( ) . equals ( "obj" ) ) {
  373. VMNode. setID ( nl2. item ( j) . getTextContent ( ) ) ;
  374. }
  375. else {
  376. if ( nl2. item ( j) . hasChildNodes ( ) ) {
  377. NodeList nl3 = nl2. item ( j) . getChildNodes ( ) ;
  378. //<proset>
  379. //There are 2 childnodes in <proset>, one is for value name, another is value, it's a pair. so k+=2
  380. for ( int k= 0; k< nl3. getLength ( ) ; k+ = 2) {
  381. if ( nl3. item ( k) . getTextContent ( ) . trim ( ) . toLowerCase ( ) . equals ( "name" ) & & nl3. item ( k+ 1) . getNodeName ( ) . trim ( ) . toLowerCase ( ) . equals ( "val" ) ) {
  382. VMNode. setName ( nl3. item ( k+ 1) . getTextContent ( ) ) ;
  383. } else if ( nl3. item ( k) . getTextContent ( ) . trim ( ) . toLowerCase ( ) . equals ( "guest.hostname" ) & & nl3. item ( k+ 1) . getNodeName ( ) . trim ( ) . toLowerCase ( ) . equals ( "val" ) ) {
  384. VMNode. setNetworkName( nl3. item ( k+ 1) . getTextContent ( ) ) ;
  385. } else if ( nl3. item ( k) . getTextContent ( ) . trim ( ) . toLowerCase ( ) . equals ( "runtime.powerstate" ) & & nl3. item ( k+ 1) . getNodeName ( ) . trim ( ) . toLowerCase ( ) . equals ( "val" ) ) {
  386. VMNode. setPowerState( nl3. item ( k+ 1) . getTextContent ( ) ) ;
  387. } else if ( nl3. item ( k) . getTextContent ( ) . trim ( ) . toLowerCase ( ) . equals ( "guest.toolsrunningstatus" ) & & nl3. item ( k+ 1) . getNodeName ( ) . trim ( ) . toLowerCase ( ) . equals ( "val" ) ) {
  388. VMNode. setVMToolRunningSattus( nl3. item ( k+ 1) . getTextContent ( ) ) ;
  389. } else if ( nl3. item ( k) . getTextContent ( ) . trim ( ) . toLowerCase ( ) . equals ( "guest.ipaddress" ) & & nl3. item ( k+ 1) . getNodeName ( ) . trim ( ) . toLowerCase ( ) . equals ( "val" ) ) {
  390. VMNode. setIpAddress( nl3. item ( k+ 1) . getTextContent ( ) ) ;
  391. }
  392. }
  393. }
  394. }
  395. }
  396. result . add ( VMNode) ;
  397. debugOutput ( "1 VM Added. VMID=" + VMNode. getID ( ) + " VMName=" + VMNode. getName ( ) + " VMNetworkName=" + VMNode. getNetworkName( ) + " VMIP=" + VMNode. getIpAddress( ) + " VMPower=" + VMNode. getPowerState( ) + " ToolStatus=" + VMNode. getVMToolRunningSattus( ) ) ;
  398. }
  399. }
  400. return result ;
  401. }
  402. private void debugOutput ( String msg) {
  403. if ( debug) System . out. println ( "/n<DEBUG TYPE=MSG>/n" + msg+ "/n</DEBUG>" ) ;
  404. }
  405. //Get VMID list on a connected ESXi
  406. private String [ ] getVMIDs ( ) throws Exception {
  407. String [ ] result = null ;
  408. //Sent xml to host to get VM ID list
  409. HttpResponse rspVMIDList = sendXML( hostURL, xml_getVMIDs) ;
  410. //Parse returned XML
  411. DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ;
  412. DocumentBuilder db = dbf. newDocumentBuilder ( ) ;
  413. Document doc = db. parse ( rspVMIDList. getEntity ( ) . getContent ( ) ) ;
  414. NodeList nl1 = doc . getElementsByTagName ( "ManagedObjectReference" ) ;
  415. //init the return value array
  416. result = new String [ nl1. getLength ( ) ] ;
  417. //set return array
  418. for ( int i= 0; i< nl1. getLength ( ) ; i+ + ) {
  419. //make sure the ID is for Virtual Machine
  420. if ( nl1. item ( i) . hasChildNodes ( ) & &
  421. nl1. item ( i) . getAttributes ( ) . getNamedItem ( "type" ) . toString ( ) . trim ( ) . equals ( "type=/"VirtualMachine/"" ) ) {
  422. result [ i] = nl1. item ( i) . getFirstChild ( ) . getNodeValue ( ) . toString ( ) . trim ( ) ;
  423. debugOutput( "VMID=" + result [ i] ) ;
  424. }
  425. }
  426. return result ;
  427. }
  428. private String genXML_getVMInfo( String [ ] vmIDList) {
  429. String result ;
  430. String tmpxml= "" ;
  431. for ( int i= 0; i< vmIDList. length ; i+ + ) {
  432. tmpxml + = "<objectSet><obj type=/"VirtualMachine/">" + vmIDList[ i] + "</obj></objectSet>" ;
  433. }
  434. result = xml_getVMInfo. replace ( "$VMIDLISTOBJ$" , tmpxml) ;
  435. debugOutput( result ) ;
  436. return result ;
  437. }
  438. private void dispalyHttpResponse ( HttpResponse rsp) throws Exception {
  439. HttpEntity entity = rsp. getEntity ( ) ;
  440. System . out. println ( "********************<HTTP Response>********************" ) ;
  441. System . out. println ( "----------------------<HEADERS>------------------------" ) ;
  442. System . out. println ( rsp. getStatusLine( ) ) ;
  443. Header[ ] headers = rsp. getAllHeaders( ) ;
  444. for ( int i = 0; i < headers. length ; i+ + ) {
  445. System . out. println ( headers[ i] ) ;
  446. }
  447. System . out. println ( "-----------------------<BODYS>-------------------------" ) ;
  448. if ( entity ! = null ) {
  449. System . out. println ( EntityUtils. toString ( entity ) ) ;
  450. }
  451. System . out. println ( "************************<END>*************************" ) ;
  452. System . out. println ( ) ;
  453. System . out. println ( ) ;
  454. }
  455. private HttpResponse sendXML( String URL , String xml ) throws Exception {
  456. HttpPost httppost = new HttpPost( URL ) ;
  457. StringEntity myEntity = new StringEntity( xml ) ;
  458. httppost. addHeader( "Content-Type" , "text/xml; charset=/"utf-8/"" ) ;
  459. httppost. addHeader( "User-Agent" , "VMware VI Client/4.1.0" ) ;
  460. httppost. addHeader( "SOAPAction" , "/"urn:internalvim25/4.0/"" ) ;
  461. httppost. setEntity( myEntity) ;
  462. if ( debug) System . out. println ( "executing request to " + httppost) ;
  463. HttpResponse rsp = httpclient. execute ( httppost) ;
  464. return rsp;
  465. }
  466. private String ip2URL ( String IPAddress) {
  467. return "HTTPS://" + IPAddress+ "/sdk/" ;
  468. }
  469. private String formatData ( String data, int width ) {
  470. String result ;
  471. if ( data!=null) {
  472. result = data;
  473. } else {
  474. result = "N/A" ;
  475. }
  476. //Append space
  477. for ( int i= result . length ( ) ; i< = width ; i+ + ) {
  478. result + = " " ;
  479. }
  480. return result ;
  481. }
  482. public static void main( String [ ] args) throws Exception {
  483. Vmoperation temp = new Vmoperation( ) ;
  484. System . out. println ( temp. Connect ( "<Your ESXi IP>" , "<Username>" , "<Password>" ) ) ;
  485. System . in . read ( ) ;
  486. System . out. println ( temp. PowerOffVM( "New Virtual Machine" ) ) ;
  487. System . in . read ( ) ;
  488. temp. DisplayVMList( ) ;
  489. System . in . read ( ) ;
  490. System . out. println ( temp. PowerOnVM( "New Virtual Machine" ) ) ;
  491. System . in . read ( ) ;
  492. System . out. println ( temp. ResetVM( "New Virtual Machine" ) ) ;
  493. System . in . read ( ) ;
  494. System . out. println ( temp. Disconnect ( ) ) ;
  495. }
  496. }

注:以上仅用于学术研究,禁止用于实际生产环境。否则将导致违反VMWare License Agreement. VMWare可能随时改变XML的定义,导致程序不能正常工作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: