コード例 #1
0
ファイル: WMIQuery.cs プロジェクト: radtek/UltimateAdmin
        public static List <string> GetLoggedOnUser(string computerName)
        {
            List <string> users = new List <string>();

            try
            {
                var scope = GetManagementScope(computerName);
                scope.Connect();
                var Query    = new SelectQuery("SELECT LogonId  FROM Win32_LogonSession Where LogonType=10");
                var Searcher = new ManagementObjectSearcher(scope, Query);
                var regName  = new Regex(@"(?<=Name="").*(?="")");

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    foreach (ManagementObject LWmiObject in WmiObject.GetRelationships("Win32_LoggedOnUser"))
                    {
                        users.Add(regName.Match(LWmiObject["Antecedent"].ToString()).Value);
                    }
                }
            }
            catch (Exception ex)
            {
                users.Add(ex.Message);
            }

            return(users);
        }
コード例 #2
0
        private WmiObject NewWmiObjectForFakeGroupUser(string name)
        {
            var partComponent = String.Format("\\\\{0}\\root\\cimv2:Win32_UserAccount.Domain=\"{0}\",Name=\"{1}\"", FAKE_COMPUTER_NAME, name);
            var newWmiObject  = new WmiObject();

            newWmiObject.Add("PartComponent", partComponent);
            return(newWmiObject);
        }
コード例 #3
0
        private WmiObject NewWmiObjectForFakeLocalGroup(string groupName, string sid)
        {
            var newWmiObject = new WmiObject();

            newWmiObject.Add("Name", groupName);
            newWmiObject.Add("SID", sid);
            return(newWmiObject);
        }
コード例 #4
0
 private void SetInformationAboutHostName(SystemInformation systemInformation, IEnumerable <WmiObject> informationAboutHostName)
 {
     if (!this.TheListIsEmpty(informationAboutHostName))
     {
         WmiObject wmiObject = informationAboutHostName.First();
         systemInformation.PrimaryHostName = this.GetHostName(wmiObject);
         systemInformation.Architecture    = this.GetArchitecture(wmiObject);
     }
 }
コード例 #5
0
 private void SetInformationAboutOperationalSystem(SystemInformation systemInformation, IEnumerable <WmiObject> informationAboutOperationalSystem)
 {
     if (!this.TheListIsEmpty(informationAboutOperationalSystem))
     {
         WmiObject wmiObject = informationAboutOperationalSystem.First();
         systemInformation.SystemName    = this.GetSystemName(wmiObject);
         systemInformation.SystemVersion = wmiObject.GetValueOf("Version").ToString();
     }
 }
コード例 #6
0
ファイル: MethodForm.cs プロジェクト: 00mjk/LanExchange
        private void RunTheMethod()
        {
            if (WmiObject == null || WmiMethod == null)
            {
                return;
            }
            //var watcher = new ManagementOperationObserver();
            var inParams = WmiMethod.InParameters;
            var options  = new InvokeMethodOptions();
            ManagementBaseObject result = null;

            bRun.Enabled = false;
            try
            {
                result = WmiObject.InvokeMethod(WmiMethod.Name, inParams, options);
            }
            catch (ManagementException ex)
            {
                ShowFAIL(ex.Message);
            }
            bRun.Enabled = true;
            if (result == null)
            {
                return;
            }
            LB.Items.Add(string.Empty);
            string str;

            foreach (PropertyData pd in result.Properties)
            {
                str = String.Format(CultureInfo.InvariantCulture, "{0} = {1}", pd.Name, pd.Value);
                LB.Items.Add(str);
            }
            var resultProp = new PropertyDataExt(result.Properties[m_ReturnValueName]);

            if (resultProp.Value != null)
            {
                var value   = (int)((UInt32)resultProp.Value);
                var message = new Win32Exception(value).Message;
                str = String.Format(CultureInfo.InvariantCulture, METHOD_FAIL_FMT, value, message);
                LB.Items.Add(str);
                if (value == 0)
                {
                    ShowOK(Resources.MethodForm_Success);
                    if (!m_OutParamPresent)
                    {
                        timerOK.Enabled = true;
                    }
                }
                else
                {
                    ShowFAIL(String.Format(CultureInfo.InvariantCulture, METHOD_FAIL_FMT, value, message));
                }
            }
        }
コード例 #7
0
        private FileItemSystemData CollectFileItemSystemData(file_item fileItem)
        {
            WmiObject wmiLogicalFile = this.OpenWmiLogicalFileClass(fileItem);
            string    fullFilePath   = this.GetCompleteFilePath(fileItem);


            var fileItemSystemData = new FileItemSystemData();

            this.FillFileItemSystemData(wmiLogicalFile.GetValues(), fileItemSystemData);
            return(fileItemSystemData);
        }
コード例 #8
0
        public IEnumerable <WmiObject> GetWmiObjectsForNetworkInterfacesAdapter()
        {
            WmiObject networkInterfaceAdapter = new WmiObject();

            networkInterfaceAdapter.Add("Index", 6);
            networkInterfaceAdapter.Add("PhysicalAdapter", true);
            networkInterfaceAdapter.Add("AdapterTypeId", 0);
            List <WmiObject> wmiObjects = new List <WmiObject>();

            wmiObjects.Add(networkInterfaceAdapter);
            return(wmiObjects);
        }
コード例 #9
0
 private void SetInformationAboutNetworkAdapters(SystemInformation systemInformation, IEnumerable <WmiObject> informationAboutNetworkAdapter)
 {
     if (!this.TheListIsEmpty(informationAboutNetworkAdapter))
     {
         WmiObject        wmiObject        = informationAboutNetworkAdapter.First();
         NetworkInterface networkInterface = new NetworkInterface();
         networkInterface.IpAddress  = ((string[])wmiObject.GetValueOf("IPAddress"))[0];
         networkInterface.MacAddress = wmiObject.GetValueOf("MACAddress").ToString();
         networkInterface.Name       = wmiObject.GetValueOf("Description").ToString();
         systemInformation.Interfaces.Add(networkInterface);
     }
 }
コード例 #10
0
        public void Should_be_possible_to_collect_FileEffectiveRights()
        {
            // Arrange
            WmiObject fakeWmiObject = new WmiObject();

            fakeWmiObject.Add("Descriptor.DACL.AccessMask", (uint)128);
            fakeWmiObject.Add("Descriptor.DACL.AceFlags", (uint)123);
            fakeWmiObject.Add("Descriptor.DACL.Trustee.SID", "{500}");
            fakeWmiObject.Add("Descriptor.DACL.Trustee.Domain", "mss");
            fakeWmiObject.Add("Descriptor.DACL.Trustee.Name", "lfernandes");


            MockRepository  mocks = new MockRepository();
            WmiDataProvider fakeWmiDataProvider = mocks.DynamicMock <WmiDataProvider>();

            Expect.Call(fakeWmiDataProvider.InvokeMethodByWmiPath(null)).IgnoreArguments().Return(new WmiObject[] { fakeWmiObject });
            FileEffectiveRightsObjectCollector fileEffectiveRightsSysDataSource = new FileEffectiveRightsObjectCollector();

            fileEffectiveRightsSysDataSource.WmiDataProvider = fakeWmiDataProvider;

            mocks.ReplayAll();

            // Act
            IEnumerable <CollectedItem> collectedItem = fileEffectiveRightsSysDataSource.CollectDataForSystemItem(this.getFakeFileItem());

            Assert.IsNotNull(collectedItem, "The return of collect data cannot be null");
            Assert.AreEqual(1, collectedItem.Count(), "Unexpected collected items count.");
            Assert.IsNotNull(collectedItem.ElementAt(0).ItemType, "The file item cannot be null.");
            Assert.IsInstanceOfType(collectedItem.ElementAt(0).ItemType, typeof(fileeffectiverights_item), "The item of collected item must be file_item");
            fileeffectiverights_item collectedFileEffectiveRights = (fileeffectiverights_item)collectedItem.ElementAt(0).ItemType;

            Assert.AreEqual("{500}", collectedFileEffectiveRights.trustee_sid.Value, "Unexpected item value.");
            Assert.AreEqual("1", collectedFileEffectiveRights.file_read_attributes.Value, "Unexpected file attribute found.");

            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_append_data, false, "file_append_data");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_delete_child, false, "file_delete_child");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_execute, false, "file_execute");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_read_data, false, "file_read_data");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_read_ea, false, "file_read_ea");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_write_attributes, false, "file_write_attributes");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_write_data, false, "file_write_data");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.file_write_ea, false, "file_write_ea");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.generic_all, true, "generic_all");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.generic_execute, true, "generic_execute");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.generic_read, true, "generic_read");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.generic_write, false, "generic_write");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.standard_delete, false, "standard_delete");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.standard_read_control, false, "standard_delete");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.standard_synchronize, false, "standard_sync");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.standard_write_dac, false, "standard_write_dac");
            this.AssertFileEffectiveRight(collectedFileEffectiveRights.standard_write_owner, false, "standard_write_owner");
        }
コード例 #11
0
        private IEnumerable <WmiObject> CreateFakeWmiReturn()
        {
            var wmiObject = new WmiObject();

            wmiObject.Add("name", "cpaiva");
            wmiObject.Add("domain", "mss");
            var wmiObject2 = new WmiObject();

            wmiObject2.Add("name", "jcastro");
            wmiObject2.Add("domain", "local");

            return(new WmiObject[] { wmiObject, wmiObject2 });
        }
コード例 #12
0
        private WmiObject createFakeWmiObject()
        {
            WmiObject fakeWmiObject = new WmiObject();

            fakeWmiObject.Add(FILE_SIZE, 50);
            fakeWmiObject.Add(C_DATE, "20081217165939.013961 - 120");
            fakeWmiObject.Add(M_DATE, "20090116171121.673899 - 120");
            fakeWmiObject.Add(A_DATE, "20081217171525.895263 - 120");
            fakeWmiObject.Add(VERSION, "1");
            fakeWmiObject.Add(FILE_TYPE, "Text Document");
            fakeWmiObject.Add(COMPANY, "Modulo");
            return(fakeWmiObject);
        }
コード例 #13
0
        private IEnumerable <WmiObject> CreateFakeWmiObjectList(string wmiFieldName, string[] wmiFieldValues)
        {
            var result = new List <WmiObject>();

            foreach (var wmiFieldValue in wmiFieldValues)
            {
                var fakeWmiObject = new WmiObject();
                fakeWmiObject.Add(wmiFieldName, wmiFieldValue);

                result.Add(fakeWmiObject);
            }

            return(result);
        }
コード例 #14
0
        private WmiDataProvider GetMockedWmiDataProvider()
        {
            var fakeWmiObjects = new WmiObject[]
            { this.CreateFakeWmiObject(FAKE_DIR_PATH, FILE_TYPE_DIRECTORY, -1),
              this.CreateFakeWmiObject(FAKE_FILE_PATH, FILE_TYPE_TEXTFILE, 50) };

            var mocks           = new MockRepository();
            var fakeWmiProvider = mocks.DynamicMock <WmiDataProvider>();

            Expect.Call(fakeWmiProvider.SearchWmiObjects(null, null)).IgnoreArguments().Return(fakeWmiObjects);
            mocks.ReplayAll();

            return(fakeWmiProvider);
        }
コード例 #15
0
        private WmiObject createFakeWmiObject(string completeFileName, string fileType, int fileSize)
        {
            WmiObject fakeWmiObject = new WmiObject();

            fakeWmiObject.Add("Name", completeFileName);
            fakeWmiObject.Add(GeneratedFileItemAttributes.FileSize.ToString(), fileSize);
            fakeWmiObject.Add(GeneratedFileItemAttributes.CreationDate.ToString(), "20081217165939.013961 - 120");
            fakeWmiObject.Add(GeneratedFileItemAttributes.LastModified.ToString(), "20090116171121.673899 - 120");
            fakeWmiObject.Add(GeneratedFileItemAttributes.LastAccessed.ToString(), "20081217171525.895263 - 120");
            fakeWmiObject.Add(GeneratedFileItemAttributes.Version.ToString(), "1");
            fakeWmiObject.Add(GeneratedFileItemAttributes.FileType.ToString(), fileType);
            fakeWmiObject.Add(GeneratedFileItemAttributes.Manufacturer.ToString(), "Modulo");
            return(fakeWmiObject);
        }
コード例 #16
0
        public IEnumerable <WmiObject> GetWmiObjectsForOperatingSystemQuery()
        {
            WmiObject os = new WmiObject();

            os.Add("Version", "6.0.6002");
            os.Add("Name", "Microsoft® Windows Server® 2008 Enterprise |C:\\Windows|\\Device\\Harddisk0\\Partition2");
            os.Add("ServicePackMajorVersion", (ushort)2);
            os.Add("ServicePackMinorVersion", (ushort)0);

            List <WmiObject> wmiObjects = new List <WmiObject>();

            wmiObjects.Add(os);
            return(wmiObjects);
        }
コード例 #17
0
        private void collectSidItemSystemData(sid_sid_item sidItem)
        {
            string trusteeSID = sidItem.trustee_sid.Value;

            IEnumerable <WmiObject> wmiObjects = this.searchSIDObjectsOnTarget(trusteeSID);

            if ((wmiObjects == null) || (wmiObjects.Count() == 0))
            {
                throw new KeyNotFoundException();
            }

            WmiObject userAccount = wmiObjects.First();

            sidItem.trustee_domain = OvalHelper.CreateItemEntityWithStringValue(userAccount.GetFieldValueAsString("Domain"));
            sidItem.trustee_name   = OvalHelper.CreateItemEntityWithStringValue(userAccount.GetValueOf("Name").ToString());
        }
コード例 #18
0
        public IEnumerable <WmiObject> GetWmiObjectsForComputerSystemQuery()
        {
            WmiObject system = new WmiObject();

            system.Add("SystemType", "X86-based PC");
            system.Add("DNSHostName", "MSS-RJ-220");
            system.Add("PartOfDomain", true);
            system.Add("Domain", "mss.modulo.com.br");
            system.Add("Name", "MSS-RJ-220");


            List <WmiObject> wmiObjects = new List <WmiObject>();

            wmiObjects.Add(system);
            return(wmiObjects);
        }
コード例 #19
0
        private WmiObject createFakeWmiObject(string accountDomain, string accountName, string isLocalAccount, string wmiClassName)
        {
            WmiObject fakeWmiObject = new WmiObject();

            fakeWmiObject.Add("__CLASS", wmiClassName);
            fakeWmiObject.Add("Description", "Administrator have complete and unrestricted access to the computer/domain");
            fakeWmiObject.Add("Domain", accountDomain);
            fakeWmiObject.Add("Name", accountName);
            fakeWmiObject.Add("InstallDate", null);
            fakeWmiObject.Add("LocalAccount", Boolean.Parse(isLocalAccount));
            fakeWmiObject.Add(@"Caption", string.Format(@"{0}\{1}", accountDomain, accountName));
            fakeWmiObject.Add("SID", Guid.NewGuid().ToString());
            fakeWmiObject.Add("SIDType", (UInt16)4);
            fakeWmiObject.Add("Status", "OK");

            return(fakeWmiObject);
        }
コード例 #20
0
        private string GetArchitecture(WmiObject wmiObject)
        {
            string systemType = wmiObject.GetValueOf("SystemType").ToString();

            switch (systemType)
            {
            case "X86-based PC":
            case "X86-Nec98 PC":
                systemType = "INTEL32";
                break;

            case "MIPS-based PC":
                systemType = "MIPS";
                break;

            case "Alpha-based PC":
                systemType = "ALPHA32";
                break;

            case "Power PC":
                systemType = "POWERPC32";
                break;

            case "SH-x PC":
                systemType = "SUPERH";
                break;

            case "StrongARM PC":
                systemType = "STRONGARM";
                break;

            case "64-bit Intel PC":
                systemType = "INTEL64";
                break;

            case "64-bit Alpha PC":
                systemType = "ALPHA64";
                break;

            default:
                systemType = "UNKNOWN";
                break;
            }
            return(systemType);
        }
コード例 #21
0
        /// <summary>
        /// Return the name of host name concatenated with the domain name.
        /// </summary>
        /// <param name="wmiObject">The WMI object.</param>
        /// <returns></returns>
        private string GetHostName(WmiObject wmiObject)
        {
            string hostName = wmiObject.GetFieldValueAsString("DNSHostName").ToLower();

            if (string.IsNullOrEmpty(hostName))
            {
                hostName = wmiObject.GetFieldValueAsString("Name").ToLower();
            }

            object partOfDomain = wmiObject.GetValueOf("PartOfDomain");

            if ((partOfDomain != null) && ((bool)partOfDomain))
            {
                hostName += "." + wmiObject.GetFieldValueAsString("Domain");
            }

            return(hostName);
        }
コード例 #22
0
        public IEnumerable <WmiObject> GetWmiObjectsForNetworkInterfaces()
        {
            WmiObject networkInterface = new WmiObject();

            networkInterface.Add("Index", 6);
            networkInterface.Add("InterfaceIndex", 10);
            networkInterface.Add("Description", "Intel(R) 82567LM-3 Gigabit Network Connection");
            networkInterface.Add("MACAddress", "00 - 23 - AE - B6 - 6F - BF");
            networkInterface.Add("DHCPEnabled", true);
            networkInterface.Add("IPAddress", new String[] { "172.16.3.166", "fe80::99ab:a003:a78e:103b" });
            networkInterface.Add("IPSubnet", new String[] { "255.255.254.0", "64" });
            networkInterface.Add("IPUseZeroBroadcast", false);

            List <WmiObject> wmiObjects = new List <WmiObject>();

            wmiObjects.Add(networkInterface);
            return(wmiObjects);
        }
コード例 #23
0
        public void Should_be_possible_to_execute_a_simple_file_collect_defined_with_one_entity()
        {
            // Arrange
            var objectType      = ProbeHelper.GetDefinitionObjectTypeByID("definitionsSimple.xml", "oval:modulo:obj:1");
            var fakeCollectInfo = ProbeHelper.CreateFakeCollectInfo(new Definitions.ObjectType[] { objectType }, null, null);
            var fakeWmiObjects  = new WmiObject[] { this.createFakeWmiObject() };
            var fakeFileItem    = this.CreateFakeFileItem("c:\\temp\\file.txt", null, null);
            var fileProber      = this.CreateMockedFileProber(fakeWmiObjects, new ItemType[] { fakeFileItem }, null);

            // Act
            var collectedObjects = (List <CollectedObject>)fileProber.Execute(FakeContext, FakeTarget, fakeCollectInfo).CollectedObjects;

            // Assert
            Assert.IsNotNull(collectedObjects, "The result of file collect cannot be null");
            Assert.IsNotNull(collectedObjects.Single(), string.Format("The object '{0}' was not found.", "oval:modulo:obj:1"));
            this.AssertCollectedFileItems(collectedObjects.Single(), fakeWmiObjects);
            this.AssertFilePathEntityExistence((file_item)collectedObjects.Single().SystemData[0]);
        }
コード例 #24
0
        public T Create <T>()
        {
            T instance = (T)Activator.CreateInstance(typeof(T));

            PropertyInfo[] props = instance.GetType().GetProperties().Where(i => i.GetCustomAttribute <WmiObject>() != null).ToArray();
            foreach (PropertyInfo prop in props)
            {
                WmiObject accessory = prop.GetCustomAttribute <WmiObject>();
                // cache features
                if (accessory.Cache)
                {
                    if (Cache.Any(e => e.RootName == accessory.RootName))
                    {
                        WmiObjectCacheEntry entry = Cache.First(e => e.RootName == accessory.RootName);
                        if (entry.Values.Any(v => v.Key == accessory.KeyName))
                        {
                            prop.SetValue(instance, (string)entry.Values[accessory.KeyName]);
                            continue;
                        }
                    }
                }

                // end cache features
                if (!Equals(accessory, null))
                {
                    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From " + accessory.RootName))
                    {
                        foreach (var o in searcher.Get())
                        {
                            object wmi_value = o[accessory.KeyName];
                            if (!Equals(wmi_value, null))
                            {
                                prop.SetValue(instance, (string)wmi_value);
                                AddCache(accessory.RootName, accessory.KeyName, (string)wmi_value);
                                SaveCache();
                            }
                        }
                    }
                }
            }
            return(instance);
        }
コード例 #25
0
        /// <summary>
        /// Gets the name of the system.
        /// </summary>
        /// <param name="wmiObject">The WMI object.</param>
        /// <returns></returns>
        private string GetSystemName(WmiObject wmiObject)
        {
            string osName = wmiObject.GetValueOf("Name").ToString();

            osName = osName.Split('|')[0].Trim();
            osName = osName.Replace("®", "");
            osName = osName.Replace("™", "");
            ushort spmajor = (ushort)wmiObject.GetValueOf("ServicePackMajorVersion");
            ushort spminor = (ushort)wmiObject.GetValueOf("ServicePackMinorVersion");

            if (spmajor > 0)
            {
                osName += " SP" + spmajor.ToString();
                if (spminor > 0)
                {
                    osName += "." + spminor.ToString();
                }
            }
            return(osName);
        }
コード例 #26
0
    public static int Main()
    {
        System.Diagnostics.TraceSwitch MySwitch = new System.Diagnostics.TraceSwitch("MySwitch", null);
        MySwitch.Level = System.Diagnostics.TraceLevel.Verbose;

        Console.WriteLine("WMI COM+ Test Application");


        //Create a WmiPath object
        WmiPath Path = new WmiPath("root\\cimv2");

        Console.WriteLine("String in WmiPath object is : {0}", Path.PathString);

        //Make a connection to this path
        WmiCollection Session = WmiCollection.Connect(Path);

        //Get a class from this connection
        WmiObject ServiceClass = Session.Get(new WmiPath("Win32_LogicalDisk"));

        //WmiObject ServiceClass = Session.Get("Win32_LogicalDisk");
        //Display the class name (__CLASS property of the class)
        Console.WriteLine("The name of this class is : {0}", ServiceClass["__CLASS"]);

        //Enumerate instances
        WmiCollection Instances = Session.Open(new WmiPath("Win32_LogicalDisk"));

        foreach (WmiObject obj in Instances)
        {
            Console.WriteLine("The key of this instance is : {0}", obj["Name"]);
        }

        //Query
        WmiCollection QueryRes = Session.Query(new WmiQuery("select * from Win32_Service"));

        foreach (WmiObject Service in QueryRes)
        {
            Console.WriteLine("{0}", Service["Name"]);
        }

        return(0);
    }
コード例 #27
0
        private WmiDataProvider GetWmiProviderMock(string usernameReturn, bool userDisabledReturn, params string[] groupNamesReturn)
        {
            var fakeWqlResult = new List <WmiObject>();

            if (usernameReturn != null)
            {
                var fakeWmiObject = new WmiObject();
                fakeWmiObject.Add("Domain", "fakeDomainOrComputername");
                fakeWmiObject.Add("Name", usernameReturn);
                fakeWmiObject.Add("Disabled", userDisabledReturn);
                fakeWqlResult.Add(fakeWmiObject);
            }

            var mocks           = new MockRepository();
            var fakeWmiProvider = mocks.DynamicMock <WmiDataProvider>();

            Expect.Call(fakeWmiProvider.ExecuteWQL(null)).IgnoreArguments().Return(fakeWqlResult);
            mocks.ReplayAll();

            return(fakeWmiProvider);
        }
コード例 #28
0
        private WmiDataProvider GetWmiProviderMockWithNoWmiResultBehavior()
        {
            // This mocked WmiDataProvider must be used in order to test GetAllGroupsByUser method.
            var mocks           = new MockRepository();
            var fakeWmiProvider = mocks.StrictMock <WmiDataProvider>();

            // Create expectation for first calling (to get computer name).
            var wqlToGetComputerName          = new WQLBuilder().WithWmiClass("Win32_ComputerSystem").Build();
            var fakeWin32ComputerSystemRecord = new WmiObject();

            fakeWin32ComputerSystemRecord.Add("Name", FAKE_COMPUTER_NAME);
            fakeWin32ComputerSystemRecord.Add("DomainRole", 1);
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetComputerName)).Return(new[] { fakeWin32ComputerSystemRecord });

            // Create expectation for second calling (to get all local groups);
            var wqlToGetAllLocalGroups = new WQLBuilder().WithWmiClass("Win32_Group").AddParameter("localaccount", "1").Build();
            var fakeWin32GroupRecords  = new List <WmiObject>();

            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Administrators", "S-1-5-32-544"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Backup Operators", "S-1-5-32-551"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Users", "S-1-5-32-545"));
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetAllLocalGroups)).Return(fakeWin32GroupRecords);

            // Create expectation for each get group component calling...
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Administrators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Backup Operators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Users");

            // Create expectation for each get user details calling (3 first times) and get user SID (3 last times)
            Expect.Call(fakeWmiProvider.ExecuteWQL(null)).IgnoreArguments().Repeat.Times(6).Return(null);

            var wqlAllGetBuiltinAccounts = new WQLBuilder().WithWmiClass("Win32_SystemAccount").Build();

            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlAllGetBuiltinAccounts)).Return(null);

            mocks.ReplayAll();

            return(fakeWmiProvider);
        }
コード例 #29
0
        public void Should_be_possible_to_collect_a_FileObject_that_contains_a_referenced_variable()
        {
            // Arrange
            var objectType      = ProbeHelper.GetDefinitionObjectTypeByID("definitionsSimple.xml", "oval:modulo:obj:3");
            var variables       = VariableHelper.CreateVariableWithOneValue("oval:modulo:obj:3", "oval:modulo:var:3", "c:\\temp");
            var fakeCollectInfo = ProbeHelper.CreateFakeCollectInfo(new Definitions.ObjectType[] { objectType }, variables, null);
            var fakeWmiObjects  = new WmiObject[] { this.createFakeWmiObject() };
            var fakeFileItems   = new ItemType[] { this.CreateFakeFileItem(null, "c:\\temp", "file1.txt") };
            var fileProber      = this.CreateMockedFileProber(fakeWmiObjects, fakeFileItems, null);

            // Act
            var collectedObjects = (List <CollectedObject>)fileProber.Execute(FakeContext, FakeTarget, fakeCollectInfo).CollectedObjects;

            // Assert
            Assert.IsNotNull(collectedObjects, "The result of file collect cannot be null");
            Assert.IsNotNull(collectedObjects.Single(), string.Format("There is no collected object."));
            this.AssertCollectedFileItems(collectedObjects.Single(), fakeWmiObjects);

            var collectedItem = (file_item)collectedObjects.Single().SystemData[0];

            this.AssertPathAndFileNameEntitiesExistence(collectedItem);
            Assert.AreEqual("c:\\temp", collectedItem.path.Value, "The variable value was not set to file item entity.");
        }
コード例 #30
0
        static void Main(string[] args)
        {
            try
            {
                string          ComputerName = "localhost";
                ManagementScope Scope;

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username  = "";
                    Conn.Password  = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope          = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
                }
                else
                {
                    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
                }

                Scope.Connect();
                ObjectQuery Query = new ObjectQuery("SELECT Handle FROM Win32_Process Where Name='notepad.exe'");
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    WmiObject.InvokeMethod("Terminate", null);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }