使用C#和vimapi进行虚拟机克隆 [英] vm cloning using C# and vimapi

查看:116
本文介绍了使用C#和vimapi进行虚拟机克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hai试图在esx服务器中克隆vm,该服务器将esx的ip和vmname用作命令行参数,并要求输入用户名和密码,但无法执行此操作.下面是正在解决的代码.如果有人可以帮忙,我会很高兴.

Hai am trying to clone vm in the esx server which takes ip of the esx and vmname as command line arguments and asks for user name and password But am not able to do the same. Below is the code am working around. I will be glad if anybody can help.

using System;
using System.Net.Security;
// for SoapException class
using System.Web.Services.Protocols;
using System.Security.Cryptography.X509Certificates;
// the VirtualInfrastructureManagement Service Reference
using VimApi;
using ReadPassword;
namespace SimpleClient
{

    /// <summary>
    /// This is a simple standalone client whose purpose is to demonstrate the
    /// process for Logging into the Webservice, and get Container contents 
    /// starting at the root Folder available in the ServiceInstanceContent
    /// </summary>
    public class SimpleClient
    {

        protected VimService _service;
        protected ServiceContent _sic;
        protected ManagedObjectReference _svcRef;

        protected ManagedObjectReference _propCol;
        protected ManagedObjectReference _rootFolder;
        protected String datacenter;
        /// <summary>
        /// Create the Managed Object Reference for the service
        /// </summary>
        /// <param name="svcRefVal">to define service reference for HostAgent or VPX</param>
        public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public void CreateServiceRef(string svcRefVal)
        {
            // Manage bad certificates our way:
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
            _svcRef = new ManagedObjectReference();
            _svcRef.type = "ServiceInstance";

            // could be ServiceInstance for "HostAgent" and "VPX" for VPXd
            _svcRef.Value = svcRefVal;
        }

        /// <summary>
        /// Creates an instance of the VMA proxy and establishes a connection
        /// </summary>
        /// <param name="url">web service url</param>
        /// <param name="username">authorized user</param>
        /// <param name="password">password for authorized user</param>
        public void Connect(string url)
        {
            if (_service != null)
            {
                Disconnect();
            }

            _service = new VimService();
            _service.Url = url;
            _service.CookieContainer = new System.Net.CookieContainer();

            _sic = _service.RetrieveServiceContent(_svcRef);
            _propCol = _sic.propertyCollector;
            _rootFolder = _sic.rootFolder;
            String username = String.Empty;
            String password = String.Empty;
            if (_sic.sessionManager != null)
            {
                Console.Write("Please enter user name:");
                username = Console.ReadLine();
                Console.WriteLine("Please enter password:");
                ReadPasswordClass x = new ReadPasswordClass();
                password = x.ReadPassword();
                _service.Login(_sic.sessionManager, username, password, null);

            }
        }



        /// <summary>
        /// Log''s out and Disconnects from the WebService
        /// </summary>
        public void Disconnect()
        {
            if (_service != null)
            {
                _service.Logout(_sic.sessionManager);

                _service.Dispose();
                _service = null;
                _sic = null;
            }
        }

        /// <summary>
        /// Get Container contents for all childEntities accessible from rootFolder
        /// </summary>
        public void GetContainerContents()
        {
            // Create a Filter Spec to Retrieve Contents for...
            TraversalSpec traversalSpec = new TraversalSpec();
            traversalSpec.type = "Folder";
            traversalSpec.name = "traverseChild";
            traversalSpec.path = "childEntity";
            traversalSpec.skip = false;
            traversalSpec.selectSet = new SelectionSpec[] { new SelectionSpec() };
            traversalSpec.selectSet[0].name = traversalSpec.name;

            PropertySpec[] propspecary = new PropertySpec[] { new PropertySpec() };
            propspecary[0].all = false;
            propspecary[0].allSpecified = true;
            propspecary[0].pathSet = new string[] { "name" };
            propspecary[0].type = "ManagedEntity";

            PropertyFilterSpec spec = new PropertyFilterSpec();
            spec.propSet = propspecary;
            spec.objectSet = new ObjectSpec[] { new ObjectSpec() };
            spec.objectSet[0].obj = _rootFolder;
            spec.objectSet[0].skip = false;
            spec.objectSet[0].selectSet = new SelectionSpec[] { traversalSpec };

            // Recursively get all ManagedEntity ManagedObjectReferences 
            // and the "name" property for all ManagedEntities retrieved
            ObjectContent[] ocary =
               _service.RetrieveProperties(
                  _propCol, new PropertyFilterSpec[] { spec }
               );

            // If we get contents back. print them out.
            if (ocary != null)
            {
                ObjectContent oc = null;
                ManagedObjectReference mor = null;
                DynamicProperty[] pcary = null;
                DynamicProperty pc = null;
                for (int oci = 0; oci < ocary.Length; oci++)
                {
                    oc = ocary[oci];
                    mor = oc.obj;
                    pcary = oc.propSet;

                    Console.WriteLine("Object Type : " + mor.type);
                    Console.WriteLine("Reference Value : " + mor.Value);
                    

                    if (pcary != null)
                    {
                        for (int pci = 0; pci < pcary.Length; pci++)
                        {
                            pc = pcary[pci];
                            Console.WriteLine("   Property Name : " + pc.name);
                            if (pc != null)
                            {
                                if (!pc.val.GetType().IsArray)
                                {
                                    Console.WriteLine("   Property Value : " + pc.val);
                                    if (mor.type.Contains("Datacenter"))
                                    {
                                        datacenter = pc.val.ToString() ;
                                    }
                                }
                                else
                                {
                                    Array ipcary = (Array)pc.val;
                                    Console.WriteLine("Val : " + pc.val);
                                    for (int ii = 0; ii < ipcary.Length; ii++)
                                    {
                                        object oval = ipcary.GetValue(ii);
                                        if (oval.GetType().Name.IndexOf("ManagedObjectReference") >= 0)
                                        {
                                            ManagedObjectReference imor = (ManagedObjectReference)oval;

                                            Console.WriteLine("Inner Object Type : " + imor.type);
                                            Console.WriteLine("Inner Reference Value : " + imor.Value);
                                        }
                                        else
                                        {
                                            Console.WriteLine("Inner Property Value : " + oval);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("No Managed Entities retrieved!");
            }
        }

        public  Object[] getProperties(ManagedObjectReference moRef, String[] properties)
        {
            // PropertySpec specifies what properties to
            // retrieve and from type of Managed Object
            PropertySpec pSpec = new PropertySpec();
            pSpec.type = moRef.type;
            pSpec.pathSet = properties;

            // ObjectSpec specifies the starting object and
            // any TraversalSpecs used to specify other objects 
            // for consideration
            ObjectSpec oSpec = new ObjectSpec();
            oSpec.obj = moRef;

            // PropertyFilterSpec is used to hold the ObjectSpec and 
            // PropertySpec for the call
            PropertyFilterSpec pfSpec = new PropertyFilterSpec();
            pfSpec.propSet = new PropertySpec[] { pSpec };
            pfSpec.objectSet = new ObjectSpec[] { oSpec };

            // retrieveProperties() returns the properties
            // selected from the PropertyFilterSpec

            //VimService service1 = new VimService();
            ManagedObjectReference _svcRef1 = new ManagedObjectReference();
            _svcRef1.type = "ServiceInstance";
            _svcRef1.Value = "ServiceInstance";

            ServiceContent sic1 = _service.RetrieveServiceContent(_svcRef1);
            ObjectContent[] ocs = new ObjectContent[20];
            ocs = _service.RetrieveProperties(sic1.propertyCollector, new PropertyFilterSpec[] { pfSpec });

            // Return value, one object for each property specified
            Object[] ret = new Object[properties.Length];

            if (ocs != null)
            {
                for (int i = 0; i < ocs.Length; ++i)
                {
                    ObjectContent oc = ocs[i];
                    DynamicProperty[] dps = oc.propSet;
                    if (dps != null)
                    {
                        for (int j = 0; j < dps.Length; ++j)
                        {
                            DynamicProperty dp = dps[j];
                            // find property path index
                            for (int p = 0; p < ret.Length; ++p)
                            {
                                if (properties[p].Equals(dp.name))
                                {
                                    ret[p] = dp.val;
                                }
                            }
                        }
                    }
                }
            }
            return ret;
        }
        
        public  Object getObjectProperty(ManagedObjectReference moRef, String propertyName)
        {
            return getProperties(moRef, new String[] { propertyName })[0];
        }

        public void CloneVM(String Template)
        {
            ManagedObjectReference searchIndex = new ManagedObjectReference();
            searchIndex = _sic.searchIndex;
            ManagedObjectReference datacenterRef = _service.FindByInventoryPath(searchIndex, datacenter);
            if (datacenterRef == null)
            {
                Console.WriteLine("The specified datacenter is not found");
            }
            ManagedObjectReference vmREf = _service.FindByIp(searchIndex,null, "172.19.194.44", true);
            
            ///////////////////////////////////////////////
            // Find the virtual machine folder for this datacenter.
            ManagedObjectReference vmFolderRef = (ManagedObjectReference)getObjectProperty(datacenterRef, "vmFolder");
            ManagedObjectReference[] vmList = (ManagedObjectReference[])getObjectProperty(vmFolderRef, "childEntity");
            ManagedObjectReference templateRef = null;
            Boolean gotVmRef = false;

            for (int i = 0; i < vmList.Length && gotVmRef==false ; i++)
            {
                if (vmList[i].type == "VirtualMachine")
                {
                    Object[] vmProps = getProperties(vmList[i],
                        new String[] { "config.name", "config.guestFullName" });

                    //if ((Boolean)vmProps[1] == true)
                    //{
                        //Console.WriteLine((String)vmProps[0]);
                        if (((String)vmProps[0]).Equals(Template))
                        {
                            templateRef = vmList[i];
                            gotVmRef = true;
                        }
                    
                    else
                    {
                        Console.WriteLine("VM Found:"+(String)vmProps[0]);
                    }
                }
            }
            //for (int i = 0;((i < vmList.Length)&& (gotVmRef==false)) ; i++)
            //{
            //    ManagedObjectReference[] temp = (ManagedObjectReference[])getObjectProperty(vmList[i], "childEntity");
            //    for (int j = 0; j < temp.Length; j++)
            //    {
            //        ManagedObjectReference[] temp1=null ;
            //        try
            //        {
            //             temp1 = (ManagedObjectReference[])getObjectProperty(temp[j], "childEntity");
            //        }
            //        catch (Exception x) 
            //        { }
            //        if (temp1 != null)
            //        {
            //            for (int k = 0; k < temp1.Length; k++)
            //            {
            //                if (temp1[k].type == "VirtualMachine")
            //                {

            //                    Object[] vmProps = getProperties(temp1[k],new String[] { "config.name", "config.template" });

            //                    if ((Boolean)vmProps[1] == true)
            //                    {
            //                        Console.WriteLine(vmProps[0].ToString());
            //                        if (((String)vmProps[0]).Equals(Template))
            //                        {
            //                            templateRef = temp1[k];
            //                            gotVmRef = true;
            //                            break;
            //                        }
            //                    }
            //                    else
            //                    {
            //                        //Console.WriteLine("Template not found in the current Datacenter");
            //                    }
            //                }
            //            }
            //        }
            //    }
            // }
            VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)getObjectProperty(templateRef, "config");

            //if (vmConfigInfo.template.Equals(false ))
            VirtualMachineRuntimeInfo vmRuntimeInfo = (VirtualMachineRuntimeInfo)getObjectProperty(templateRef, "runtime");
            ManagedObjectReference hostRef = vmRuntimeInfo.host; //_service.FindByIp(searchIndex, null, "172.19.194.245", false);
            // Get the host folder from the data center.
            ManagedObjectReference hostFolderRef = (ManagedObjectReference)getObjectProperty(datacenterRef, "hostFolder");
            // Get the compute resource from host folder.
            ManagedObjectReference[] crList = (ManagedObjectReference[])getObjectProperty(hostFolderRef, "childEntity");
            ManagedObjectReference computeResourceRef;
            computeResourceRef = null;
            for (int i = 0; i < crList.Length; i++)
            {
                if (crList[i].type == "ComputeResource")
                {
                    computeResourceRef = crList[i];
                    break;
                }
            }
            if (computeResourceRef != null)
            {
                // Get the resource pool from the compute resource.
                ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)getObjectProperty(computeResourceRef, "resourcePool");
                ManagedObjectReference resourcePoolRef = resourcePoolRootRef;

                // Making VirtualMachineCloneSpec to clone template

                VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
                VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();
                relocSpec.host = hostRef  ;
                relocSpec.pool = resourcePoolRef;
                cloneSpec.location = relocSpec;
                cloneSpec.location.pool = resourcePoolRef;
               
                cloneSpec.powerOn = false;
                cloneSpec.template = false;
                
                VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
                
                cloneSpec.config = configSpec;

                
                String clonedName = "VMCLONEDTEST";
                Console.WriteLine("Launching clone task to create a clone: " + clonedName);
                //ManagedObjectReference cloneTask = _service.CloneVM_Task(templateRef, vmFolderRef, clonedName, cloneSpec);
                if (cloneSpec != null)
                {
                    // Performing CloneVM_Task
                    ManagedObjectReference cloneTask = _service.CloneVM_Task(templateRef, vmFolderRef, clonedName, cloneSpec);
                }
                else
                {
                    Console.WriteLine("Clone spec is null");
                }

            }
        }


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                Console.WriteLine("Usage : SimpleClient <webserviceurl>");
            }

            SimpleClient sc = new SimpleClient();

            try
            {
                // Create the Service Managed Object Reference
                sc.CreateServiceRef("ServiceInstance");

                // Connect to the Service
                sc.Connect(args[0]);

                // Retrieve Container contents for all Managed Entities and their names
                sc.GetContainerContents();

                //Clone VM
                sc.CloneVM(args[1]);

                // Disconnect from the WebServcice
                sc.Disconnect();
            }
            catch (SoapException se)
            {
                Console.WriteLine("Caught SoapException - " + " Actor : " + se.Actor + " Code : " + se.Code + " Detail XML : " + se.Detail.OuterXml);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception : " + " Name : " + e.GetType().Name + " Message : " + e.Message + " Trace : " + e.StackTrace);
            }
        }

    }

}

推荐答案

请转到源并尝试在此处找到帮助:http://www.vmware.com/support/pubs/sdk_pubs.html [
Please go to the source and try to find help there: http://www.vmware.com/support/pubs/sdk_pubs.html[^].

Best Regards,

—MRB


这篇关于使用C#和vimapi进行虚拟机克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆