C# 使用WMI以编程方式更改远程IP地址
我正在编写一个应用程序,使用WMI更改本地和远程计算机的IP地址。此代码成功地更改了远程计算机的网关和DNS,并且相同的代码(在不同的类中,减去管理范围部分)在本地更改了所有数据(两个IP、网关、DNS)。问题是它不会更改远程IP地址。我到处都在寻找这个答案,有人能给我建议吗 我在Windows7和xp上进行了测试,没有防火墙,远程机器上安装了.NET4C# 使用WMI以编程方式更改远程IP地址,c#,ip,wmi,C#,Ip,Wmi,我正在编写一个应用程序,使用WMI更改本地和远程计算机的IP地址。此代码成功地更改了远程计算机的网关和DNS,并且相同的代码(在不同的类中,减去管理范围部分)在本地更改了所有数据(两个IP、网关、DNS)。问题是它不会更改远程IP地址。我到处都在寻找这个答案,有人能给我建议吗 我在Windows7和xp上进行了测试,没有防火墙,远程机器上安装了.NET4 class remoteIPChange { public string setTillIP(string IPAddress1, s
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地址匹配的有效子网数组,而不是空值。返回值是多少?请注意,当您更改远程计算机的IP地址时,保持与远程计算机连接的难度。因此,如果得到返回值1“成功完成,需要重新启动”,不要感到惊讶。它不会返回错误代码,而是返回“更新的Ip地址到…”消息。我过去曾设法使其工作,但我记不起如果您正在更改网关,请确保您也已设置到该网关的路由-在目标主机和/或路由器上。我从你的书面报告中猜测,你仍然能够使用与以前相同的旧IP与目标进行通信?你有什么解决方案吗?