簡體   English   中英

使用WMI以編程方式更改遠程IP地址

[英]Change remote IP address programmatically using 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";
    }
}

我會從EnableStatic的invokemethod中檢查ReturnValue。 我很確定為您的子網傳遞null是您的問題。 提供與您的IP地址匹配的有效子網子網,而不是該null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM