public static List <RemoteApplication> GetInstalledApplications()
        {
            var apps       = new List <RemoteApplication>();
            var taskResult = new TaskResult();

            Result = taskResult;

            const string uninstallKey       = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const string uninstallKey32on64 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

            var managementScope            = new ManagementScope($@"\\{ComputerName}\root\CIMV2");
            ManagementBaseObject inParams  = null;
            ManagementBaseObject outParams = null;

            try
            {
                using (var wmiRegistry = new ManagementClass(managementScope, new ManagementPath("StdRegProv"), null))
                {
                    List <string> subKeys       = null;
                    List <string> subKeys32on64 = null;
                    var           uninstallKeys = new List <string>();

                    // Get uninstall subkeys.
                    inParams = wmiRegistry.GetMethodParameters("EnumKey");
                    inParams["sSubKeyName"] = uninstallKey;
                    outParams = wmiRegistry.InvokeMethod("EnumKey", inParams, null);
                    if (outParams["sNames"] != null)
                    {
                        subKeys = new List <string>((string[])outParams["sNames"]).Select(x => $@"{uninstallKey}\{x}").ToList();
                    }

                    // Get 32-bit on 64-bit uninstall subkeys.
                    inParams["sSubKeyName"] = uninstallKey32on64;
                    outParams = wmiRegistry.InvokeMethod("EnumKey", inParams, null);
                    if (outParams["sNames"] != null)
                    {
                        subKeys32on64 = new List <string>((string[])outParams["sNames"]).Select(x => $@"{uninstallKey32on64}\{x}").ToList();
                    }

                    // Combine lists of keys.
                    if (subKeys != null)
                    {
                        uninstallKeys.AddRange(subKeys);
                    }
                    if (subKeys32on64 != null)
                    {
                        uninstallKeys.AddRange(subKeys32on64);
                    }

                    // Enumerate keys.
                    foreach (string subKey in uninstallKeys)
                    {
                        // Get SystemComponent (DWORD) value.  Skip key if this value exists and is set to '1'.
                        inParams = wmiRegistry.GetMethodParameters("GetDWORDValue");
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "SystemComponent";
                        outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                        if (outParams["uValue"] != null && (UInt32)outParams["uValue"] == 1)
                        {
                            continue;
                        }

                        // Get ParentKeyName (String) value.  Skip key if this value exists.
                        inParams = wmiRegistry.GetMethodParameters("GetStringValue");
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "ParentKeyName";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null && ((string)outParams["sValue"]).Length > 0)
                        {
                            continue;
                        }

                        // Get ReleaseType (String) value.  Skip key if this value contains 'Update' or 'Hotfix'.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "ReleaseType";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null && (((string)outParams["sValue"]).Contains("Update") || ((string)outParams["sValue"]).Equals("Hotfix")))
                        {
                            continue;
                        }

                        var app = new RemoteApplication();

                        // Get DisplayName (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "DisplayName";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.DisplayName = (string)outParams["sValue"];
                        }
                        else
                        {
                            continue;
                        }

                        // Get Publisher (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "Publisher";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.Publisher = (string)outParams["sValue"];
                        }

                        // Get DisplayVersion (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "DisplayVersion";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.Version = (string)outParams["sValue"];
                        }

                        // Get UninstallString (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "UninstallString";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.UninstallPath = (string)outParams["sValue"];
                        }

                        apps.Add(app);
                    }
                }

                taskResult.DidTaskSucceed = true;
            }

            catch (ManagementException ex) when(ex.ErrorCode == ManagementStatus.NotFound)
            {
                // Target OS might not support WMI StdRegProv.  Attempt to gather data using remote registry.
                apps = new List <RemoteApplication>();
                const string serviceName      = "RemoteRegistry";
                bool         isLocal          = ComputerName.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
                bool         isServiceRunning = true;

                // If the target computer is remote, then start the Remote Registry service.
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (var sc = new ServiceController(serviceName, ComputerName))
                    {
                        try
                        {
                            if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                            {
                                isServiceRunning = false;
                                sc.Start();
                            }
                        }
                        catch (Exception)
                        {
                        }

                        try
                        {
                            using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName))
                            {
                                using (RegistryKey mainKey64 = key.OpenSubKey(uninstallKey))
                                    apps.AddRange(EnumerateUninstallKeys(mainKey64));
                                using (RegistryKey mainKey32 = key.OpenSubKey(uninstallKey32on64))
                                    apps.AddRange(EnumerateUninstallKeys(mainKey32));
                            }

                            taskResult.DidTaskSucceed = true;
                        }
                        catch
                        {
                            taskResult.DidTaskSucceed = false;
                        }


                        // Cleanup.
                        if (!isLocal && !isServiceRunning)
                        {
                            try
                            {
                                if (sc != null)
                                {
                                    sc.Stop();
                                }
                            }

                            catch (Exception)
                            {
                            }
                        }
                    }
            }

            catch
            {
                // Do nothing.
            }

            finally
            {
                if (inParams != null)
                {
                    inParams.Dispose();
                }
                if (outParams != null)
                {
                    outParams.Dispose();
                }
            }

            // Get Internet Explorer version.
            if (taskResult.DidTaskSucceed && apps.Count > 0)
            {
                try
                {
                    var internetExplorerVersion = FileVersionInfo.GetVersionInfo($@"\\{ComputerName}\C$\Program Files\Internet Explorer\iexplore.exe");
                    if (internetExplorerVersion != null && internetExplorerVersion.ProductVersion.Length > 0)
                    {
                        apps.Add(new RemoteApplication
                        {
                            DisplayName = "Internet Explorer",
                            Publisher   = "Microsoft Corporation",
                            Version     = internetExplorerVersion.ProductVersion
                        });
                    }
                }
                catch { }
            }

            return(apps);
        }
        public static RemoteSystemInfo GetSystemInfo()
        {
            var systemInfo = new RemoteSystemInfo();
            var taskResult = new TaskResult();

            systemInfo.Result = taskResult;

            ConnectionOptions op = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                op.Username  = GlobalVar.AlternateUsername;
                op.Password  = GlobalVar.AlternatePassword;
                op.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            ManagementScope          sc       = new ManagementScope($@"\\{TargetComputer}\root\CIMV2", op);
            ObjectQuery              query    = new ObjectQuery("SELECT Caption,Description,LastBootUpTime,Version,ProductType FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);

            try
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    systemInfo.ComputerType         = (obj["ProductType"] != null) ? obj["ProductType"].ToString() : string.Empty;
                    systemInfo.WindowsVersionNumber = (obj["Version"] != null) ? obj["Version"].ToString().Trim() : string.Empty;
                    systemInfo.WindowsVersion       = (obj["Caption"] != null) ? obj["Caption"].ToString().Trim() : string.Empty;
                    systemInfo.ComputerDescription  = (obj["Description"] != null) ? obj["Description"].ToString().Trim() : string.Empty;
                    int index = systemInfo.WindowsVersion.IndexOf(@"(R)", StringComparison.OrdinalIgnoreCase);
                    while (index >= 0)
                    {
                        systemInfo.WindowsVersion = systemInfo.WindowsVersion.Remove(index, @"(R)".Length);
                        index = systemInfo.WindowsVersion.IndexOf(@"(R)", StringComparison.OrdinalIgnoreCase);
                    }
                    index = systemInfo.WindowsVersion.IndexOf(@"®", StringComparison.OrdinalIgnoreCase);
                    while (index >= 0)
                    {
                        systemInfo.WindowsVersion = systemInfo.WindowsVersion.Remove(index, @"®".Length);
                        index = systemInfo.WindowsVersion.IndexOf(@"®", StringComparison.OrdinalIgnoreCase);
                    }

                    if (obj["LastBootUpTime"] != null)
                    {
                        DateTime lastBoot = ManagementDateTimeConverter.ToDateTime(obj["LastBootUpTime"].ToString());
                        TimeSpan ts       = DateTime.Now - lastBoot;
                        string   uptime;
                        if (ts.Days > 0)
                        {
                            uptime = string.Format("{0} day{1}, {2} hour{3}, {4} minute{5}",
                                                   ts.Days, ts.Days == 1 ? "" : "s",
                                                   ts.Hours, ts.Hours == 1 ? "" : "s",
                                                   ts.Minutes, ts.Minutes == 1 ? "" : "s");
                        }
                        else if (ts.Hours > 0)
                        {
                            uptime = string.Format("{0} hour{1}, {2} minute{3}",
                                                   ts.Hours, ts.Hours == 1 ? "" : "s",
                                                   ts.Minutes, ts.Minutes == 1 ? "" : "s");
                        }
                        else if (ts.Minutes > 0)
                        {
                            uptime = string.Format("{0} minute{1}",
                                                   ts.Minutes, ts.Minutes == 1 ? "" : "s");
                        }
                        else
                        {
                            uptime = string.Format("{0} second{1}",
                                                   ts.Seconds, ts.Seconds == 1 ? "" : "s");
                        }
                        systemInfo.Uptime = uptime;
                    }

                    //foreach (var prop in obj.Properties)
                    //{
                    //    if (prop.Name == "OSArchitecture" && obj["OSArchitecture"] != null)
                    //        systemInfo.WindowsArchitecture = obj["OSArchitecture"].ToString();
                    //}
                }

                //if (systemInfo.WindowsArchitecture == null)
                //{
                WindowsArchitecture = "32-bit";
                query    = new ObjectQuery("SELECT Name,VariableValue FROM Win32_Environment");
                searcher = new ManagementObjectSearcher(sc, query);

                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["Name"] != null && obj["Name"].ToString() == "PROCESSOR_ARCHITECTURE" && obj["VariableValue"] != null && obj["VariableValue"].ToString().ToUpper() == "AMD64")
                    {
                        WindowsArchitecture = "64-bit";
                        break;
                    }
                    else if (obj["Name"] != null && obj["Name"].ToString() == "PROCESSOR_ARCHITEW6432 " && obj["VariableValue"] != null && obj["VariableValue"].ToString().ToUpper() == "AMD64")
                    {
                        WindowsArchitecture = "64-bit";
                        break;
                    }
                }
                //}


                if (systemInfo.WindowsVersionNumber.StartsWith("5.0") || systemInfo.WindowsVersionNumber.StartsWith("5.2"))
                {
                    query = new ObjectQuery("SELECT CurrentClockSpeed FROM Win32_Processor");
                }
                else
                {
                    query = new ObjectQuery("SELECT CurrentClockSpeed,NumberOfLogicalProcessors FROM Win32_Processor");
                }
                searcher = new ManagementObjectSearcher(sc, query);
                UInt32 clockSpeed            = 0;
                UInt32 numberOfProcessors    = 1;
                bool   isLogicalCpuSupported = false;
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["CurrentClockSpeed"] != null)
                    {
                        clockSpeed = (UInt32)obj["CurrentClockSpeed"];
                    }
                    if (systemInfo.WindowsVersionNumber.StartsWith("5.0") || systemInfo.WindowsVersionNumber.StartsWith("5.2"))
                    {
                        break;
                    }
                    else if (obj["NumberOfLogicalProcessors"] != null)
                    {
                        isLogicalCpuSupported = true;
                    }
                    //foreach (var prop in obj.Properties)
                    //{
                    //    if (prop.Name == "NumberOfLogicalProcessors" && obj["NumberOfLogicalProcessors"] != null)
                    //    {
                    //        isLogicalCpuSupported = true;
                    //        break;
                    //    }
                    //}
                    break;
                }


                if (isLogicalCpuSupported == true)
                {
                    query = new ObjectQuery("SELECT Manufacturer,Model,Name,NumberOfLogicalProcessors,NumberOfProcessors FROM Win32_ComputerSystem");
                }
                else
                {
                    query = new ObjectQuery("SELECT Manufacturer,Model,Name,NumberOfProcessors FROM Win32_ComputerSystem");
                }
                searcher = new ManagementObjectSearcher(sc, query);
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["Manufacturer"] != null)
                    {
                        systemInfo.ComputerManufacturer = obj["Manufacturer"].ToString();
                    }
                    if (obj["Model"] != null)
                    {
                        systemInfo.ComputerModel = obj["Model"].ToString();
                    }
                    if (obj["Name"] != null)
                    {
                        systemInfo.ComputerName = obj["Name"].ToString();
                    }
                    if (isLogicalCpuSupported == true && obj["NumberOfLogicalProcessors"] != null)
                    {
                        numberOfProcessors = (UInt32)obj["NumberOfLogicalProcessors"];
                    }
                    else if (isLogicalCpuSupported == false && obj["NumberOfProcessors"] != null)
                    {
                        numberOfProcessors = (UInt32)obj["NumberOfProcessors"];
                    }
                    else
                    {
                        numberOfProcessors = 1;
                    }
                }
                systemInfo.Processor = string.Format("{0} Core{1} @ {2:0.#} {3}",
                                                     numberOfProcessors, numberOfProcessors == 1 ? "" : "s",
                                                     clockSpeed > 1000 ? (double)clockSpeed / 1000.0 : clockSpeed,
                                                     clockSpeed > 1000 ? "GHz" : "MHz");


                query    = new ObjectQuery("SELECT SerialNumber FROM Win32_SystemEnclosure");
                searcher = new ManagementObjectSearcher(sc, query);
                foreach (ManagementObject obj in searcher.Get())
                {
                    systemInfo.ComputerSerialNumber = (obj["SerialNumber"] != null) ? obj["SerialNumber"].ToString() : string.Empty;
                    break;
                }


                query    = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
                searcher = new ManagementObjectSearcher(sc, query);
                UInt64 totalMemory = 0;
                foreach (ManagementObject m in searcher.Get())
                {
                    if (m["Capacity"] != null)
                    {
                        totalMemory += (UInt64)m["Capacity"];
                    }
                }
                systemInfo.Memory = RemoteAdmin.ConvertBytesToString(totalMemory);


                // Determine computer type:
                if (!string.IsNullOrEmpty(systemInfo.ComputerType) && systemInfo.ComputerType == "3")
                {
                    systemInfo.ComputerType = "Server";
                }
                else
                {
                    systemInfo.ComputerType = "Desktop";
                }

                if (systemInfo.ComputerManufacturer == "VMware, Inc." || (systemInfo.ComputerManufacturer == "Xen" && systemInfo.ComputerModel == "HVM domU"))
                {
                    if (systemInfo.ComputerType == "Server")
                    {
                        systemInfo.ComputerType = "Server (Virtual Machine)";
                    }
                    else
                    {
                        systemInfo.ComputerType = "Virtual Machine";
                    }
                }
                query    = new ObjectQuery("SELECT BatteryStatus FROM Win32_Battery");
                searcher = new ManagementObjectSearcher(sc, query);
                foreach (ManagementObject m in searcher.Get())
                {
                    systemInfo.ComputerType = "Laptop / Portable";
                    break;
                }

                taskResult.DidTaskSucceed = true;



                query    = new ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True");
                searcher = new ManagementObjectSearcher(sc, query);
                foreach (ManagementObject obj in searcher.Get())
                {
                    string[] ipAddresses = (string[])(obj["IPAddress"]);
                    systemInfo.IpAddresses = ipAddresses.FirstOrDefault(s => s.Contains('.'));
                }
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
            }

            systemInfo.IsRebootRequired = GetSysRebootState();

            return(systemInfo);
        }
Esempio n. 3
0
        public static List <RemoteProcess> GetProcesses()
        {
            // GetProcesses() uses WMI to retrieve a list of running processes.
            // It returns a List of RemoteProcess which will be bound to a DataGrid on this UserControl.
            var processes  = new List <RemoteProcess>();
            var taskResult = new TaskResult();

            Result = taskResult;

            // Setup WMI Query.
            var options = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                options.Username  = GlobalVar.AlternateUsername;
                options.Password  = GlobalVar.AlternatePassword;
                options.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            var scope    = new ManagementScope($@"\\{ComputerName}\root\CIMV2", options);
            var query    = new ObjectQuery("SELECT * FROM Win32_Process");
            var searcher = new ManagementObjectSearcher(scope, query);

            try
            {
                // Retrieve a list of running processes.
                foreach (ManagementObject m in searcher.Get())
                {
                    var process = new RemoteProcess();

                    process.Name           = (m["Name"] != null) ? m["Name"].ToString() : string.Empty;
                    process.ExecutablePath = (m["ExecutablePath"] != null) ? m["ExecutablePath"].ToString() : string.Empty;
                    if (m["ProcessId"] != null)
                    {
                        process.ProcessId = (UInt32)m["ProcessId"];
                    }
                    if (m["SessionId"] != null)
                    {
                        process.SessionId = (UInt32)m["SessionId"];
                    }

                    string[] argList   = new string[] { string.Empty, string.Empty };
                    int      returnVal = Convert.ToInt32(m.InvokeMethod("GetOwner", argList));
                    process.Owner = (returnVal == 0) ? argList[0] : string.Empty;

                    if (process.ProcessId == 0 || process.ProcessId == 4)
                    {
                        process.Owner = "SYSTEM";
                    }

                    switch (process.Owner.ToUpper())
                    {
                    case ("SYSTEM"):
                        process.Owner = "System";
                        break;

                    case ("LOCAL SERVICE"):
                        process.Owner = "Local Service";
                        break;

                    case ("NETWORK SERVICE"):
                        process.Owner = "Network Service";
                        break;
                    }

                    processes.Add(process);
                }
                taskResult.DidTaskSucceed = true;
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
            }

            return(processes);
        }
Esempio n. 4
0
        public static List <RemoteLogonSession> GetLogonSessions()
        {
            // GetProcesses() first uses WMI to determine if the target computer is running a desktop or server OS.
            // If running a server OS, it uses the Remote Desktop Service API to retrieve logon sessions.
            // If running a desktop OS, it uses WMI to retrieve logon sessions.
            // It returns a List of RemoteLogonSession which will be bound to a DataGrid on this UserControl.

            var logonSessions = new List <RemoteLogonSession>();
            var taskResult    = new TaskResult();

            Result = taskResult;
            UInt32 productType = 1;

            // Determine whether operating system is server or desktop edition.
            var options = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                options.Username  = GlobalVar.AlternateUsername;
                options.Password  = GlobalVar.AlternatePassword;
                options.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            var scope    = new ManagementScope($@"\\{ComputerName}\root\CIMV2", options);
            var query    = new ObjectQuery("SELECT ProductType FROM Win32_OperatingSystem");
            var searcher = new ManagementObjectSearcher(scope, query);

            try
            {
                foreach (ManagementObject m in searcher.Get())
                {
                    productType = (m["ProductType"] != null) ? (UInt32)m["ProductType"] : 1;
                    break;
                }
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
                return(logonSessions);
            }
            IsServerEdition = productType > 1 ? true : false;

            // If operating system is server edition, use Remote Desktop Services API to retrieve logon sessions.
            if (IsServerEdition)
            {
                try
                {
                    using (
                        GlobalVar.UseAlternateCredentials
                        ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                        : null)
                    {
                        IntPtr server = WtsApi.WTSOpenServer(ComputerName);
                        logonSessions.AddRange(WtsApi.GetWindowsUsers(server));

                        foreach (RemoteLogonSession logonSession in logonSessions)
                        {
                            query    = new ObjectQuery($"SELECT CreationDate FROM Win32_Process WHERE SessionId = {logonSession.SessionId}");
                            searcher = new ManagementObjectSearcher(scope, query);
                            DateTime logonTime = DateTime.Now;
                            foreach (ManagementObject m in searcher.Get())
                            {
                                DateTime procCreationDate = ManagementDateTimeConverter.ToDateTime(m["CreationDate"].ToString());
                                if (procCreationDate < logonTime)
                                {
                                    logonSession.LogonTime = procCreationDate;
                                }
                            }
                        }
                    }
                    taskResult.DidTaskSucceed = true;
                }
                catch
                {
                    taskResult.DidTaskSucceed = false;
                }
            }
            // If operating system is desktop edition, query Win32_Process for explorer.exe to determine logged on users.
            else
            {
                query    = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");
                searcher = new ManagementObjectSearcher(scope, query);

                try
                {
                    foreach (ManagementObject m in searcher.Get())
                    {
                        var logonSession = new RemoteLogonSession();
                        logonSession.SessionId = (UInt32)m["SessionId"];
                        var dmtfDateTime = m["CreationDate"].ToString();
                        logonSession.LogonTime = ManagementDateTimeConverter.ToDateTime(dmtfDateTime);

                        string[] argList   = new string[] { string.Empty, string.Empty };
                        int      returnVal = Convert.ToInt32(m.InvokeMethod("GetOwner", argList));
                        if (returnVal == 0)
                        {
                            logonSession.Username = argList[0];
                            logonSession.Domain   = argList[1];
                        }
                        else
                        {
                            logonSession.Username = string.Empty;
                        }

                        int index = logonSessions.FindIndex(item => item.SessionId == logonSession.SessionId);
                        if (index >= 0)
                        {
                            continue;
                        }
                        else
                        {
                            logonSessions.Add(logonSession);
                        }
                    }
                    taskResult.DidTaskSucceed = true;
                }
                catch
                {
                    taskResult.DidTaskSucceed = false;
                }
            }

            return(logonSessions);
        }
Esempio n. 5
0
        public static List <RemoteService> GetServices()
        {
            // GetServices() uses WMI to retrieve a list of running services.
            // It returns a List of RemoteService which will be bound to a DataGrid on this UserControl.
            var services   = new List <RemoteService>();
            var taskResult = new TaskResult();

            Result = taskResult;

            // Setup WMI query.
            var options = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                options.Username  = GlobalVar.AlternateUsername;
                options.Password  = GlobalVar.AlternatePassword;
                options.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            var scope    = new ManagementScope($@"\\{ComputerName}\root\CIMV2", options);
            var query    = new ObjectQuery("SELECT * FROM Win32_Service");
            var searcher = new ManagementObjectSearcher(scope, query);

            try
            {
                // Retrieve a list of running services.
                foreach (ManagementObject m in searcher.Get())
                {
                    var service = new RemoteService();

                    service.DisplayName = (m["DisplayName"] != null) ? m["DisplayName"].ToString() : string.Empty;
                    service.AcceptPause = (m["AcceptPause"] != null) ? (bool)m["AcceptPause"] : false;
                    service.AcceptStop  = (m["AcceptStop"] != null) ? (bool)m["AcceptStop"] : false;
                    service.Description = (m["Description"] != null) ? m["Description"].ToString() : string.Empty;
                    service.Name        = (m["Name"] != null) ? m["Name"].ToString() : string.Empty;
                    service.PathName    = (m["PathName"] != null) ? m["PathName"].ToString() : string.Empty;
                    service.StartupType = (m["StartMode"] != null) ? m["StartMode"].ToString() : string.Empty;
                    service.LogOnAs     = (m["StartName"] != null) ? m["StartName"].ToString() : string.Empty;
                    service.State       = (m["State"] != null) ? m["State"].ToString() : string.Empty;

                    int index = service.LogOnAs.IndexOf(@"NT AUTHORITY\", StringComparison.OrdinalIgnoreCase);
                    if (index >= 0)
                    {
                        service.LogOnAs = service.LogOnAs.Remove(index, @"NT AUTHORITY\".Length);
                    }

                    switch (service.LogOnAs.ToUpper())
                    {
                    case ("LOCALSERVICE"):
                        service.LogOnAs = "Local Service";
                        break;

                    case ("LOCALSYSTEM"):
                        service.LogOnAs = "Local System";
                        break;

                    case ("NETWORKSERVICE"):
                        service.LogOnAs = "Network Service";
                        break;
                    }

                    services.Add(service);
                }
                taskResult.DidTaskSucceed = true;
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
            }

            return(services);
        }
Esempio n. 6
0
        public static List <RemoteStorage> GetStorageDevices()
        {
            // Use WMI to retrieve a list of storage devices.
            var drives     = new List <RemoteStorage>();
            var taskResult = new TaskResult();

            Result = taskResult;

            // Setup WMI query.
            var options = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                options.Username  = GlobalVar.AlternateUsername;
                options.Password  = GlobalVar.AlternatePassword;
                options.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            var scope    = new ManagementScope($@"\\{ComputerName}\root\CIMV2", options);
            var query    = new ObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 2 OR DriveType = 3 OR DriveType = 5");
            var searcher = new ManagementObjectSearcher(scope, query);

            try
            {
                // Retrieve a list of storage devices.
                foreach (ManagementObject m in searcher.Get())
                {
                    var drive = new RemoteStorage();

                    drive.DriveLetter = (m["Name"] != null) ? m["Name"].ToString() : string.Empty;
                    drive.VolumeName  = (m["VolumeName"] != null) ? m["VolumeName"].ToString() : string.Empty;
                    drive.Capacity    = (m["Size"] != null) ? (UInt64)m["Size"] : 0;
                    drive.FreeSpace   = (m["FreeSpace"] != null) ? (UInt64)m["FreeSpace"] : 0;
                    drive.UsedSpace   = drive.Capacity - drive.FreeSpace;
                    drive.DriveType   = (UInt32)m["DriveType"];

                    double bytes = (double)drive.Capacity;
                    switch (drive.DriveType)
                    {
                    case (2):
                        drive.CapacityString = "Removable";
                        break;

                    case (5):
                        drive.CapacityString = "CD-ROM";
                        break;

                    default:
                        drive.CapacityString = ConvertBytesToString(bytes);
                        break;
                    }

                    bytes = (double)drive.FreeSpace;
                    drive.FreeSpaceString = (drive.DriveType == 2 || drive.DriveType == 5) ? string.Empty : ConvertBytesToString(bytes);

                    bytes = (double)drive.UsedSpace;
                    drive.UsedSpaceString = (drive.DriveType == 2 || drive.DriveType == 5) ? string.Empty : ConvertBytesToString(bytes);

                    drives.Add(drive);
                }
                taskResult.DidTaskSucceed = true;
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
            }

            return(drives);
        }
        public static List <RemoteLogonHistory> GetLogonHistory()
        {
            var logonHistory = new List <RemoteLogonHistory>();

            Result = new TaskResult();

            const int logonEventId   = 4624;
            const int logoffEventIdA = 4634;
            const int logoffEventIdB = 4647;
            const int landeskRemoteControlEventId = 2;

            string queryString =
                "<QueryList><Query Id='1'>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='LogonGuid'] != '{00000000-0000-0000-0000-000000000000}']] and " +
                "*[EventData[Data[@Name='LogonProcessName'] != 'seclogo']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='TargetDomainName'] = '" + RemoteLogonSession.ComputerName.ToUpper().Trim() + "']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                //"*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                //"(EventID=" + logoffEventIdA + ")]] and " +
                //"*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] or " +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logoffEventIdB + ")]]" +
                "</Select>" +
                "<Select Path='Application'>" +
                "*[System[Provider[@Name='LANDESK Remote Control Service'] and (EventID=" + landeskRemoteControlEventId + ")]]" +
                "</Select>" +
                "</Query></QueryList>";

            try
            {
                var eventLogSession = new EventLogSession(RemoteLogonSession.ComputerName);
                var eventLogQuery   = new EventLogQuery("Security", PathType.LogName, queryString);
                eventLogQuery.ReverseDirection = true;
                eventLogQuery.Session          = eventLogSession;

                using (
                    GlobalVar.UseAlternateCredentials
                        ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                        : null)
                    using (var eventLogReader = new EventLogReader(eventLogQuery))
                    {
                        for (EventRecord eventLogRecord = eventLogReader.ReadEvent(); null != eventLogRecord; eventLogRecord = eventLogReader.ReadEvent())
                        {
                            string regexString;

                            switch (eventLogRecord.Id)
                            {
                            case (logonEventId):
                                regexString = @"An account was successfully logged on.*Logon Type:\s+(?<logonType>.*?)\r" +
                                              @".*\tAccount Name:\s+(?<accountName>.*?)\r" +
                                              @".*\tAccount Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Network Information:.*Source Network Address:\s+(?<sourceIpAddress>.*?)\r";
                                break;

                            case (landeskRemoteControlEventId):
                                regexString = @"^Remote control action: (?<controlAction>\w+?) Remote Control  Initiated from (?<sourceHostname>.*?) by user " +
                                              @"(?<accountName>.*?), Security Type";
                                break;

                            case (logoffEventIdA):
                                regexString = @"An account was logged off" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Logon Type:\s+(?<logonType>.*?)\r";
                                break;

                            case (logoffEventIdB):
                                regexString = @"User initiated logoff" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r";
                                break;

                            default:
                                regexString = string.Empty;
                                break;
                            }
                            var match = Regex.Match(eventLogRecord.FormatDescription(), regexString, RegexOptions.Singleline);

                            if (match.Success)
                            {
                                switch (eventLogRecord.Id)
                                {
                                case (logonEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = match.Groups["logonType"].Value,
                                        IpAddress   = match.Groups["sourceIpAddress"].Value
                                    });
                                    break;

                                case (landeskRemoteControlEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonDomain = string.Empty,
                                        LogonType   = "LANDesk",
                                        LogonAction = match.Groups["controlAction"].Value,
                                        IpAddress   = match.Groups["sourceHostname"].Value
                                    });
                                    break;

                                case (logoffEventIdA):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;

                                case (logoffEventIdB):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;
                                }
                            }
                        }

                        Result.DidTaskSucceed = true;
                    }
            }
            catch (UnauthorizedAccessException)
            {
                Result.DidTaskSucceed = false;
                Result.MessageBody    = "This feature is currently only supported on Windows Vista and Server 2008 or higher.";
            }
            catch
            {
                Result.DidTaskSucceed = false;
            }

            return(logonHistory);
        }
        public static List <RemoteApplication> GetInstalledApplications()
        {
            var apps       = new List <RemoteApplication>();
            var taskResult = new TaskResult();

            Result = taskResult;

            const string uninstallKey64   = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const string uninstallKey32   = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            const string serviceName      = "RemoteRegistry";
            bool         isLocal          = ComputerName.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
            bool         isServiceRunning = true;

            // If the target computer is remote, then start the Remote Registry service.
            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(serviceName, ComputerName))
                {
                    try
                    {
                        if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                        {
                            isServiceRunning = false;
                            sc.Start();
                        }
                    }
                    catch (Exception)
                    {
                    }

                    try
                    {
                        using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName))
                        {
                            using (RegistryKey mainKey64 = key.OpenSubKey(uninstallKey64))
                                apps.AddRange(EnumerateUninstallKeys(mainKey64));
                            using (RegistryKey mainKey32 = key.OpenSubKey(uninstallKey32))
                                apps.AddRange(EnumerateUninstallKeys(mainKey32));
                        }

                        var internetExplorerVersion = FileVersionInfo.GetVersionInfo($@"\\{ComputerName}\C$\Program Files\Internet Explorer\iexplore.exe");
                        if (internetExplorerVersion != null && internetExplorerVersion.ProductVersion.Length > 0)
                        {
                            apps.Add(new RemoteApplication
                            {
                                DisplayName = "Internet Explorer",
                                Publisher   = "Microsoft Corporation",
                                Version     = internetExplorerVersion.ProductVersion
                            });
                        }

                        taskResult.DidTaskSucceed = true;
                    }
                    catch
                    {
                        taskResult.DidTaskSucceed = false;
                    }


                    // Cleanup.
                    if (!isLocal && !isServiceRunning)
                    {
                        try
                        {
                            if (sc != null)
                            {
                                sc.Stop();
                            }
                        }

                        catch (Exception)
                        {
                        }
                    }
                }

            return(apps);
        }