c# - vsphere api 更改虚拟机的 IP 地址

标签 c# vmware vsphere

我是 vsphere api 的新手,我正在尝试将虚拟机的网络设置从动态 IP 更改为静态 IP,但找不到该设置。 这是我到目前为止的代码,它连接到 vsphere,查找虚拟机,并更改虚拟机的名称。
我假设 VirtualMachineConfigSpec 中有一个设置也会更改网络设置,但我找不到它。

VimClient vimClient = new VimClient();
ServiceContent serviceContent = vimClient.Connect("https://[MY ADDRESS]/sdk");
UserSession us = vimClient.Login("[USERNAME]","[PASSWORD]");

ManagedObjectReference _svcRef = new ManagedObjectReference();
_svcRef.Type = "ServiceInstance";
_svcRef.Value = "ServiceInstance";

NameValueCollection filterForVM = new NameValueCollection();
filterForVM.Add("Name","[VIRTUAL MACHINE NAME]");
VirtualMachine vm = (VirtualMachine)vimClient.FindEntityView(typeof(VirtualMachine),null,filterForVM,null);
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();

vmConfigSpec.Name = "[NEW NAME]"; // change the VM name
vmConfigSpec.???? // how to set the ip address

vm.ReconfigVM_Task(vmConfigSpec);

vimClient.Disconnect();

最佳答案

VMware API 没有在虚拟机 guest 操作系统上设置 IP 地址的设置,因为 IP 地址设置取决于 guest 操作系统版本。您可以使用两种方法来做到这一点:

1) 您可以使用GuestOperationsManager从 VMware vSphere API 启动 guest 操作系统上的 IP 地址设置脚本。

先决条件:

  • 您应该为每个支持的操作系统(Linux、Windows 等)编写 IP 地址设置脚本
  • 必须在每个受支持的虚拟机上安装 VMware Tools(以便使用 GuestOperationsManager)。

Update2. 以下是在 guest 操作系统上运行脚本的简化示例。本示例不包含错误处理、获取脚本日志、VM开机等内容。

using System;
using System.IO;
using System.Net;
using Vim25Api;

namespace RunScriptOnGuestOsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.RunScriptInGuestOs(
                "https://10.1.1.10/sdk",
                "root",
                "vmware",
                "c:\\temp\\test.bat",
                "vm-73",
                "Administrator",
                "P@ssword",
                "c:\\test.bat",
                String.Empty);
        }

        public void RunScriptInGuestOs(string vCenterUrl, string vCenterUserName, string vCenterPassword, string scriptFilePatch, string vmKey, string username, string password, string destinationFilePath, string arguments)
        {
            var service = CreateVimService(vCenterUrl, 600000, true);
            var serviceContent = RetrieveServiceContent(service);
            service.Login(serviceContent.sessionManager, vCenterUserName, vCenterPassword, null);

            byte[] dataFile;
            using (var fileStream = new FileStream(scriptFilePatch, FileMode.Open, FileAccess.Read))
            {
                dataFile = new byte[fileStream.Length];
                fileStream.Read(dataFile, 0, dataFile.Length);
            }

            FileTransferToGuest(service, vmKey, username, password, destinationFilePath, dataFile);
            RunProgramInGuest(service, vmKey, username, password, destinationFilePath, arguments);
        }

        private static VimService CreateVimService(string url, int serviceTimeout, bool trustAllCertificates)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
            return new VimService
            {
                Url = url,
                Timeout = serviceTimeout,
                CookieContainer = new CookieContainer()
            };
        }

        private ServiceContent RetrieveServiceContent(VimService service)
        {
            var serviceInstance = new ManagedObjectReference
            {
                type = "ServiceInstance",
                Value = "ServiceInstance"
            };

            var content = service.RetrieveServiceContent(serviceInstance);
            if (content.sessionManager == null)
            {
                throw new ApplicationException("Session manager is null.");
            }

            return content;
        }

        private void FileTransferToGuest(VimService service, string vmKey, string username, string password, string fileName, byte[] fileData)
        {
            var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false };
            var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey };
            var fileMgr = new ManagedObjectReference { type = "GuestFileManager", Value = "guestOperationsFileManager" };
            var posixFileAttributes = new GuestPosixFileAttributes();
            posixFileAttributes.ownerId = 1;
            posixFileAttributes.groupId = 1;
            posixFileAttributes.permissions = (long)0777; //execution file

            var requestUrl = service.InitiateFileTransferToGuest(fileMgr, vmRef, auth, fileName, posixFileAttributes, fileData.Length, true);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
            request.ContentType = "application/octet-stream";
            request.Method = "PUT";
            request.ContentLength = fileData.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileData, 0, fileData.Length);
            requestStream.Close();

            request.GetResponse();
        }

        private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments)
        {
            var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false };
            var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey };
            var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments };
            var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" };
            var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec);
        }
    }
}

2) 您可以使用 DHCP 服务器来管理分配的 IP 地址。使用VMware API,您可以获得虚拟机的MAC地址。接下来,您应该设置 DHCP 服务器,以便在获得的 MAC 地址上分配所需的 IP 地址。

先决条件:

  • 必须将每个虚拟机设置为从 DHCP 服务器获取 IP 地址。
  • 可根据您的需求进行配置的 DHCP 服务器。

关于c# - vsphere api 更改虚拟机的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320469/

相关文章:

c# - EventStore重复提交异常

c# - 在 C# 中使用外部文件和 MVVM 模式在运行时更改语言

c# - WebBrowser.Body 总是返回 null

linux - VMware ESXi 本地存储速度慢,仅位于一个磁盘分区上

sql-server - 在 NIC 的高级属性中更改小型 RX 缓冲区的脚本

c# String.Split((string)null, , StringSplitOptions.RemoveEmptyEntries) 不按空格分割,它有什么作用?

vmware 解锁器错误 : "file not found - darwin*.*"

javascript - vSphere Web 客户端自定义插件中的 AngularJS UI 渲染问题

directory - ESXi 服务器中 vmware 的共享文件夹选项

java - 六、JAVA : Getting Custom Fields (Names and Values) from Virtual Machines