使用WMI以编程方式更改远程IP地址

时间:2012-07-07 12:50:02

标签: c# ip wmi

我正在编写一个应用程序来使用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";
    }
}

1 个答案:

答案 0 :(得分:0)

我会从EnableStatic上的invoke方法检查ReturnValue。我很确定你的子网传入null是你的问题。提供与您的IP地址匹配的有效子网数组,而不是该地址。