Exemplo n.º 1
0
 // extractSystemInfoString tar inn som parameter en System management query og henter ut
 // egenskapen definert i selector parameteret
 // dette returneres som en string
 public static string extractSystemInfoString(string query, string selector)
 {
     using (ManagementObjectSearcher mos = new ManagementObjectSearcher(query))
     {
         using (ManagementObjectCollection moc = mos.Get())
         {
             return(moc?.Cast <ManagementBaseObject>()?.SingleOrDefault()?[selector]?.ToString());
         }
     }
 }
Exemplo n.º 2
0
        // Token: 0x06000112 RID: 274 RVA: 0x0000439A File Offset: 0x0000259A
        public ReadOnlyCollection <TResult> QueryAll <TResult>(WmiQueryBase wmiQuery, ManagementObjectSearcher searcher = null) where TResult : class, new()
        {
            ManagementObjectCollection managementObjectCollection = this.QueryAll(wmiQuery.SelectQuery, searcher);

            return(new ReadOnlyCollection <TResult>((managementObjectCollection != null) ? managementObjectCollection.Cast <ManagementBaseObject>().Select(new Func <ManagementBaseObject, TResult>(WmiService.Extract <TResult>)).ToList <TResult>() : null));
        }
Exemplo n.º 3
0
        /// <summary>
        /// This is where things get interesting. The bulk of the work
        /// in data collection and class creation takes place here.
        /// </summary>
        /// <param name="ctype">Type 1 is a user collection, otherwise expect device collection.</param>
        /// <returns>Returns a ObservableCollection of SCCMCollection</returns>
        public static ObservableCollection <SCCMCollection> GetCollection(int ctype)
        {
            // Create a blank observable collection
            ObservableCollection <SCCMCollection> sc = new ObservableCollection <SCCMCollection>();

            // Retrieve the SCCM settings from the regsitry
            string SCCMServer   = Settings.GetServerName();
            string SCCMSiteCode = Settings.GetSiteCode();

            // Create some blank strings to exclude the base collections
            string excludeCol;
            string excludeID;

            // Set the name and ID of the base collection. This will be the
            // same for any instance of ConfigMgr.
            if (ctype == 1)
            {
                excludeCol = "All Users and User Groups";
                excludeID  = "SMS00004";
            }
            else
            {
                excludeCol = "All Systems";
                excludeID  = "SMS00001";
            }

            // Wrapping this all in a try catch is probably a pretty lazy
            // way to do this honestly, but it works. Pretty much the only
            // reason this fails is if you cannot talk to the SCCM server
            // or you've set the name and site code improperly.
            try
            {
                // sets the management scope to \\SCCMServer\ROOT\SMS\sms_SCCMSiteCode
                ManagementScope scope = new ManagementScope("\\\\" + SCCMServer + "\\ROOT\\SMS\\site_" + SCCMSiteCode);

                // We need the default collection to be the first object in the list
                // due to a limitation with the tree builder. So we're going to search
                // for that collection and then add it to the ObservableCollection.
                ObjectQuery query = new ObjectQuery("SELECT * FROM SMS_Collection WHERE CollectionId = '" + excludeID + "'");
                ManagementObjectSearcher   searcher       = new ManagementObjectSearcher(scope, query);
                ManagementObjectCollection allCollections = searcher.Get();
                foreach (ManagementObject sCol in allCollections.Cast <ManagementObject>().OrderBy(obj => obj["Name"]))
                {
                    sc.Add(new SCCMCollection()
                    {
                        CollectionID = excludeID, CollectionType = ctype, LimitToCollectionID = "", Name = excludeCol, LastRefreshTime = ManagementDateTimeConverter.ToDateTime(sCol["LastRefreshTime"].ToString()), MemberCount = sCol["MemberCount"].ToString()
                    });
                }

                // Now we'll search for the rest of the collections by type but exclude
                // the default collection. Since all collections build off of that the
                // remaining order of collections is not important.
                query          = new ObjectQuery("SELECT * FROM SMS_Collection WHERE CollectionType = " + ctype + " AND NOT CollectionId = '" + excludeID + "'");
                searcher       = new ManagementObjectSearcher(scope, query);
                allCollections = searcher.Get();

                // This gets a bit more involved, but essentially we're just setting
                // an SCCMCollection object with the information pulled from WMI.
                // We're also ordering them by name so that they show up in alphabetical
                // order per tier.
                foreach (ManagementObject sCol in allCollections.Cast <ManagementObject>().OrderBy(obj => obj["Name"]))
                {
                    SCCMCollection oCol = new SCCMCollection();                                                        // create a new SCCMCollection object
                    oCol.CollectionID    = sCol["CollectionId"].ToString();                                            // set the collection ID
                    oCol.CollectionType  = int.Parse(sCol["CollectionType"].ToString());                               // convert the collection type from an integer to a string
                    oCol.LastRefreshTime = ManagementDateTimeConverter.ToDateTime(sCol["LastRefreshTime"].ToString()); // convert the last refresh time from a WMI time to normal datetime
                    oCol.MemberCount     = sCol["MemberCount"].ToString();                                             // set the member count
                    if (string.IsNullOrEmpty((string)sCol["LimitToCollectionID"]))
                    {
                        oCol.LimitToCollectionID = ""; // it doesn't have a limiting collection... this shouldn't be possible.
                    }
                    else
                    {
                        oCol.LimitToCollectionID = sCol["LimitToCollectionID"].ToString(); // set the limiting collection
                    }
                    oCol.Name = sCol["Name"].ToString();                                   // set the name of the collection

                    List <string> ics = new List <string>();                               // create an empty list of include collections
                    List <string> ecs = new List <string>();                               // create an empty list of exclude collections
                    Dictionary <string, string> qcs = new Dictionary <string, string>();   // create an empty dictionary of queries (name, query)
                    List <string> dcs = new List <string>();                               // create an empty list of direct memberships

                    ManagementObject ic = new ManagementObject();                          // now we have to get the list of include/exclude collections, queries, and direct relationships
                    ManagementPath   mp = new ManagementPath(sCol["__PATH"].ToString());   // this is the path to the object in WMI so that we can get the lazy properties
                    ic.Path = mp;
                    ic.Get();                                                              // grab all the lazy properties from this object in WMI

                    // shoot me now... this has to be the worst way to handle this
                    // maybe I'll find a way to check for null entries on mbos...
                    try
                    {
                        ManagementBaseObject[] mbos = (ManagementBaseObject[])ic["CollectionRules"]; // this represents all of the collection rules
                        if (mbos.Count() > 0)
                        {
                            foreach (ManagementBaseObject mbo in mbos)
                            {
                                // exclude collections
                                if (mbo["__CLASS"].ToString() == "SMS_CollectionRuleExcludeCollection")
                                {
                                    ecs.Add(mbo["ExcludeCollectionID"].ToString() + ": " + mbo["RuleName"].ToString());
                                }
                                // include collections
                                else if (mbo["__CLASS"].ToString() == "SMS_CollectionRuleIncludeCollection")
                                {
                                    ics.Add(mbo["IncludeCollectionID"].ToString() + ": " + mbo["RuleName"].ToString());
                                }
                                // query rules
                                else if (mbo["__CLASS"].ToString() == "SMS_CollectionRuleQuery")
                                {
                                    qcs.Add(mbo["RuleName"].ToString(), mbo["QueryExpression"].ToString());
                                }
                                // direct rules
                                else if (mbo["__CLASS"].ToString() == "SMS_CollectionRuleDirect")
                                {
                                    dcs.Add(mbo["RuleName"].ToString() + " (Resource ID: " + mbo["ResourceID"] + ")");
                                }
                            }
                        }
                    }
                    catch
                    {
                        // bummer dude.
                        // basically this just means that the collection
                        // doesn't have any rules
                    }

                    // Connvert the refresh schedule to a readable format
                    try
                    {
                        oCol.RefreshSchedule = ScheduleConverter.ConvertSchedule(ic["RefreshType"].ToString(), (ManagementBaseObject[])ic["RefreshSchedule"]);
                    }
                    catch
                    {
                        oCol.RefreshSchedule = "Unknown";
                    }


                    oCol.IncludeCollections = ics; // set the include collections
                    oCol.ExcludeCollections = ecs; // set the exclude collections
                    oCol.QueryRules         = qcs; // set the query rules
                    oCol.DirectMembership   = dcs; // set the direct memberships

                    sc.Add(oCol);                  // add the collection to the ObservableCollection
                }
            }
            catch
            {
                // Something went wrong when trying to get data from the SCCM server.
                System.Windows.MessageBox.Show("An error occurred. Did you set your SCCM server name and site code properly?");
                sc.Clear();
            }
            return(sc);
        }
Exemplo n.º 4
0
        public void USB_Read()
        {
            //預設AutoBox沒接上
            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxExist", "0");
            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxPort", "");
            ini12.INIWrite(Global.MainSettingPath, "Device", "CANbusExist", "0");
            ini12.INIWrite(Global.MainSettingPath, "Device", "KlineExist", "0");

            ManagementObjectSearcher   search     = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity");
            ManagementObjectCollection collection = search.Get();
            var usbList = from u in collection.Cast <ManagementBaseObject>()
                          select new
            {
                id          = u.GetPropertyValue("DeviceID"),
                name        = u.GetPropertyValue("Name"),
                description = u.GetPropertyValue("Description"),
                status      = u.GetPropertyValue("Status"),
                system      = u.GetPropertyValue("SystemName"),
                caption     = u.GetPropertyValue("Caption"),
                pnp         = u.GetPropertyValue("PNPDeviceID"),
            };

            foreach (var usbDevice in usbList)
            {
                string deviceId          = (string)usbDevice.id;
                string deviceTp          = (string)usbDevice.name;
                string deviecDescription = (string)usbDevice.description;

                string deviceStatus  = (string)usbDevice.status;
                string deviceSystem  = (string)usbDevice.system;
                string deviceCaption = (string)usbDevice.caption;
                string devicePnp     = (string)usbDevice.pnp;

                if (deviecDescription != null)
                {
                    #region 偵測相機
                    if (deviecDescription.IndexOf("USB 視訊裝置", StringComparison.OrdinalIgnoreCase) >= 0 ||
                        deviecDescription.IndexOf("USB 视频设备", StringComparison.OrdinalIgnoreCase) >= 0 ||
                        deviceTp.IndexOf("Webcam", StringComparison.OrdinalIgnoreCase) >= 0 ||
                        deviceTp.IndexOf("Camera", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        if (deviceId.IndexOf("VID_", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            int    vidIndex      = deviceId.IndexOf("VID_");
                            string startingAtVid = deviceId.Substring(vidIndex + 4); // + 4 to remove "VID_"
                            string vid           = startingAtVid.Substring(0, 4);    // vid is four characters long
                            Global.VID.Add(vid);
                        }

                        if (deviceId.IndexOf("PID_", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            int    pidIndex      = deviceId.IndexOf("PID_");
                            string startingAtPid = deviceId.Substring(pidIndex + 4); // + 4 to remove "PID_"
                            string pid           = startingAtPid.Substring(0, 4);    // pid is four characters long
                            Global.PID.Add(pid);
                        }

                        Console.WriteLine("-----------------Camera------------------");
                        Console.WriteLine("DeviceID: {0}\n" +
                                          "Name: {1}\n" +
                                          "Description: {2}\n" +
                                          "Status: {3}\n" +
                                          "System: {4}\n" +
                                          "Caption: {5}\n" +
                                          "Pnp: {6}\n"
                                          , deviceId, deviceTp, deviecDescription, deviceStatus, deviceSystem, deviceCaption, devicePnp);

                        //Camera存在
                        ini12.INIWrite(Global.MainSettingPath, "Device", "CameraExist", "1");
                    }
                    #endregion

                    #region 偵測AutoBox1
                    if (deviceId.Substring(deviceId.Length - 2, 2) == "&3" &&
                        deviceId.IndexOf("USB\\VID_067B&PID_2303\\", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Console.WriteLine("-----------------AutoBox1------------------");
                        Console.WriteLine("DeviceID: {0}\n" +
                                          "Name: {1}\n" +
                                          "Description: {2}\n" +
                                          "Status: {3}\n" +
                                          "System: {4}\n" +
                                          "Caption: {5}\n" +
                                          "Pnp: {6}\n"
                                          , deviceId, deviceTp, deviecDescription, deviceStatus, deviceSystem, deviceCaption, devicePnp);

                        int    FirstIndex           = deviceTp.IndexOf("(");
                        string AutoBoxPortSubstring = deviceTp.Substring(FirstIndex + 1);
                        string AutoBoxPort          = AutoBoxPortSubstring.Substring(0);

                        int    AutoBoxPortLengh = AutoBoxPort.Length;
                        string AutoBoxPortFinal = AutoBoxPort.Remove(AutoBoxPortLengh - 1);

                        if (AutoBoxPortSubstring.Substring(0, 3) == "COM")
                        {
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxExist", "1");
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxVerson", "1");
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxPort", AutoBoxPortFinal);
                        }
                    }
                    #endregion

                    #region 偵測AutoBox2
                    if (deviceId.IndexOf("&0&5", StringComparison.OrdinalIgnoreCase) >= 0 &&
                        deviceId.IndexOf("USB\\VID_067B&PID_2303\\", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Console.WriteLine("-----------------AutoBox2------------------");
                        Console.WriteLine("DeviceID: {0}\n" +
                                          "Name: {1}\n" +
                                          "Description: {2}\n" +
                                          "Status: {3}\n" +
                                          "System: {4}\n" +
                                          "Caption: {5}\n" +
                                          "Pnp: {6}\n"
                                          , deviceId, deviceTp, deviecDescription, deviceStatus, deviceSystem, deviceCaption, devicePnp);

                        int    FirstIndex           = deviceTp.IndexOf("(");
                        string AutoBoxPortSubstring = deviceTp.Substring(FirstIndex + 1);
                        string AutoBoxPort          = AutoBoxPortSubstring.Substring(0);

                        int    AutoBoxPortLengh = AutoBoxPort.Length;
                        string AutoBoxPortFinal = AutoBoxPort.Remove(AutoBoxPortLengh - 1);

                        if (AutoBoxPortSubstring.Substring(0, 3) == "COM")
                        {
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxExist", "1");
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxVerson", "2");
                            ini12.INIWrite(Global.MainSettingPath, "Device", "AutoboxPort", AutoBoxPortFinal);
                        }
                    }
                    #endregion

                    #region 偵測CANbus
                    if (deviceId.IndexOf("USB\\VID_04D8&PID_0053\\", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Console.WriteLine("-----------------Canbus------------------");
                        Console.WriteLine("DeviceID: {0}\n" +
                                          "Name: {1}\n" +
                                          "Description: {2}\n" +
                                          "Status: {3}\n" +
                                          "System: {4}\n" +
                                          "Caption: {5}\n" +
                                          "Pnp: {6}\n"
                                          , deviceId, deviceTp, deviecDescription, deviceStatus, deviceSystem, deviceCaption, devicePnp);

                        ini12.INIWrite(Global.MainSettingPath, "Device", "CANbusExist", "1");
                    }
                    #endregion
                }
            }
        }
Exemplo n.º 5
0
        private void ParseSections(object sender, System.Timers.ElapsedEventArgs hse)         // Main checks loop
        {
            hstimer.Stop();
            float curval = 0;

            // Headers
            alarms = 0;
            output = "Healthstone checks: " + Environment.MachineName; // The output string contains the results from all checks

            try                                                        // Get computer name
            {
                wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
                foreach (ManagementObject items in wmi.Get())
                {
                    output += " - " + items["Caption"] + " (" + items["OSArchitecture"] + ")";
                }
            }
            catch (Exception e)
            {
                output += " - " + e;
                alarms += 1;
            }
            output += " - " + cfg["general"]["template"] + "\n\n";

            // Checks
            if (cfg.ContainsKey("checkcpu"))             // check cpu load
            {
                try
                {
                    cpu = new PerformanceCounter();
                    cpu.CategoryName = "Processor";
                    cpu.CounterName  = "% Processor Time";
                    cpu.InstanceName = "_Total";
                    float val1 = cpu.NextValue();
                    Thread.Sleep(500);
                    float val2 = cpu.NextValue();
                    Thread.Sleep(500);
                    float val3 = cpu.NextValue();
                    curval = Math.Max(val1, Math.Max(val2, val3));
                    if (curval > Int32.Parse(cfg["checkcpu"]["maximum"]))
                    {
                        output += "--> [CheckCPU] High CPU load: " + curval + "%\n";
                        alarms += 1;
                    }
                    else if (cfg["general"]["verbose"] == "true")
                    {
                        output += "[CheckCPU] CPU load: " + curval + "%\n";
                    }
                }
                catch (Exception e)
                {
                    output += "[CheckCPU] Performance Counter failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkmemory"))             // check free memory
            {
                try
                {
                    wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
                    foreach (ManagementObject items in wmi.Get())
                    {
                        if ((Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) < Int32.Parse(cfg["checkmemory"]["minimum"]))
                        {
                            output += "--> [CheckMemory] Low physical memory: " + (Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) + " MB.\n";
                            alarms += 1;
                        }
                        else if (cfg["general"]["verbose"] == "true")
                        {
                            output += "[CheckMemory] Free physical memory: " + (Int32.Parse(items["FreePhysicalMemory"].ToString()) / 1000) + " MB.\n";
                        }
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckMemory] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkprocesses"))             // check processes
            {
                try
                {
                    wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
                    foreach (ManagementObject items in wmi.Get())
                    {
                        if (Int32.Parse(items["NumberOfProcesses"].ToString()) > Int32.Parse(cfg["checkprocesses"]["maximum"]))
                        {
                            output += "--> [CheckProcesses] There are too many processes running: " + items["NumberOfProcesses"] + ".\n";
                            alarms += 1;
                        }
                        else if (Int32.Parse(items["NumberOfProcesses"].ToString()) < Int32.Parse(cfg["checkprocesses"]["minimum"]))
                        {
                            output += "--> [CheckProcesses] There are too few processes running: " + items["NumberOfProcesses"] + ".\n";
                            alarms += 1;
                        }
                        else if (cfg["general"]["verbose"] == "true")
                        {
                            output += "[CheckProcesses] " + items["NumberOfProcesses"] + " processes are running.\n";
                        }
                    }
                    wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
                    foreach (string pp in cfg["checkprocesses"]["include"].Split(' '))
                    {
                        string p = pp.Trim();
                        if (p != "")
                        {
                            bool found = false;
                            foreach (ManagementObject items in wmi.Get())
                            {
                                if (string.Compare(items["Caption"].ToString().ToLower(), p) == 0)
                                {
                                    found = true;
                                }
                            }
                            if (!found)
                            {
                                output += "--> [CheckProcesses] Process in include list is not running: " + p + "\n";
                                alarms += 1;
                            }
                        }
                    }
                    wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
                    foreach (string pp in cfg["checkprocesses"]["exclude"].Split(' '))
                    {
                        string p = pp.Trim();
                        if (p != "")
                        {
                            bool found = false;
                            foreach (ManagementObject items in wmi.Get())
                            {
                                if (string.Compare(items["Caption"].ToString().ToLower(), p) == 0)
                                {
                                    found = true;
                                }
                            }
                            if (found)
                            {
                                output += "--> [CheckProcesses] Process in exclude list is running: " + p + "\n";
                                alarms += 1;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckProcesses] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkav"))             // check for an anti virus
            {
                try
                {
                    wmi = new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM AntivirusProduct");
                    ManagementObjectCollection instances = wmi.Get();
                    if (instances.Count == 0)
                    {
                        output += "--> [CheckAV] No anti virus product installed.\n";
                        alarms += 1;
                    }
                    else
                    {
                        foreach (ManagementObject items in instances)
                        {
                            if (string.Compare(items["displayName"].ToString().ToLower(), cfg["checkav"]["require"]) != 0)
                            {
                                output += "--> [CheckAV] Wrong anti virus product: " + items["displayName"] + "\n";
                                alarms += 1;
                            }
                            else if (cfg["general"]["verbose"] == "true")
                            {
                                output += "[CheckAV] " + items["displayName"] + "\n";
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckAV] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkdiskspace"))             // check disk space
            {
                try
                {
                    wmi = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_LogicalDisk");
                    foreach (ManagementObject items in wmi.Get())
                    {
                        if (items["FreeSpace"] != null && (cfg["checkdiskspace"]["onlysystemdisk"] != "true" || items["Caption"].ToString() == "C:"))
                        {
                            ulong freespace = (ulong)items["FreeSpace"] / 1000000;
                            if (freespace < UInt64.Parse(cfg["checkdiskspace"]["minimum"]) && freespace > 0)
                            {
                                output += "--> [CheckDiskSpace] Low free space on drive " + items["Caption"] + " " + freespace + " MB\n";
                                alarms += 1;
                            }
                            else if (cfg["general"]["verbose"] == "true")
                            {
                                output += "[CheckDiskSpace] Free space on drive " + items["Caption"] + " " + freespace + " MB\n";
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckDiskSpace] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkdomain"))             // check domnain joined
            {
                try
                {
                    string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
                    if (string.Compare(domain.ToLower(), cfg["checkdomain"]["domain"].ToLower()) != 0)
                    {
                        output += "--> [CheckDomain] System domain mismatch: " + domain + "\n";
                        alarms += 1;
                    }

                    else if (cfg["general"]["verbose"] == "true")
                    {
                        output += "[CheckDomain] System domain: " + domain + "\n";
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckDomain] Domain query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkupdates"))             // check Windows updates
            {
                try
                {
                    string[] WUstatus = new string[6] {
                        "Unknown", "Disabled", "Manual", "Manual", "Automatic", "Unknown"
                    };
                    rkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update");
                    string curWU = rkey.GetValue("AUOptions").ToString();
                    if (string.Compare(WUstatus[Int32.Parse(curWU)].ToLower(), cfg["checkupdates"]["status"]) != 0)
                    {
                        output += "--> [CheckUpdates] Windows Updates are set to: " + WUstatus[Int32.Parse(curWU)] + ".\n";
                        alarms += 1;
                    }
                    else if (cfg["general"]["verbose"] == "true")
                    {
                        output += "[CheckUpdates] Windows Updates are set to: " + WUstatus[Int32.Parse(curWU)] + ".\n";
                    }
                }
                catch (Exception e)
                {
                    if (output.ToLower().IndexOf("microsoft windows 10") != -1)                     // Windows 10 updates are on be default, the registry key doesn exist
                    {
                        output += "[CheckUpdates] Windows Updates are set to: Default\n";
                    }
                    else
                    {
                        output += "--> [CheckUpdates] Registry query failure: " + e + "\n";
                        alarms += 1;
                    }
                }
            }

            if (cfg.ContainsKey("checklusers"))             // check local users
            {
                try
                {
                    string localusers = "";
                    ManagementObjectSearcher   usersSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_UserAccount");
                    ManagementObjectCollection users         = usersSearcher.Get();
                    var lUsers = users.Cast <ManagementObject>().Where(u => (bool)u["LocalAccount"] == true && (bool)u["Disabled"] == false);
                    foreach (ManagementObject user in lUsers)
                    {
                        localusers += user["Caption"].ToString() + " ";
                    }
                    foreach (string pp in cfg["checklusers"]["include"].Split(' '))
                    {
                        string p       = pp.Trim();
                        string domainp = Environment.MachineName + "\\" + p;
                        domainp = domainp.ToLower();
                        if (p != "")
                        {
                            bool found = false;
                            foreach (string lu in localusers.Split(' '))
                            {
                                if (string.Compare(lu.ToLower(), p) == 0 || string.Compare(lu.ToLower(), domainp) == 0)
                                {
                                    found = true;
                                }
                            }
                            if (!found)
                            {
                                output += "--> [CheckLUsers] User in include list is not enabled: " + p + "\n";
                                alarms += 1;
                            }
                        }
                    }
                    foreach (string pp in cfg["checklusers"]["exclude"].Split(' '))
                    {
                        string p       = pp.Trim();
                        string domainp = Environment.MachineName + "\\" + p;
                        domainp = domainp.ToLower();
                        if (p != "")
                        {
                            bool found = false;
                            foreach (string lu in localusers.Split(' '))
                            {
                                if (string.Compare(lu.ToLower(), p) == 0 || string.Compare(lu.ToLower(), domainp) == 0)
                                {
                                    found = true;
                                }
                            }
                            if (found)
                            {
                                output += "--> [CheckLUsers] User in exclude list is enabled: " + p + "\n";
                                alarms += 1;
                            }
                        }
                    }
                    if (cfg["general"]["verbose"] == "true")
                    {
                        output += "[CheckLUsers] Local users: " + localusers + "\n";
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckLUsers] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checkfirewall"))             // check firewall
            {
                try
                {
                    string firewallresults = "";
                    rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\PublicProfile");
                    if ((int)rkey.GetValue("EnableFirewall") != 1)
                    {
                        if (cfg["checkfirewall"]["require"].IndexOf("public") != -1)
                        {
                            output += "--> [CheckFirewall] Public firewall is OFF\n";
                            alarms += 1;
                        }
                        firewallresults += "Public: OFF  ";
                    }
                    else
                    {
                        firewallresults += "Public: ON  ";
                    }
                    rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile");
                    if ((int)rkey.GetValue("EnableFirewall") != 1)
                    {
                        if (cfg["checkfirewall"]["require"].IndexOf("private") != -1)
                        {
                            output += "--> [CheckFirewall] Private firewall is OFF\n";
                            alarms += 1;
                        }
                        firewallresults += "Private: OFF  ";
                    }
                    else
                    {
                        firewallresults += "Private: ON  ";
                    }
                    rkey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile");
                    if ((int)rkey.GetValue("EnableFirewall") != 1)
                    {
                        if (cfg["checkfirewall"]["require"].IndexOf("domain") != -1)
                        {
                            output += "--> [CheckFirewall] Domain firewall is OFF\n";
                            alarms += 1;
                        }
                        firewallresults += "Domain: OFF  ";
                    }
                    else
                    {
                        firewallresults += "Domain: ON  ";
                    }
                    if (cfg["general"]["verbose"] == "true")
                    {
                        output += "[CheckFirewall] " + firewallresults + "\n";
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckLUsers] WMI Query failure: " + e + "\n";
                    alarms += 1;
                }
            }

            if (cfg.ContainsKey("checknetwork"))             // check network connection
            {
                try
                {
                    Ping      ping  = new Ping();
                    PingReply reply = ping.Send(cfg["checknetwork"]["host"], 4000);
                    if (reply.Status != IPStatus.Success)
                    {
                        output += "--> [CheckNetwork] Host " + cfg["checknetwork"]["host"] + " is not reachable.\n";
                        alarms += 1;
                    }
                    else
                    {
                        if (reply.RoundtripTime > Int32.Parse(cfg["checknetwork"]["latency"]))
                        {
                            output += "--> [CheckNetwork] High network latency: " + reply.RoundtripTime + "ms.\n";
                            alarms += 1;
                        }
                        else if (cfg["general"]["verbose"] == "true")
                        {
                            output += "[CheckNetwork] Latency: " + reply.RoundtripTime + " ms.\n";
                        }
                    }
                }
                catch (Exception e)
                {
                    output += "--> [CheckNetwork] Ping failure: " + e + "\n";
                    alarms += 1;
                }
            }

            // Notifications
            if (alarms > 1)
            {
                output += "\nChecks completed with " + alarms.ToString() + " alarms raised.\n";
            }
            else
            {
                output += "\nChecks completed with " + alarms.ToString() + " alarm raised.\n";
            }

            try
            {
                wc       = new WebClient();
                wc.Proxy = wp;
                wc.QueryString.Add("alarms", alarms.ToString());
                wc.QueryString.Add("cpu", curval.ToString());
                wc.QueryString.Add("name", Environment.MachineName);
                wc.QueryString.Add("interval", cfg["general"]["interval"]);
                wc.QueryString.Add("template", cfg["general"]["template"]);
                wc.QueryString.Add("output", output);
                string result = wc.DownloadString(cfg["general"]["dashboard"]);
                if (result.ToLower().IndexOf("[general]") != -1)
                {
                    if (cfg["general"]["debug"] == "true")
                    {
                        EventLog.WriteEntry("Healthstone", "Dashboard template provided: " + result, EventLogEntryType.Information);
                    }
                    ParseNewCfg(result);
                }
                else
                {
                    EventLog.WriteEntry("Healthstone", "Unknown reply from dashboard: " + result, EventLogEntryType.Error);
                }
            }
            catch (Exception e)
            {
                EventLog.WriteEntry("Healthstone", "Healthstone dashboard [" + cfg["general"]["dashboard"] + "] could not be contacted: " + e, EventLogEntryType.Error);
            }

            if (alarms > 0)
            {
                EventLog.WriteEntry("Healthstone", output, EventLogEntryType.Warning);
            }
            else
            {
                EventLog.WriteEntry("Healthstone", output, EventLogEntryType.Information);
            }

            hstimer.Interval = Int32.Parse(cfg["general"]["interval"]) * 1000;
            hstimer.Start();
        }
Exemplo n.º 6
0
        private void UpdateData()
        {
            string s = sd.GetProcessorData();

            labelCpu.Text = s;
            double d = double.Parse(s.Substring(0, s.IndexOf("%")));

            dataBarCPU.Value = (int)d;

            dataChartCPU.UpdateChart(d);
            cpu = (int)d;

            s = sd.GetMemoryVData();
            labelMemV.Text = s;
            d = double.Parse(s.Substring(0, s.IndexOf("%")));
            dataBarMemV.Value = (int)d;
            dataChartMem.UpdateChart(d);
            mem_v = (int)d;

            s = sd.GetMemoryPData();
            labelMemP.Text = s;
            d = double.Parse(s.Substring(0, s.IndexOf("%")));
            dataBarMemP.Value = (int)d;
            mem_p             = (int)d;

            d = sd.GetDiskData(SystemData.DiskData.Read);
            labelDiskR.Text = "Disk R (" + sd.FormatBytes(d) + "/s)";
            dataChartDiskR.UpdateChart(d);
            disk_r = (int)(d / 1024);

            d = sd.GetDiskData(SystemData.DiskData.Write);
            labelDiskW.Text = "Disk W (" + sd.FormatBytes(d) + "/s)";
            dataChartDiskW.UpdateChart(d);
            disk_w = (int)(d / 1024);

            d = sd.GetNetData(SystemData.NetData.Received);
            labelNetI.Text = "Net I (" + sd.FormatBytes(d) + "/s)";
            dataChartNetI.UpdateChart(d);
            net_i = (int)(d / 1024);

            d = sd.GetNetData(SystemData.NetData.Sent);
            labelNetO.Text = "Net O (" + sd.FormatBytes(d) + "/s)";
            dataChartNetO.UpdateChart(d);
            net_o = (int)(d / 1024);

            label12.Text = HardwareInfo.GetCPUCurrentClockSpeed().ToString();

            count = 0;
            ManagementObjectSearcher   usersSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_UserAccount");
            ManagementObjectCollection users         = usersSearcher.Get();

            var localUsers = users.Cast <ManagementObject>().Where(
                u => (bool)u["LocalAccount"] == true &&
                (bool)u["Disabled"] == false &&
                (bool)u["Lockout"] == false &&
                int.Parse(u["SIDType"].ToString()) == 1 &&
                u["Name"].ToString() != "HomeGroupUser$");

            foreach (ManagementObject user in users)
            {
                Console.WriteLine("Name: " + user["Name"].ToString());
                count++;
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Gets command line of specific process.
 /// </summary>
 /// <param name="processId">process id</param>
 /// <returns>null if not accessible (e.g. executed with admin priviledges)</returns>
 public static string GetProcessCommandLine(int processId)
 {
     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + processId))
         using (ManagementObjectCollection objects = searcher.Get())
             return(objects.Cast <ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString());
 }