WMI入门

作者: SMILE_NO_09 | 来源:发表于2018-02-23 15:02 被阅读70次

    IT部门要求统计一下各个Team手里的Windows Server,提供一个大概的配置信息,但是Server太多,逐个查看太过于麻烦,于是想到直接用VMI去获取系统数据,但是必须要本地运行。网上查找发现ManagementScope 可以实现远程登录,正好可以用ManagementScope与WMI写了一个小程序Windows Server获取信息。

    1WMI

    WMI 即Windows Management Instrumentation,可以通过WMI控制远程计算机。通过DCOM连接实现。还有一种通过SOAP实现管理连接的WinRM。
    微软文档:https://msdn.microsoft.com/en-us/library/aa384642(v=vs.85).aspx
    官方文档详尽的讲解了VIM,这里直接跳到.NET部分。
    System.Management 命名空间下的类及其功能

    Technology Area Classes/interfaces/configuration elements
    WMI类的信息采集 ManagementObject, ManagementClass
    查询数据 SelectQuery, ManagementObjectSearcher, WqlObjectQuery, ObjectQuery
    异步查询数据 ManagementObjectCollection, ManagementOperationObserver
    执行方法 ManagementBaseObject
    异步执行方法 ManagementOperationObserver
    接收事件 WqlEventQuery, ManagementEventWatcher
    异步接收事件 EventArrivedEventArgs, EventArrivedEventHandler, CompletedEventArgs, CompletedEventHandler
    连接远程计算机 ConnectionOptions, ManagementScope

    System.Management.Instrumentation命名空间下的类及其功能

    Technology Area Classes/interfaces/configuration elements
    Creating data providers Instance, InstrumentationClassAttribute, InstrumentedAttribute
    Creating event providers BaseEvent, Instrumentation
    Registering a provider ManagementInstaller

    2 WMI Queries

    查询WMI的语句类似于SQL,叫WQL (SQL for WMI)
    例如:

    SELECT * FROM Win32_OperatingSystem
    

    语法参考:https://msdn.microsoft.com/en-us/library/aa394606(v=vs.85).aspx
    微软提供了很多的Win32 Provider,用于查询系统信息。具体需要哪些和对应查询出来的字段含义请参考:https://msdn.microsoft.com/en-us/library/aa394388(v=vs.85).aspx

    3代码实现

    了解了如上信息,需要查询数据,要用到的类有SelectQuery, ManagementObjectSearcher, WqlObjectQuery, ObjectQuery。远程登录需要用到ConnectionOptions, ManagementScope。
    代码如下:

            /// <summary>
            /// 远程连接计算机
            /// </summary>
            /// <param name="Host">计算机名称</param>
            /// <param name="UID">登录用户</param>
            /// <param name="PWD">登录密码</param>
            /// <returns></returns>
            private static  ManagementScope getManagementScope(string Host, string UID, string PWD)
            {
                ConnectionOptions connOption = new ConnectionOptions();
                connOption.Username = UID.Trim();
                connOption.Password = PWD;
                return new ManagementScope("//" + Host.Trim() + "/root/cimv2", connOption);
                //return new ManagementScope("//" + Host.Trim() + "/root/cimv2");
            }
    
            /// <summary>  
            /// 获取远程Windows系统的OS信息  
            /// </summary>  
            /// <param name="Host">远程主机</param>  
            /// <param name="UID">远程主机的用户名</param>  
            /// <param name="PWD">密码</param>  
            /// <returns>操作系统信息,或报告错误信息</returns>  
            public static  string GetOSInfo(string Host, string UID, string PWD)
            {
                string rtn = "";
                ManagementScope mms = null;
                ManagementObjectSearcher cmd = null;
                ManagementObjectCollection objs = null;
                try
                {
                    mms = getManagementScope(Host, UID, PWD);
                    string sql = "Select * from Win32_OperatingSystem";
              
                    cmd = new ManagementObjectSearcher(mms, new ObjectQuery(sql));
                    objs = cmd.Get();
                    foreach (ManagementObject obj in objs)
                    {
                        rtn = Host + "," + obj["Caption"].ToString().Trim();
                    }
                    string sql2 = "Select * from Win32_Processor";
                    cmd = new ManagementObjectSearcher(mms, new ObjectQuery(sql2));
                    objs = cmd.Get();
                    rtn += ",CUP个数,"+objs.Count.ToString();
                    rtn += ",CUP型号," + objs.Count.ToString();
                    foreach (ManagementObject obj in objs)
                    {
                        rtn += "," + obj["Name"].ToString().Trim();
                        rtn += ",核心数," + obj["NumberOfCores"];
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    mms = null;
                    if (cmd != null)
                        cmd.Dispose();
                    if (objs != null)
                        objs.Dispose();
                }
                return rtn;
            }  
    

    将服务器,用户,密码保存在一个txt文档中,读取调用生成CSV文件

    static void Main(string[] args)
            {
               string[] serverList = File.ReadAllLines("server.txt");
                List<string>InfoList= new List<string>();
                foreach (string item in serverList)
                {
                    string[] infos = item.Split('\t');
                    if (infos.Count() == 3)
                    {
                        try
                        {
                            string result = GetOSInfo(infos[0], infos[1], infos[2]);
                           InfoList.Add(result);
                            Console.WriteLine(result);
                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine(infos[0]+":"+ex.Message);
                        }
                    }
                }
                File.WriteAllLines("server.csv", InfoList,Encoding.UTF8);
                Console.WriteLine("pass any key to end");
                Console.ReadLine();
            }
    

    相关文章

      网友评论

          本文标题:WMI入门

          本文链接:https://www.haomeiwen.com/subject/qnrztftx.html