Beispiel #1
0
 public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
 {
     ManagementScope connectScope = new ManagementScope();
      connectScope.Path = new ManagementPath(@"\\" + machineName + path);
      connectScope.Options = options;
      connectScope.Connect();
      return connectScope;
 }
Beispiel #2
0
        }//end of gets

        public static string GetProcessMan(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_Processor");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string manuf = "";

            foreach (ManagementObject n in searcher.Get())
            {
                manuf = n["Manufacturer"].ToString();
            }
            return(manuf);
        }//end of gets
    public static void Main()
    {
        // Build an options object for the remote connection
        // if you plan to connect to the remote
        // computer with a different user name
        // and password than the one you are currently using.
        // This example uses the default values.
        ConnectionOptions options =
            new ConnectionOptions();

        options.Authentication =
            System.Management.AuthenticationLevel.PacketPrivacy;

        // Make a connection to a remote computer.
        // Replace the "FullComputerName" section of the
        // string "\\\\FullComputerName\\root\\cimv2" with
        // the full computer name or IP address of the
        // remote computer.
        ManagementScope scope =
            new ManagementScope(
                "\\\\FullComputerName\\root\\cimv2", options);

        scope.Connect();

        //Query system for Operating System information
        ObjectQuery query = new ObjectQuery(
            "SELECT * FROM Win32_OperatingSystem");
        ManagementObjectSearcher searcher =
            new ManagementObjectSearcher(scope, query);

        ManagementObjectCollection queryCollection = searcher.Get();

        foreach (ManagementObject m in queryCollection)
        {
            // Display the remote computer information
            Console.WriteLine("Computer Name : {0}",
                              m["csname"]);
            Console.WriteLine("Windows Directory : {0}",
                              m["WindowsDirectory"]);
            Console.WriteLine("Operating System: {0}",
                              m["Caption"]);
            Console.WriteLine("Version: {0}", m["Version"]);
            Console.WriteLine("Manufacturer : {0}",
                              m["Manufacturer"]);
        }
    }
Beispiel #4
0
        static void WriteCSV(ManagementScope scope, string wmi_query, string csvfile)
        {
            CsvWriter writer = null;
            ManagementObjectSearcher searcher = null;
            SelectQuery query = new SelectQuery();

            try
            {
                scope.Connect();

                query.QueryString = wmi_query;
                using (searcher = new ManagementObjectSearcher(scope, query))
                    using (writer = new CsvWriter(new StreamWriter(csvfile)))
                    {
                        for (int i = 0; i < query.SelectedProperties.Count; i++)
                        {
                            writer.WriteField(query.SelectedProperties[i].ToString());
                        }
                        writer.NextRecord();

                        foreach (System.Management.ManagementObject service in searcher.Get())
                        {
                            for (int i = 0; i < query.SelectedProperties.Count; i++)
                            {
                                //if ((service[query.SelectedProperties[i].ToString()]) is string[])
                                //{
                                //    writer.WriteField(string.Join(" *** ", (string[])service[query.SelectedProperties[i].ToString()]));
                                //}
                                //else if ((service[query.SelectedProperties[i].ToString()]) is int[]) { }
                                //else
                                //{
                                //    writer.WriteField(service[query.SelectedProperties[i].ToString()]);
                                //}
                                writer.WriteField(service[query.SelectedProperties[i].ToString()]);
                            }
                            writer.NextRecord();
                        }
                    }
            }
            catch (Exception ex)
            {
                logger.Error("Can not connect Management target.");
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
            }
        }
Beispiel #5
0
        public void Select_All_Win32_LogicalDisk_Wql(string scopeRoot)
        {
            var query = new SelectQuery("select * from Win32_LogicalDisk");
            var scope = new ManagementScope(scopeRoot + @"root\cimv2");

            scope.Connect();

            using (var searcher = new ManagementObjectSearcher(scope, query))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    Assert.True(collection.Count > 0);
                    foreach (ManagementBaseObject result in collection)
                    {
                        Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString()));
                    }
                }
        }
        private List <ProcessInfo> GetProcessList()
        {
            var connection = new ConnectionOptions {
                Authentication = AuthenticationLevel.PacketPrivacy
            };

            var scope = new ManagementScope(@"\\localhost\root\CIMV2", connection);

            scope.Connect();

            var processQuery    = new ObjectQuery("SELECT * FROM Win32_Process");
            var processSearcher = new ManagementObjectSearcher(scope, processQuery);

            var infoList = new List <ProcessInfo>();

            try
            {
                foreach (var p in processSearcher.Get())
                {
                    try
                    {
                        PropertyData pidProp  = p.Properties["ProcessId"];
                        PropertyData pathProp = p.Properties["ExecutablePath"];

                        if (pidProp.Value != null && pathProp.Value != null)
                        {
                            infoList.Add(
                                new ProcessInfo
                            {
                                ProcessId = (int)(uint)pidProp.Value,
                                Path      = (string)pathProp.Value,
                                Name      = System.IO.Path.GetFileName((string)pathProp.Value)
                            });
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (ManagementException)
            {
            }

            return(infoList);
        }
Beispiel #7
0
        }//end of getos

        public static string GetServicePack(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string service = "";

            foreach (ManagementObject n in searcher.Get())
            {
                service = n["servicepackmajorversion"].ToString();
            }
            return(service);
        }//end of getsn
Beispiel #8
0
        }//end of getmodel

        public static string GetSN(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_BIOS");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string sn = "";

            foreach (ManagementObject n in searcher.Get())
            {
                sn = n["SerialNumber"].ToString();
            }
            return(sn);
        }//end of getsn
Beispiel #9
0
        static void GetServices(string ns, string host)
        {
            ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\{1}", host, ns));
            //https://docs.microsoft.com/en-us/windows/win32/wmisdk/wql-operators
            //https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-service
            SelectQuery query = new SelectQuery("SELECT name,displayname,startname,description,systemname FROM Win32_Service WHERE startname IS NOT NULL");

            // Requires Local Admin. Try catch for insufficient privs, network connectivity issues, etc
            try
            {
                Console.WriteLine("[+] {0} - Connecting", host);
                scope.Connect();
                //https://stackoverflow.com/questions/842533/in-c-sharp-how-do-i-query-the-list-of-running-services-on-a-windows-server
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
                {
                    Console.WriteLine("[+] {0} - Enumerating services", host);
                    ManagementObjectCollection services = searcher.Get();
                    Console.WriteLine("[+] {0} - Found {1} services running", host, services.Count);
                    Console.WriteLine("[+] {0} - Filtering out LocalSystem and NT Authority Account services", host);
                    bool results = false;
                    foreach (ManagementObject service in services)
                    {
                        // Exclude services running as local accounts
                        string[] exclusions = { "LOCALSYSTEM", "NT AUTHORITY\\LOCALSERVICE", "NT AUTHORITY\\NETWORKSERVICE" };
                        if (!exclusions.Contains(service["StartName"].ToString().ToUpper()))
                        {
                            Console.WriteLine("[+] Host: {0}", service["SystemName"]);
                            Console.WriteLine(" Account: {0}", service["StartName"]);
                            Console.WriteLine(" Service: {0}", service["Name"]);
                            Console.WriteLine("    Name: {0}", service["DisplayName"]);
                            Console.WriteLine("    Info: {0}", service["Description"]);
                            results = true;
                        }
                    }
                    if (!results)
                    {
                        Console.WriteLine("[!] {0} - No other services identified", host);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[!] " + ex.Message);
                Console.WriteLine("[!] {0} - Unable to query services", host);
            }
        }
Beispiel #10
0
        public void RegisterCertificateWithIIS6(string webSiteName, string certificateFilePath, string certificatePassword)
        {
            // USE WMI TO DERIVE THE INSTANCE NAME
            ManagementScope managementScope = new ManagementScope(@"\\.\root\MicrosoftIISv2");

            managementScope.Connect();
            ObjectQuery queryObject = new ObjectQuery("SELECT Name FROM IISWebServerSetting WHERE ServerComment = '" + webSiteName + "'");
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(managementScope, queryObject);
            var instanceNameCollection            = searchObject.Get();
            var instanceName = (from i in instanceNameCollection.Cast <ManagementObject>() select i).FirstOrDefault();

            // USE IIS CERT OBJ TO IMPORT CERT - THIS IS A COM OBJECT
            var IISCertObj = new CERTOBJLib.IISCertObjClass();

            IISCertObj.InstanceName = instanceName["Name"].ToString();
            IISCertObj.Import(certificateFilePath, certificatePassword, false, true);             // OVERWRITE EXISTING
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            string host     = ".";
            string userName = "******";
            string password = "******";

            ConnectionOptions connectionOptions = new ConnectionOptions();

            if (host != ".")
            {
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
            }
            ManagementScope managementScope = new ManagementScope("//" + host + "/root/cimv2", connectionOptions);

            try
            {
                managementScope.Connect();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            ObjectQuery query = new ObjectQuery(
                "SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(managementScope, query);

            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementObject m in queryCollection)
            {
                // Display the remote computer information
                Console.WriteLine("Computer Name : {0}",
                                  m["csname"]);
                Console.WriteLine("Windows Directory : {0}",
                                  m["WindowsDirectory"]);
                Console.WriteLine("Operating System: {0}",
                                  m["Caption"]);
                Console.WriteLine("Version: {0}", m["Version"]);
                Console.WriteLine("Manufacturer : {0}",
                                  m["Manufacturer"]);
            }

            Console.ReadKey();
        }
Beispiel #12
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor");
            ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController");
            ManagementObjectSearcher searcher4 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PhysicalMemory");

            ManagementScope scope = new ManagementScope("root\\cimv2");

            scope.Connect();
            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory");
            ManagementObjectSearcher searcher3 = new ManagementObjectSearcher(scope, query);
            int Capacity = 0;
            ManagementObjectCollection queryCollection = searcher3.Get();

            foreach (ManagementObject m in queryCollection)
            {
                Capacity = Capacity + Convert.ToInt32(Math.Round(System.Convert.ToDouble(m["Capacity"]) / 1024 / 1024));
                string test = Convert.ToString(m["Manufacturer"]);
                label10.Text = "Об'єм: " + (Convert.ToString(Capacity) + " MБ");
                //MessageBox.Show(test);
            }
            //CPU
            foreach (ManagementObject queryObj in searcher1.Get())
            {
                label1.Text = string.Format("Назва: {0}", queryObj["Name"]);
                label2.Text = string.Format("Кількість ядер: {0}", queryObj["NumberOfCores"]);
                label9.Text = string.Format("Опис: {0}", queryObj["Caption"]);
            }
            //RAM
            foreach (ManagementObject queryObj in searcher3.Get())
            {
                label5.Text = string.Format("Назва: {0}", queryObj["MemoryType"]);//speed 677 + 800 //Manufacturer Kingston + Uknknow
            }
            //GPU
            foreach (ManagementObject queryObj in searcher2.Get())
            {
                //  label12.Text = string.Format("Назва: {0}", queryObj["Name"]);
                label3.Text  = string.Format("Назва: {0}", queryObj["Caption"]);
                label4.Text  = string.Format("Сімейство: {0}", queryObj["VideoProcessor"]);
                label11.Text = string.Format("Об'єм: {0}", Convert.ToInt32(queryObj["AdapterRAM"] + " Мегабайт"));
                //   label11.Text = string.Format("Об'єм: {0}", Convert.ToInt32(queryObj["AdapterRAM"] + " Мегабайт"));
                // label11.Text = Convert.ToInt32(Math.Round(System.Convert.ToDouble(m["Capacity"]) / 1024 / 1024));
            }

            //label10.Text = ("Об'єм: "+Capacity.ToString()+" Мегабайт"); // ответ в Мб
        }
Beispiel #13
0
        public ManagementScope ConnectToRemoteWmi(string hostname, string scope, ConnectionOptions options)
        {
            try
            {
                var wmiscope = new ManagementScope($"\\\\{hostname}{scope}", options);
                wmiscope.Connect();
                return(wmiscope);
            }
            catch (Exception e)
            {
                ResultConsole.Instance.AddConsoleLine($"Failed to connect to WMI namespace \\\\{hostname}{scope}");
                ResultConsole.Instance.AddConsoleLine($"Exception message: {e.Message}");
                _logger.LogError($"Error connecting to WMI namespace \\\\{hostname}{scope}", e);

                return(null);
            }
        }
Beispiel #14
0
        static void RemoteWMIQuery(string host, string wmiQuery, string wmiNameSpace, string username, string password)
        {
            if (wmiNameSpace == "")
            {
                wmiNameSpace = "root\\cimv2";
            }

            ConnectionOptions options = new ConnectionOptions();

            Console.WriteLine("\r\n  Scope: \\\\{0}\\{1}", host, wmiNameSpace);

            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("  User credentials: {0}", username);
                options.Username = username;
                options.Password = password;
            }
            Console.WriteLine();

            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);

            try
            {
                scope.Connect();

                ObjectQuery query = new ObjectQuery(wmiQuery);
                ManagementObjectSearcher   searcher = new ManagementObjectSearcher(scope, query);
                ManagementObjectCollection data     = searcher.Get();

                Console.WriteLine();

                foreach (ManagementObject result in data)
                {
                    System.Management.PropertyDataCollection props = result.Properties;
                    foreach (System.Management.PropertyData prop in props)
                    {
                        Console.WriteLine(String.Format("{0,30} : {1}", prop.Name, prop.Value));
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("  Exception : {0}", ex.Message));
            }
        }
Beispiel #15
0
        public static string GetMotherBoardID()
        {
            string          mbInfo = string.Empty;
            ManagementScope scope  = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");

            scope.Connect();
            ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions());

            foreach (PropertyData propData in wmiClass.Properties)
            {
                if (propData.Name == "SerialNumber")
                {
                    mbInfo = string.Format("{0,-25}{1}", propData.Name, Convert.ToString(propData.Value));
                }
            }
            return(mbInfo.Replace("SerialNumber ", "").Replace("            ", ""));
        }
Beispiel #16
0
        public static void Get(string UserName, string Password, string Domain, string ComputerName, object Hive, string SubKey)
        {
            ManagementScope scope = null;

            try
            {
                ConnectionOptions connection = new ConnectionOptions();

                if (UserName != null)
                {
                    try
                    {
                        connection.Username  = UserName;
                        connection.Password  = Password;
                        connection.Authority = $"NTLMDOMAIN:{Domain}";
                    }
                    catch
                    {
                        connection.Impersonation = System.Management.ImpersonationLevel.Impersonate;
                    }
                }
                else
                {
                    connection.Impersonation = System.Management.ImpersonationLevel.Impersonate;
                }

                scope = new ManagementScope($"\\\\{ComputerName}\\root\\default", connection);
                scope.Connect();

                ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);

                ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey");
                inParams["hDefKey"]     = (UInt32)Hive;
                inParams["sSubKeyName"] = SubKey;
                ManagementBaseObject outParams = registry.InvokeMethod("EnumKey", inParams, null);
                Console.WriteLine($"[+] Successfully retrieved SubKeys for key {SubKey}\n");
                foreach (string Name in (string[])outParams["sNames"])
                {
                    Console.WriteLine(Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"[-] Error: {e.Message}");
            }
        }
Beispiel #17
0
        }//end of gets

        public static string GetMaxSpeed(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_Processor");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string speed = "";

            foreach (ManagementObject n in searcher.Get())
            {
                speed = n["MaxClockSpeed"].ToString();
            }
            return(speed);
        }//end of gets
Beispiel #18
0
        private static List <string> ReadRemoteRegistryusingWMI(string ComputerName)
        {
            List <string> programs = new List <string>();

            ConnectionOptions connectionOptions = new ConnectionOptions();
            //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope scope = new ManagementScope("\\\\" + ComputerName + "\\root\\CIMV2", connectionOptions);

            try
            {
                scope.Connect();

                string softwareRegLoc = @"Software\Microsoft\Windows\CurrentVersion\Uninstall";

                ManagementClass      registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey");
                inParams["hDefKey"]     = 0x80000002;//HKEY_LOCAL_MACHINE
                inParams["sSubKeyName"] = softwareRegLoc;

                // Read Registry Key Names
                ManagementBaseObject outParams    = registry.InvokeMethod("EnumKey", inParams, null);
                string[]             programGuids = outParams["sNames"] as string[];

                foreach (string subKeyName in programGuids)
                {
                    inParams                = registry.GetMethodParameters("GetStringValue");
                    inParams["hDefKey"]     = 0x80000002;//HKEY_LOCAL_MACHINE
                    inParams["sSubKeyName"] = softwareRegLoc + @"\" + subKeyName;
                    inParams["sValueName"]  = "DisplayName";
                    // Read Registry Value
                    outParams = registry.InvokeMethod("GetStringValue", inParams, null);

                    if (outParams.Properties["sValue"].Value != null)
                    {
                        string softwareName = outParams.Properties["sValue"].Value.ToString();
                        programs.Add(softwareName);
                    }
                }
            }
            catch
            {
            }


            return(programs);
        }
Beispiel #19
0
        }//end of getsn

        public static string GetOS(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string os = "";

            foreach (ManagementObject n in searcher.Get())
            {
                os = n["Caption"].ToString();
            }
            return(os);
        }//end of getos
Beispiel #20
0
        public bool CheckConnection()
        {
            ConnectionOptions connectionOptions = new ConnectionOptions();

            connectionOptions.Username = _username;
            connectionOptions.Password = _password;
            ManagementScope managementScope = new ManagementScope(_manageScope, connectionOptions);

            try
            {
                managementScope.Connect();
            }
            catch (Exception ex)
            {
            }
            return(managementScope.IsConnected);
        }
Beispiel #21
0
        }//end of getsn

        public static string GetLastBootUp(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string boottime = "";

            foreach (ManagementObject n in searcher.Get())
            {
                boottime = n["LastBootUpTime"].ToString();
            }
            return(boottime);
        }//end of getsn
Beispiel #22
0
        //Получение коллекции объектов
        private ManagementObjectCollection GetManagementObject(string printerName)
        {
            ConnectionOptions options = new ConnectionOptions();

            options.EnablePrivileges = true;
            //options.Username = "******";
            options.Impersonation = ImpersonationLevel.Impersonate;
            //options.Impersonation = ImpersonationLevel.Delegate;
            managementScope = new ManagementScope(ManagementPath.DefaultPath, options);
            managementScope.Connect();
            SelectQuery selectQuery = new SelectQuery();

            selectQuery.QueryString = @"SELECT * FROM Win32_Printer WHERE Name = '" + printerName.Replace("\\", "\\\\") + "'";
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, @selectQuery);

            return(managementObjectSearcher.Get());
        }
Beispiel #23
0
        public void Select_Win32_LogicalDisk_ClassName_Condition()
        {
            var query = new SelectQuery("Win32_LogicalDisk", "DriveType=3");
            var scope = new ManagementScope($@"\\{WmiTestHelper.TargetMachine}\root\cimv2");

            scope.Connect();

            using (var searcher = new ManagementObjectSearcher(scope, query))
                using (ManagementObjectCollection collection = searcher.Get())
                {
                    Assert.True(collection.Count > 0);
                    foreach (ManagementBaseObject result in collection)
                    {
                        Assert.True(!string.IsNullOrEmpty(result.GetPropertyValue("DeviceID").ToString()));
                    }
                }
        }
Beispiel #24
0
        }//end of getsn

        public static string GetSize(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string size = "";

            foreach (ManagementObject n in searcher.Get())
            {
                size = n["Size"].ToString();
            }
            return(size);
        }//end of getsize
        /// <summary>
        /// Permet de retourner la liste des valeurs dans un chemin donnée.
        /// </summary>
        /// <param name="subKey"></param>
        /// <param name="valueName"></param>
        /// <returns></returns>
        public Task<string> GetValueInUserAsync(string hostName, string subKey, string valueName)
        {
            return Task.Factory.StartNew(() =>
            {
                ManagementScope scope = new ManagementScope("\\\\" + hostName + "\\root\\CIMV2", _connectionOption);
                scope.Connect();

                ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);

                ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue");
                inParams.SetPropertyValue("hDefKey", 0x80000003);
                inParams.SetPropertyValue("sSubKeyName", subKey);
                inParams.SetPropertyValue("sValueName", valueName);

                return registry.InvokeMethod("GetStringValue", inParams, null).Properties["sValue"]?.Value?.ToString();
            });
        }
Beispiel #26
0
        }//end of gets

        public static string GetCores(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_Processor");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string cores = "";

            foreach (ManagementObject n in searcher.Get())
            {
                cores = n["NumberOfCores"].ToString();
            }
            return(cores);
        }//end of gets
Beispiel #27
0
 //多執行緒檢察windows NonPage Time 3.2版新增
 private void CheckWindowsNonPageThread(object obj)
 {
     //轉型傳過來的obj
     string[] Askitem = new string[10];
     Askitem = (string[])obj;
     //0=TargetIP , 1 = TargetName, 2= TargetDomain ,3=TargetUser ,4=TargetPassword ,5=TargetDeviceID ,6=TargetAlert ,7=TargetSpaceLog ,8=id , 9=TargetWarning
     //開始檢察
     try
     {
         //這邊進行wmi查詢目標硬碟代號
         System.Management.ConnectionOptions Conn = new ConnectionOptions();
         //設定用於WMI連接操作的用戶名
         string user = Askitem[2] + "\\" + Askitem[3];
         Conn.Username = user;
         //設定用戶的密碼
         Conn.Password = Askitem[4];
         //設定用於執行WMI操作的範圍
         System.Management.ManagementScope Ms = new ManagementScope("\\\\" + Askitem[0] + "\\root\\cimv2", Conn);
         Ms.Connect();
         ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
         //WQL語句,設定的WMI查詢內容和WMI的操作範圍,檢索WMI對象集合
         ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms, Query);
         //異步調用WMI查詢
         ManagementObjectCollection ReturnCollection = Searcher.Get();
         //設定接收的變數
         int      NonBytesInt;
         string[] text = new string[4];
         foreach (ManagementObject Return in ReturnCollection)
         {
             NonBytesInt = (int.Parse(Return["PoolNonpagedBytes"].ToString()) / 1024 / 1024);
             text[0]     = Askitem[1];             //名稱
             text[1]     = NonBytesInt.ToString(); //NonPageBytesInt
             text[2]     = "Windows";              //檢察windows
             text[3]     = Askitem[8];             //WindowsTargetID
             if (NonBytesInt >= LimitNonPage)
             {
                 this.Invoke(new D_AddNonPageGridView(AddNonPageGridView), new object[] { text });
             }
         }
     }
     catch (Exception x)
     {
         this.Invoke(new D_AddErrorList(AddErrorList), Askitem[1] + " >>NonPageCheckError>> " + x.Message.ToString());
     }
     this.Invoke(new D_AddProgress(AddProgress), null);
 }
Beispiel #28
0
        public static string GetModel(string computer)
        {
            ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2");

            scope.Connect();
            WqlObjectQuery wqlQuery =
                new WqlObjectQuery("SELECT * FROM Win32_ComputerSystemProduct");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, wqlQuery);
            string model = "";

            foreach (ManagementObject n in searcher.Get())
            {
                model = n["Version"].ToString();
            }
            return(model);
        }//end of getmodel
        }//End Detect OS Drive

        #endregion

        #region Drive Type
        //Some test code to get the drive type SSD HDD ect...
        private static string DriveType(int driveNumber)
        {
            ManagementScope          scope    = new ManagementScope(@"\\.\root\microsoft\windows\storage");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM MSFT_PhysicalDisk where DeviceId = " + driveNumber.ToString());
            string type = "";

            scope.Connect();
            searcher.Scope = scope;

            try
            {
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    switch (Convert.ToInt16(queryObj["MediaType"]))
                    {
                    case 1:
                        type = "Unspecified";
                        return(type);

                    case 3:
                        type = "HDD";
                        return(type);

                    case 4:
                        type = "SSD";
                        return(type);

                    case 5:
                        type = "SCM";
                        return(type);

                    default:
                        type = "Unspecified";
                        return(type);
                    }
                }
            }
            catch
            {
            }

            searcher.Dispose();

            return(type);
        }
        /// <summary>
        /// The function determines whether the operating system of the 
        /// current machine of any remote machine is a 64-bit operating 
        /// system through Windows Management Instrumentation (WMI).
        /// </summary>
        /// <param name="machineName">
        /// The full computer name or IP address of the target machine. "." 
        /// or null means the local machine.
        /// </param>
        /// <param name="domain">
        /// NTLM domain name. If the parameter is null, NTLM authentication 
        /// will be used and the NTLM domain of the current user will be used.
        /// </param>
        /// <param name="userName">
        /// The user name to be used for the connection operation. If the 
        /// user name is from a domain other than the current domain, the 
        /// string may contain the domain name and user name, separated by a 
        /// backslash: string 'username' = "DomainName\\UserName". If the 
        /// parameter is null, the connection will use the currently logged-
        /// on user
        /// </param>
        /// <param name="password">
        /// The password for the specified user.
        /// </param>
        /// <returns>
        /// The function returns true if the operating system is 64-bit; 
        /// otherwise, it returns false.
        /// </returns>
        /// <exception cref="System.Management.ManagementException">
        /// The ManagementException exception is generally thrown with the  
        /// error code: System.Management.ManagementStatus.InvalidParameter.
        /// You need to check whether the parameters for ConnectionOptions 
        /// (e.g. user name, password, domain) are set correctly.
        /// </exception>
        /// <exception cref="System.Runtime.InteropServices.COMException">
        /// A common error accompanied with the COMException is "The RPC 
        /// server is unavailable. (Exception from HRESULT: 0x800706BA)". 
        /// This is usually caused by the firewall on the target machine that 
        /// blocks the WMI connection or some network problem.
        /// </exception>
        public static bool Is64Bit(string machineName, string domain, string userName, string password)
        {
            ConnectionOptions options = null;
            if (!string.IsNullOrEmpty(userName))
            {
                // Build a ConnectionOptions object for the remote connection 
                // if you plan to connect to the remote with a different user 
                // name and password than the one you are currently using.
                options = new ConnectionOptions();
                options.Username = userName;
                options.Password = password;
                options.Authority = "NTLMDOMAIN:" + domain;
            }
            // Else the connection will use the currently logged-on user

            // Make a connection to the target computer.
            ManagementScope scope = new ManagementScope("\\\\" +
                (string.IsNullOrEmpty(machineName) ? "." : machineName) +
                "\\root\\cimv2", options);
            scope.Connect();

            // Query Win32_Processor.AddressWidth which dicates the current 
            // operating mode of the processor (on a 32-bit OS, it would be 
            // "32"; on a 64-bit OS, it would be "64").
            // Note: Win32_Processor.DataWidth indicates the capability of 
            // the processor. On a 64-bit processor, it is "64".
            // Note: Win32_OperatingSystem.OSArchitecture tells the bitness
            // of OS too. On a 32-bit OS, it would be "32-bit". However, it 
            // is only available on Windows Vista and newer OS.
            ObjectQuery query = new ObjectQuery(
                "SELECT AddressWidth FROM Win32_Processor");

            // Perform the query and get the result.
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();
            foreach (ManagementObject queryObj in queryCollection)
            {
                if (queryObj["AddressWidth"].ToString() == "64")
                {
                    return true;
                }
            }

            return false;
        }
Beispiel #31
0
        public List <string> GetHardwareListFromRemote()
        {
            var             list  = new List <string>();
            ManagementScope scope = new ManagementScope();

            try
            {
                //get the credentials to connect to this computer with
                ConnectionOptions options = new ConnectionOptions();
                options.Username         = "******";
                options.Password         = "******";
                options.EnablePrivileges = true;
                options.Authority        = "ntlmdomain: ";
                //Create the scope that will connect to the default root for WMI
                scope = new ManagementScope(@"\\dazgen-wpc\root\CIMV2″, options");
                scope.Connect();
                //query the computer for the OS information
                SelectQuery query = new SelectQuery("SELECT * FROM Win32_OperatingSystem");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                using (ManagementObjectCollection queryCollection = searcher.Get())
                {
                    foreach (ManagementObject m in queryCollection)
                    {
                        // Display the remote computer’s information in our labels
                        list.Add(string.Format(";Computer Name: { 0}", m["csname"]));
                        //Label1.Text = string.Format(“Windows Directory: { 0}”, m[“WindowsDirectory”]);
                        //Label1.Text = string.Format(“Operating System: { 0}”, m[“Caption”]);
                        //Label1.Text = string.Format(“Version: { 0}”, m[“Version”]);
                        //Label1.Text = string.Format(“Manufacturer: { 0}”, m[“Manufacturer”]);
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }



            return(list);
        }
    public async Task initConnection()
    {

        var timeOut = new TimeSpan(0, 5, 0);
        ConnectionOptions options = new ConnectionOptions();
        options.Authority = "NTLMDOMAIN:" + remoteDomain.Trim();
        options.Username = remoteUser.Trim();
        options.Password = remotePass.Trim();
        options.Impersonation = ImpersonationLevel.Impersonate;
        options.Timeout = timeOut;



        scope = new ManagementScope("\\\\" + remoteComputerName.Trim() + connectionNamespace, options);
        scope.Options.EnablePrivileges = true;

        scope2 = new ManagementScope("\\\\" + remoteComputerName.Trim() + "\\root\\default", options);
        scope2.Options.EnablePrivileges = true;

        try
        {
            await Task.Run(() => { scope.Connect(); });
        }

        catch (Exception)
        {
            await Task.Run(() => { scope.Connect(); });
        }

    }
Beispiel #33
0
        public static string GetMotherBoardID()
        {
            string mbInfo = String.Empty;
            ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
            scope.Connect();
            ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions());

            foreach (PropertyData propData in wmiClass.Properties)
            {
                if (propData.Name == "SerialNumber")
                    mbInfo = String.Format("{0}", Convert.ToString(propData.Value).Trim()).Replace('-', '#'); ;
            }

            return mbInfo;
        }