用c#更改IP.Gateway,Mask等的和对.net下调用WMI的认识

private void Ipstatic()
  {
   ManagementBaseObject inPar1  = null;
   ManagementBaseObject inPar2  = null;
   ManagementBaseObject outPar1 = null;
   ManagementBaseObject outPar2 = null;
   ManagementClass mc = new ManagementClass( "Win32_NetworkAdapterConfiguration");
   ManagementObjectCollection moc = mc.GetInstances();
   foreach( ManagementObject mo in moc )
   {
    if( !(bool)mo[ "IPEnabled" ])
     continue;
    if( mo["Caption"].Equals("[00000008] VMware Virtual Ethernet Adapter for VMnet1") )
    {
     inPar1 = mo.GetMethodParameters( "EnableStatic" );
     inPar2 = mo.GetMethodParameters( "SetGateways" );
     inPar2["DefaultIPGateway"] = new string[] { "192.168.1.1" };
     inPar2["GatewayCostMetric"] = new int[] {1};
     
     inPar1["IPAddress"] = new string[] { "192.168.1.10" };     
     inPar1["SubnetMask"] = new string[] { "255.255.255.0" };
     outPar1 = mo.InvokeMethod( "EnableStatic", inPar1, null );
     outPar2 = mo.InvokeMethod( "SetGateways", inPar2, null );
     break;
    }           
   }

此为c#版本,只能在本地执行.(不能在asp.net中使用,原因现在没还弄清楚,可能是MicroSoft在IIS设置了什么)

注意,需要导入System.Management或System.Management.Dll这个.net组件.这样才可以使用System.Management这个名字空间.

用这种方法,可以使用.net语言来调用WMI的类和接口.具体见msdn

 

下面再介绍一种调用WMI的方法(同时兼顾远程调用时的问题)(老外的代码,具体见

http://www.codeproject.com/csharp/wmi.asp 

//Connect to the remote computer
ConnectionOptions co = new ConnectionOptions();

co.Username = textUserID.Text;
co.Password = textPassword.Text;

//Point to machine
System.Management.ManagementScope ms = new System.Management.
    ManagementScope("" + stringHostName + "//root//cimv2", co);

(这里改成"."也可以表示本地)

//Query system for Operating System information
System.Management.ObjectQuery oq = new System.Management.ObjectQuery(
    "SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher query = new ManagementObjectSearcher(ms,oq);

queryCollection = query.Get();
foreach ( ManagementObject mo in queryCollection)
{

   (以下代码不用看了)
    //create child node for operating system
    createChildNode(nodeCollection, "Operating System: " +
        mo["Caption"]);
    createChildNode(nodeCollection, "Version: " + mo["Version"]);
    createChildNode(nodeCollection, "Manufacturer : " +
        mo["Manufacturer"]);
    createChildNode(nodeCollection, "Computer Name : " +
        mo["csname"]);
    createChildNode(nodeCollection, "Windows Directory : " +
        mo["WindowsDirectory"]);
}     

其实ManagementClass也可以完成以上功能(用它的不同的构造函数),具体见msdn
下面是一个补充:(把查询得到的TCP/IP信息,放到asp.net中显示)
 private void Button1_Click(object sender, System.EventArgs e)
  {
   ManagementClass mc = new ManagementClass( "Win32_NetworkAdapterConfiguration");
   ManagementObjectCollection moc = mc.GetInstances();
   foreach( ManagementObject mo in moc )
   {
    if( !(bool) mo[ "IPEnabled"] )
     continue;
    if( mo["Caption"].Equals( "[00000001] ADMtek AN983 10/100 PCI Adapter" ) )
    {
     string[] addresses = ( string[] ) mo["IPAddress"];
    
     foreach( string ipadr in addresses )
     {
      IP1.Text = ipadr.ToString();
      MAC1.Text = mo["MACAddress"].ToString();
     }
    }
    if( mo["Caption"].Equals( "[00000008] VMware Virtual Ethernet Adapter for VMnet1") )
    {
     string[] addresses = ( string[] ) mo["IPAddress"];
    
     foreach( string ipadr in addresses )
     {
      IP2.Text = ipadr.ToString();
      MAC2.Text = mo["MACAddress"].ToString();
     }
    }    
   } 
  }
下面是在Console App中实现的代码:
 static void ReportIP()
  {
   Console.WriteLine( "****** Current IP addresses:" );
   ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
   ManagementObjectCollection moc = mc.GetInstances();
   foreach( ManagementObject mo in moc )
   {
    if( ! (bool) mo[ "IPEnabled" ] )
     continue;
    Console.WriteLine( "{0}//n SVC: /'{1}/' MAC: [{2}]", (string) mo["Caption"],
     (string) mo["ServiceName"], (string) mo["MACAddress"] );
    string[] addresses = (string[]) mo[ "IPAddress" ];
    string[] subnets = (string[]) mo[ "IPSubnet" ];
    Console.WriteLine( " Addresses :" );
    foreach(string sad in addresses)
     Console.WriteLine( "", sad );
    Console.WriteLine( " Subnets :" );
    foreach(string sub in subnets )
     Console.WriteLine( "
", sub );
   }
  }

 

Introduction

This article demonstrates the power of WMI, on how to configure TCP/IP Setting programmatically using C#. This article is targeted at intermediate developers.

Using the code

WMI Extends the possibilities of .NET and simplifies the life while working on NetworkAdapters. The Following Code snippet lists all the Network adapters along with the IP Address, Subnet Mask, Default Gateway

public void ListIP()
{
 ManagementClass objMC = new ManagementClass(
    "Win32_NetworkAdapterConfiguration");
 ManagementObjectCollection objMOC = objMC.GetInstances();
 
foreach(ManagementObject objMO in objMOC)
{
          if(!(bool)objMO["ipEnabled"])
                 continue;


       
          Console.WriteLine(objMO["Caption"] + "," +
            objMO["ServiceName"] + "," + objMO["MACAddress"]) ;
          string[] ipaddresses = (string[]) objMO["IPAddress"];
          string[] subnets = (string[]) objMO["IPSubnet"];
          string[] gateways = (string[]) objMO["DefaultIPGateway"];

  
          Console.WriteLine("Printing Default Gateway Info:");
          Console.WriteLine(objMO["DefaultIPGateway"].ToString());
         
          Console.WriteLine("Printing IPGateway Info:");
          foreach(string sGate in gateways)
               Console.WriteLine (sGate);

 
          Console.WriteLine("Printing Ipaddress Info:");

          foreach(string sIP in ipaddresses)
               Console.WriteLine(sIP);
 
          Console.WriteLine("Printing SubNet Info:");

          foreach(string sNet in subnets)
               Console.WriteLine(sNet);

Now, here is the code to configure TCP/IP Settings using WMI.

public void setIP(string IPAddress,string SubnetMask, string Gateway)
{
 
ManagementClass objMC = new ManagementClass(
    "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();

 
foreach(ManagementObject objMO in objMOC)
{

      if (!(bool) objMO["IPEnabled"])
           continue;


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

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


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

          //Set IPAddress and Subnet Mask
          objNewIP["IPAddress"] = new string[] {IPAddress};
          objNewIP["SubnetMask"] = new string[] {SubnetMask};
         
          objSetIP = objMO.InvokeMethod("EnableStatic",objNewIP,null);
          objSetIP = objMO.InvokeMethod("SetGateways",objNewGate,null);


         
          Console.WriteLine(
             "Updated IPAddress, SubnetMask and Default Gateway!");


       
        }
        catch(Exception ex)
        {
              MessageBox.Show("Unable to Set IP : " + ex.Message); }
        }

 

How to Programmatically add IP Addresses to IIS's Deny Access List using C# and WMI
using System;
using System.IO;
using System.Collections;
using System.DirectoryServices;
using System.Reflection;

namespace soccerwrek
{
 class IISWMI
 {     
  [STAThread]
  static void Main(string[] args)
      {
         try
         {
            // retrieve the directory entry for the root of the IIS server
            System.DirectoryServices.DirectoryEntry IIS =
               new System.DirectoryServices.DirectoryEntry(
               "IIS://localhost/w3svc/1/root");
            // retrieve the list of currently denied IPs
            Console.WriteLine(
                "Retrieving the list of currently denied IPs.");
            // get the IPSecurity property
            Type typ = IIS.Properties["IPSecurity"][0].GetType();
            object IPSecurity = IIS.Properties["IPSecurity"][0];
            // retrieve the IPDeny list from the IPSecurity object
            Array origIPDenyList = (Array) typ.InvokeMember("IPDeny",
                       BindingFlags.DeclaredOnly |
                       BindingFlags.Public | BindingFlags.NonPublic |
                       BindingFlags.Instance | BindingFlags.GetProperty,
                       null, IPSecurity, null);
            // display what was being denied
            foreach(string s in origIPDenyList)
               Console.WriteLine("Before: " + s);
            // check GrantByDefault.  This has to be set to true,
            // or what we are doing will not work.
            bool bGrantByDefault = (bool) typ.InvokeMember("GrantByDefault",
                        BindingFlags.DeclaredOnly |
                        BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Instance | BindingFlags.GetProperty,
                        null, IPSecurity, null);
            Console.WriteLine("GrantByDefault = " + bGrantByDefault);
            if(!bGrantByDefault)
            {
               typ.InvokeMember("GrantByDefault",
                      BindingFlags.DeclaredOnly |
                      BindingFlags.Public | BindingFlags.NonPublic |
                      BindingFlags.Instance | BindingFlags.SetProperty,
                      null, IPSecurity, new object[] {true});
            }
            // update the list of denied IPs.  This is a
            // complete replace.  If you want to maintain what
            // was already being denied, you need to make sure
            // those IPs are in here as well.  This area
            // will be where you will most likely modify to
            // your needs as this is just an example.
            Console.WriteLine("Updating the list of denied IPs.");
            object[] newIPDenyList = new object[4];
            newIPDenyList[0] = "192.168.1.1, 255.255.255.255";
            newIPDenyList[1] = "192.168.1.2, 255.255.255.255";
            newIPDenyList[2] = "192.168.1.3, 255.255.255.255";
            newIPDenyList[3] = "192.168.1.4, 255.255.255.255";
            Console.WriteLine("Calling SetProperty");
            // add the updated list back to the IPSecurity object
            typ.InvokeMember("IPDeny",
                     BindingFlags.DeclaredOnly |
                     BindingFlags.Public | BindingFlags.NonPublic |
                     BindingFlags.Instance | BindingFlags.SetProperty,
                     null, IPSecurity, new object[] {newIPDenyList});
           
            IIS.Properties["IPSecurity"][0] = IPSecurity;           
            Console.WriteLine("Commiting the changes.");
            // commit the changes
            IIS.CommitChanges();
            IIS.RefreshCache();
            // check to see if the update took
            Console.WriteLine("Checking to see if the update took.");
            IPSecurity = IIS.Properties["IPSecurity"][0];
            Array y = (Array) typ.InvokeMember("IPDeny",
                      BindingFlags.DeclaredOnly |
                      BindingFlags.Public | BindingFlags.NonPublic |
                      BindingFlags.Instance | BindingFlags.GetProperty,
                      null, IPSecurity, null);
            foreach(string s in y)
               Console.WriteLine("After:  " + s);
         }
         catch (Exception e)
         {
            Console.WriteLine("Error: " + e.ToString());
         }
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值