0

我正在编写一个应用程序来使用 WMI 更改本地和远程机器的 IP 地址。此代码成功更改了远程计算机的网关和 DNS,并且相同的代码(在不同的类中并减去管理范围部分)在本地更改了所有数据(两个 IP、网关、DNS)。问题是它不会更改远程 IP 地址。当我到处寻找这个答案时,有人可以建议吗?

我已经在没有防火墙的 Windows 7 和 XP 上进行了测试,并且在远程机器上安装了 .net 4

class remoteIPChange
{
    public string setTillIP(string IPAddress1, string IPAddress2, string SubnetMask, string Gateway)
    {
        ConnectionOptions connection = new ConnectionOptions();
        connection.Username = "username";
        connection.Password = "password";
        connection.Authority = "ntlmdomain:DOMAIN";

        ManagementScope scope = new ManagementScope(
        "\\\\"+IPAddress1+"\\root\\CIMV2", connection);
        scope.Connect();

        ObjectGetOptions o = new ObjectGetOptions();

        ManagementPath p = new ManagementPath("Win32_NetworkAdapterConfiguration");

        ManagementClass objMC = new ManagementClass(scope,p,o);

        ManagementObjectCollection objMOC = objMC.GetInstances();

        foreach (ManagementObject objMO in objMOC)
        {
            if (!(bool)objMO["IPEnabled"])
            continue;

            try
            {
                ManagementBaseObject objNewIP = null;
                ManagementBaseObject objSetIP = null;
                ManagementBaseObject objNewGate = null;
                ManagementBaseObject objNewDNS = null;

                objNewIP = objMO.GetMethodParameters("EnableStatic");
                objNewGate = objMO.GetMethodParameters("SetGateways");
                objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");

                //Set DefaultGateway
                objNewGate["DefaultIPGateway"] = new string[] { Gateway };
                objNewGate["GatewayCostMetric"] = new int[] { 1 };

                //Set IPAddress and Subnet Mask
                objNewIP["IPAddress"] = new string[] { IPAddress1, IPAddress2 };
                objNewIP["SubnetMask"] = new string[] { SubnetMask, SubnetMask };

                //Set DNS servers
                objNewDNS["DNSServerSearchOrder"] = new string[] {Gateway };

                //Invoke all changes
                objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
                objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
                objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);

                return ("Updated IPAddress to " + IPAddress + ", \nSubnetMask to " + SubnetMask + " \nand Default Gateway to " + Gateway + "!");
            }
            catch (Exception ex)
            {
                return ("Unable to Set IP : " + ex.Message);
            }
        }
        return "code has not run";
    }
}
4

1 回答 1

0

我会从 EnableStatic 的调用方法中检查 ReturnValue。我很确定为您的子网传入 null 是您的问题。提供与您的 IP 地址匹配的有效子网数组,而不是那个空值。

于 2013-08-29T20:15:55.243 回答