Esempio n. 1
0
        /// <summary>
        /// Performs a repair on the current installed version of the .NET agent via the command line.
        /// </summary>
        public void CommandLineRepair(string testName = "")
        {
            Common.Log(String.Format("Repairing the .NET Agent"), testName);
            IISCommand("Stop");

            // Make a call to perform the repair
            FileOperations.DeleteFileOrDirectory(_mgmtScope, @"C:\\repairLog.txt");

            if (File.Exists($@"{Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi"))
            {
                Common.Log($@"Found {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }
            else
            {
                Common.Log($@"ERROR: Did not find: {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }

            var command =
                $@"msiexec.exe /f {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi /quiet /lv* C:\repairLog.txt";

            Common.Log($"MSIEXEC command: {command}", testName);
            WMI.MakeWMICall(_mgmtScope, "Win32_Process", command);

            IISCommand("Start");
        }
Esempio n. 2
0
        public WMI ProcressWater(AllIndex item)
        {
            var create = new WMI
            {
                HasWater = HasWater(item),
                WaterManagementForUse = WaterManagementForUse(item),
                Agriculture           = Agriculture(item),
                Factory                = Factory(item),
                Service                = Service(item),
                WaterForDevelopment    = (Agriculture(item) + Factory(item) + Service(item)) / 3,
                WaterBalanceCostAndUse = item.WaterBalanceCostAndWaterUse,
                WaterQualityAndEnvironmentalManagement = WaterQualityAndEnvironmentalManagement(item),
                Flood   = Flood(item),
                Drought = Drought(item),
                WaterDisasterManagement           = (Flood(item) + Drought(item)) / 2,
                WatershedForestManagement         = WatershedForestManagement(item),
                BasinManagementPlans              = item.PlanWaterManagement,
                ParticipationWaterManagement      = item.ParticipatingIrrigationProjects,
                WaterManagementOrganization       = item.DistributionOfParticipatingIrrigationProjects,
                DevelopmentPotential              = DevelopmentPotential(item),
                MaintainingForWaterTransportation = item.WaterwaysAreSuitableForWaterTransportation,
                Tracking                 = Tracking(item),
                WaterAllocation          = item.ReservoirHasGoodManagement,
                WaterResourcesManagement = (item.PlanWaterManagement + item.ParticipatingIrrigationProjects + item.DistributionOfParticipatingIrrigationProjects + DevelopmentPotential(item) + item.WaterwaysAreSuitableForWaterTransportation + Tracking(item) + item.ReservoirHasGoodManagement) / 7,
            };

            throw new NotImplementedException();
        }
Esempio n. 3
0
        internal static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /* Set up the logging framework */
            Logging.Initialize();
            logger.Info("Application started");
            logger.Info("App Version: {0}", Assembly.GetExecutingAssembly().GetName().Version.ToString());
            logger.Info("Portable Mode: {0}", AppFolders.PortableMode);
            logger.Info("Base Working Directory: {0}", AppFolders.BaseWorkingFolder);

            logger.Info("System Name: {0}", WMI.QuerySystemName());
            logger.Info("Operating System: {0}", WMI.QueryWindowsVersion());
            logger.Info("OS Service Pack: {0}", WMI.QueryWindowsServicePack());
            logger.Info("System Memory: {0}", WMI.QueryInstalledMemory());
            logger.Info("BIOS ID: {0}", WMI.QueryInstalledBIOS());
            logger.Info("System Role: {0}", WMI.QueryDomainRole());

            if (!AppFolders.WorkingFolderIsWritable())
            {
                logger.Error("Working directory was not writable. Terminating...");
                return;
            }

            logger.Info("Launching main user interface");
            Application.Run(new FormMain());
            logger.Info("Application closed cleanly");
        }
Esempio n. 4
0
        /// <summary>
        /// Get a single computer's Win32 properties
        /// </summary>
        /// <param name="wmi"></param>
        /// <returns></returns>
        static Computer GetComputerProperties(WMI wmi)
        {
            var queries = new Dictionary <string, string>()
            {
                { "Baseboard", "SELECT Manufacturer,Model,Product,SerialNumber FROM Win32_BaseBoard" },
                { "BIOS", "SELECT Manufacturer,SerialNumber,SMBIOSBIOSVersion FROM Win32_BIOS" },
                { "DiskDrive", "SELECT Model,Size,Manufacturer FROM Win32_DiskDrive" },
                { "MotherboardDevice", "SELECT PrimaryBusType,SecondaryBusType FROM Win32_MotherboardDevice" },
                //{"OperatingSystem","SELECT * FROM Win32_OperatingSystem"},
                { "PhysicalMemory", "SELECT Capacity,DataWidth,FormFactor,MemoryType,Speed FROM Win32_PhysicalMemory" },
                { "Processor", "SELECT Manufacturer,Name,Description,MaxClockSpeed,L2CacheSize,AddressWidth,DataWidth,NumberOfCores,NumberOfLogicalProcessors,ProcessorId FROM Win32_Processor" },
                { "VideoController", "SELECT AdapterCompatibility,AdapterRAM,Name,VideoModeDescription,VideoProcessor,VideoMemoryType FROM Win32_VideoController" }
            };

            var computer = new Computer()
            {
                Baseboard         = new Baseboard(wmi.GetQueryResult(queries["Baseboard"])),
                BIOS              = new BIOS(wmi.GetQueryResult(queries["BIOS"])),
                DiskDrive         = new DiskDrive(wmi.GetQueryResult(queries["DiskDrive"])),
                MotherboardDevice = new MotherboardDevice(wmi.GetQueryResult(queries["MotherboardDevice"])),
                PhysicalMemory    = new PhysicalMemory(wmi.GetQueryResult(queries["PhysicalMemory"])),
                Processor         = new Processor(wmi.GetQueryResult(queries["Processor"])),
                VideoController   = new VideoController(wmi.GetQueryResult(queries["VideoController"]))
            };

            return(computer);
        }
Esempio n. 5
0
        /// <summary>
        /// Fetches the value of the specified environment variable.
        /// </summary>
        /// <param name="environmentVariable">The name of the environment variable.</param>
        /// <returns>The value of the environment variable.</returns>
        public string FetchEnvironmentVariableValue(String environmentVariable)
        {
            var query = $"SELECT * FROM Win32_Environment WHERE Name='{environmentVariable}'";
            var value = WMI.WMIQuery_GetPropertyValue(_mgmtScope, query, "variableValue");

            return(value);
        }
Esempio n. 6
0
        public TestServer(String address = null, bool factoryReset = false)
        {
            if (address != null)
            {
                _address = address;
                Common.LockServer(_address);
            }
            else
            {
                if (Settings.RemoteServers.Length > 1 && Settings.Environment == Enumerations.EnvironmentSetting.Remote)
                {
                    _address = Common.FindAndLockATestServer();
                }
                else if (Settings.RemoteServers.Length == 1 && Settings.Environment == Enumerations.EnvironmentSetting.Remote)
                {
                    _address = Settings.RemoteServers[0];
                    Common.LockServer(_address);
                }
                else
                {
                    _address = System.Environment.MachineName;
                }
            }

            if (Settings.Environment == Enumerations.EnvironmentSetting.Remote)
            {
                _connection = new ConnectionOptions {
                    Authentication = AuthenticationLevel.PacketPrivacy, Username = "******", Password = "******"
                };
                _driveRoot = $@"\\{_address}\C$\";
            }
            else
            {
                _connection = new ConnectionOptions {
                    Authentication = AuthenticationLevel.PacketPrivacy
                };
                _driveRoot = @"C:\";
            }

            _dataPath    = $@"{_driveRoot}ProgramData\New Relic\.NET Agent\";
            _installPath = $@"{_driveRoot}Program Files\New Relic\.NET Agent\";

            _mgmtScope = new ManagementScope {
                Options = _connection, Path = new ManagementPath($@"\\{_address}\root\cimv2")
            };

            _configPath            = $@"{_dataPath}\newrelic.config";
            _processorArchitecture = WMI.WMIQuery_GetPropertyValue(_mgmtScope, "SELECT * FROM Win32_OperatingSystem", "OSArchitecture") == "64-bit"
                ? "x64"
                : "x86";
            _processorBit = _processorArchitecture == "x64"
                ? "64"
                : "32";

            if (factoryReset)
            {
                FactoryReset();
            }
        }
Esempio n. 7
0
        static void CollectLocalMachine()
        {
            var      computerName = SystemInformation.ComputerName;
            var      wmi          = new WMI(computerName);
            Computer c            = GetComputerProperties(wmi);

            Console.WriteLine(c.ToJson());
        }
Esempio n. 8
0
        /// <summary>
        /// Executes the specified command against IIS.
        /// </summary>
        /// <param name="command">The command to execute ('Stop', 'Start', or 'Reset').</param>
        public void IISCommand(String command)
        {
            Common.Log($"Executing IIS '{command}' on '{_address}'");
            var iisCommand = command == "Reset"
                ? String.Empty
                : $" /{command}";

            WMI.MakeWMICall(_mgmtScope, "Win32_Process", $@"cmd.exe /c iisreset.exe{iisCommand}");
        }
Esempio n. 9
0
        private string GetWmiInstanceName()
        {
            try
            {
                instanceName = WMI.GetInstanceName(wmiScope, wmiAMDACPI);
            }
            catch { }

            return(instanceName);
        }
Esempio n. 10
0
        /// <summary>
        /// Uninstalls the .NET Agent via a WMI call.
        /// </summary>
        /// <param name="purge">Flag used to purge remaining file(s) after uninstall.</param>
        public void CommandLineUninstall(bool purge = false, string testName = "")
        {
            Common.Log(String.Format("Uninstalling the .NET Agent"), testName);
            IISCommand("Stop");

            // Uninstall the agent
            FileOperations.DeleteFileOrDirectory(_mgmtScope, @"C:\\uninstallLog.txt");

            if (File.Exists($@"{Settings.Workspace}\build\BuildArtifacts\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi"))
            {
                Common.Log($@"Found {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }
            else
            {
                Common.Log($@"ERROR: Did not find: {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }

            var command =
                $@"msiexec.exe /x {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi /norestart /quiet /lv* C:\uninstallLog.txt";

            Common.Log($"MSIEXEC command: {command}", testName);
            WMI.MakeWMICall(_mgmtScope, "Win32_Process", command);

            // Purge files if specified
            if (purge)
            {
                // Set the file paths
                var paths = new[]
                {
                    @"C:\\Program Files\\New Relic",
                    @"C:\\ProgramData\\New Relic"
                };

                // Recursively deleted the specified paths
                foreach (var path in paths)
                {
                    FileOperations.DeleteFileOrDirectory(_mgmtScope, path, true);
                }

                // Delete the agent environment variables
                DeleteEnvironmentVariable("COR_ENABLE_PROFILING");
                DeleteEnvironmentVariable("COR_PROFILER");
                DeleteEnvironmentVariable("COR_PROFILER_PATH");
                DeleteEnvironmentVariable("NEWRELIC_HOME");
                DeleteEnvironmentVariable("NEW_RELIC_HOME");
                DeleteEnvironmentVariable("NEW_RELIC_HOST");
                DeleteEnvironmentVariable("NEWRELIC_LICENSEKEY");

                // Delete the WAS and W3SVC Environment
                DeleteRegistryKey(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Services\W3SVC", "Environment");
                DeleteRegistryKey(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Services\WAS", "Environment");
            }

            IISCommand("Start");
        }
Esempio n. 11
0
        public static IEnumerable <SmbShare> EnumerateInstances(
            string computerName           = ".",
            NetworkCredential credentials = default)
        {
            var classInfo = typeof(SmbShare).GetCustomAttribute <ManagementObjectAttribute>();

            foreach (var o in WMI.Query(classInfo.GetQuery(), classInfo.GetScope(computerName, credentials)))
            {
                yield return(WMI.Bind <SmbShare>((ManagementObject)o));
            }
        }
Esempio n. 12
0
        private void PrintWmiFunctions()
        {
            try
            {
                classInstance = new ManagementObject(wmiScope,
                                                     $"{wmiAMDACPI}.InstanceName='{instanceName}'",
                                                     null);

                // Get function names with their IDs
                string[] functionObjects = { "GetObjectID", "GetObjectID2" };
                var      index           = 1;

                foreach (var functionObject in functionObjects)
                {
                    AddHeading($"WMI: Bios Functions {index}");

                    try
                    {
                        pack = WMI.InvokeMethod(classInstance, functionObject, "pack", null, 0);

                        if (pack != null)
                        {
                            var ID       = (uint[])pack.GetPropertyValue("ID");
                            var IDString = (string[])pack.GetPropertyValue("IDString");
                            var Length   = (byte)pack.GetPropertyValue("Length");

                            for (var i = 0; i < Length; ++i)
                            {
                                if (IDString[i] == "")
                                {
                                    return;
                                }
                                AddLine($"{IDString[i] + ":",-30}{ID[i]:X8}");
                            }
                        }
                        else
                        {
                            AddLine("<FAILED>");
                        }
                    }
                    catch
                    {
                        // ignored
                    }

                    index++;
                    AddLine();
                }
            }
            catch
            {
                // ignored
            }
        }
Esempio n. 13
0
 private void AddXBoxControlersVIDPIDsToPnPDevices(List <PnPEntityInfo> collection)
 {
     foreach (var pnpEntityInfo in collection)
     {
         if (pnpEntityInfo.DeviceID.Contains(WMI.XInputDeviceIDMarker))
         {
             pnpEntityInfo.IsXBoxDevice  = true;
             pnpEntityInfo.VID_PID       = WMI.Get_VID_PID(pnpEntityInfo.DeviceID);
             pnpEntityInfo.PID_VIDstring = WMI.Get_PID_VID(pnpEntityInfo.DeviceID);
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Executes the strong name utility to determine if the specified file is signed.
        /// </summary>
        /// <param name="filePath">The path to the file to be checked.</param>
        /// <returns>Output from the batch script that checks if the .dll is signed.</returns>
        private string ExecuteIsStronglyNamed(string filePath)
        {
            var command = string.Format("cmd.exe /c sn.exe -vf \"{0}\" > C:\\cmdOutput.txt", filePath);

            WMI.MakeWMICall(TServer.MgmtScope, "Win32_Process", command, @"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\NETFX 4.0 Tools\");

            var result = FileOperations.ParseTextFile(string.Format(@"{0}\cmdOutput.txt", TServer.DriveRoot));

            FileOperations.DeleteFileOrDirectory(TServer.MgmtScope, @"C:\\cmdOutput.txt");

            return(result);
        }
Esempio n. 15
0
        /// <summary>
        /// Installs the .NET Agent via a command line call to msiexec.exe.
        /// </summary>
        /// <param name="licenseKey">The account license key.</param>
        /// <param name="features">The optional list of features to install.</param>
        /// <param name="allFeatures">Option to install all options - this will override any/all features specified in the 'features' parameter.</param>
        public void CommandLineInstall(String licenseKey, List <Enumerations.InstallFeatures> features = null, bool allFeatures = false, bool setCollectorHost = true, string testName = "")
        {
            Common.Log(String.Format("Installing the .NET Agent"), testName);
            IISCommand("Stop");

            // Make a wmi call to perform the install
            var addKey = !String.IsNullOrEmpty(licenseKey)
                ? $" NR_LICENSE_KEY={licenseKey}"
                : String.Empty;
            var featuresList = String.Empty;
            var command      = String.Empty;

            FileOperations.DeleteFileOrDirectory(_mgmtScope, @"C:\\installLog.txt");

            if (File.Exists($@"{Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi"))
            {
                Common.Log($@"Found {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }
            else
            {
                Common.Log($@"ERROR: Did not find: {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi", testName);
            }

            if (allFeatures)
            {
                command =
                    $@"msiexec.exe /i {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi /norestart /quiet{addKey} INSTALLLEVEL=50 /lv* C:\installLog.txt";
            }
            else
            {
                if (features != null)
                {
                    featuresList = features.Aggregate(" ADDLOCAL=", (current, feature) => current + (feature.ToString() + ","));
                    featuresList = featuresList.TrimEnd(',');
                }

                command =
                    $@"msiexec.exe /i {Settings.Workspace}\build\BuildArtifacts\\MsiInstaller-x64\NewRelicAgent_{_processorArchitecture}_{Settings.AgentVersion}.msi /norestart /quiet{addKey}{featuresList} /lv* C:\installLog.txt";
            }

            Common.Log($"MSIEXEC command: {command}", testName);
            WMI.MakeWMICall(_mgmtScope, "Win32_Process", command);

            if (setCollectorHost)
            {
                ModifyOrCreateXmlAttribute("//x:service", "host", "staging-collector.newrelic.com");
            }

            ModifyOrCreateXmlAttribute("//x:configuration/x:log", "level", "debug");
            ModifyOrCreateXmlAttribute("//x:configuration/x:log", "auditLog", "true");
            IISCommand("Start");
        }
Esempio n. 16
0
        public void TestInstallWMICommandLine()
        {
            string filePath = @"C:\CommandLineTest.txt";
            string command  = $@"cmd /c ""echo ""Command Line Test"" > {filePath}""";

            WMI.InstallWMIPersistence("CommandLineTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.CommandLine, command, "notepad.exe");

            Process notepad = StartNotepad();

            Thread.Sleep(3000);

            Assert.IsTrue(File.Exists(filePath));
        }
Esempio n. 17
0
        public override string[] Execute(ParsedArgs args)
        {
            if (string.IsNullOrEmpty(args.ProcessName))
            {
                throw new EDDException("ProcessName cannot be empty");
            }

            LDAP          procQuery       = new LDAP();
            List <string> procComputers   = procQuery.CaptureComputers();
            WMI           processSearcher = new WMI();
            List <string> systemsWithProc = processSearcher.CheckProcesses(procComputers, args.ProcessName);

            return(systemsWithProc.ToArray());
        }
Esempio n. 18
0
        private void AddMachineInformation(List <string> extra)
        {
            extra.Add("Machine information:");

            // Processor
            List <string> cpuNames = WMI.Processor_Name();

            foreach (string s in cpuNames)
            {
                extra.Add(string.Format("- Processor: {0}", s));
            }

            List <string> clockspeed = WMI.Processor_MaxClockSpeed();

            foreach (string s in clockspeed)
            {
                extra.Add(string.Format("- Processor clock speed: {0} MHz", s));
            }

            extra.Add(string.Format("- Logical processors: {0}", Environment.ProcessorCount));
            extra.Add(string.Format("- Physical memory: {0:0.000} GB", WMI.PhysicalMemory_Capacity()));
            extra.Add(string.Format("- OS version: {0}", Environment.OSVersion));

            // Physical disks
            List <PhysicalDisk> disks = WMI.PhysicalDisks();

            foreach (PhysicalDisk disk in disks)
            {
                extra.Add(string.Format("- Disk: {0}", disk.Model));
                extra.Add(string.Format("    Type: {0}", disk.Type));
                extra.Add(string.Format("    Interface: {0}", disk.InterfaceType));
                extra.Add(string.Format("    Size: {0:0.000} GB", disk.Size));
            }

            List <LogicalDisk> logicalDisks = WMI.LogicalDisks();

            foreach (LogicalDisk disk in logicalDisks)
            {
                if (disk.Size == 0)
                {
                    continue;
                }

                extra.Add(string.Format("- Partition: {0}", disk.Caption));
                extra.Add(string.Format("    Type: {0}", disk.DriveType.ToString()));
                extra.Add(string.Format("    File System: {0}", disk.FileSystem));
                extra.Add(string.Format("    Size: {0:0.000} GB", disk.Size));
                extra.Add(string.Format("    Free space: {0:0.000} GB", disk.Free));
            }
        }
        public ActionResult <dynamic> Post([FromBody] WMI wmi)
        {
            var newWmi = new WeeklyMenuItem
            {
                Date   = wmi.Date,
                Recipe = _context.Set <Recipe>().Find(wmi.Recipe)
            };

            _context.Add(newWmi);

            _context.SaveChanges();

            return(newWmi);
        }
Esempio n. 20
0
 public override void Run(Dictionary <String, Parameter> RunParams)
 {
     if (RunParams.TryGetValue("ComputerName", out Parameter computer))
     {
         if (RunParams.TryGetValue("Command", out Parameter command))
         {
             foreach (string cmd in command.Value)
             {
                 WMI.WMIExecute(computer.Value, cmd, null, null);
             }
         }
         else
         {
             Printing.Error("No command specified");
         }
     }
 }
Esempio n. 21
0
        /*private string ExecuteCommand(InquiryEntity ie)
         * {
         *  IList<FileEntity> res = new List<FileEntity>();
         *  string result = string.Empty;
         *
         *  if (ie.Tasks != null)
         *  {
         *      IFinder finder = new WMI(true, ie);
         *      //todo for many tasks
         *      res = finder.Search(ie.Tasks[0]);
         *  }
         *
         *  if (res.Count > 0) result = CSVFile.WriteCsvString(res);
         *
         *  return res; // result;
         * }*/

        private List <FileEntity> ExecuteCommand(InquiryEntity ie)
        {
            List <FileEntity> res = new List <FileEntity>();

            //string result = string.Empty;

            if (ie.Tasks != null)
            {
                IFinder finder = new WMI(true, ie);
                //todo for many tasks
                res = finder.Search(ie.Tasks[0]);
            }

            //if (res.Count > 0) result = CSVFile.WriteCsvString(res);

            return(res); // result;
        }
Esempio n. 22
0
        public void TestInstallWMIJScript()
        {
            string filePath = @"C:\\JScriptTest.txt";
            string jscript  = $@"
var myObject, newfile;
myObject = new ActiveXObject(""Scripting.FileSystemObject"");
newfile = myObject.CreateTextFile(""{filePath}"", false);
";

            WMI.InstallWMIPersistence("JScriptTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.ActiveScript, jscript, "notepad.exe", WMI.ScriptingEngine.JScript);

            Process notepad = StartNotepad();

            Thread.Sleep(3000);

            Assert.IsTrue(File.Exists(filePath));
        }
Esempio n. 23
0
 private void bAddPCFromDomain_Click(object sender, EventArgs e)
 {
     if (WMI.IsDomainMember())
     {
         Debug.WriteLine(WMI.GetComputerDomainName());
     }
     else
     {
         Debug.WriteLine(WMI.GetComputerWorkgroupName());
         using (DirectoryEntry workgroup = new DirectoryEntry("WinNT://Workgroup"))
         {
             foreach (DirectoryEntry child in workgroup.Children)
             {
                 Debug.WriteLine(child.Name);
             }
         }
     }
 }
Esempio n. 24
0
        public void TestInstallWMIVBScript()
        {
            string filePath = @"C:\VBScriptTest.txt";
            string vbscript = $@"
Set objFSO=CreateObject(""Scripting.FileSystemObject"")
outFile = ""{filePath}""
Set objFile = objFSO.CreateTextFile(outFile, True)
objFile.Write ""VBScript Test""
objFile.Close";

            WMI.InstallWMIPersistence("VBScriptTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.ActiveScript, vbscript, "notepad.exe", WMI.ScriptingEngine.VBScript);

            Process notepad = StartNotepad();

            Thread.Sleep(3000);

            Assert.IsTrue(File.Exists(filePath));
        }
 void getWmiData()
 {
     try {
         foreach (ManagementObject obj in WMI.GetWmi("Select Caption, OSProductSuite from Win32_OperatingSystem", ComputerName))
         {
             OperatingSystem = (String)obj["Caption"];
             UInt32 osSuite = (UInt32)obj["OSProductSuite"];
             if ((osSuite & 2) > 0)
             {
                 Sku = "Enterprise";
             }
             if ((osSuite & 128) > 0)
             {
                 Sku = "Datacenter";
             }
         }
     } catch { }
 }
Esempio n. 26
0
 public MainWindow()
 {
     InitializeComponent();
     this.PreviewKeyDown += new KeyEventHandler((obj, kea) => {
         if (kea.Key == Key.Escape)
         {
             Close();
         }
     });
     ctx            = SynchronizationContext.Current;
     worker         = new BackgroundWorker();
     worker.DoWork += (obj, ea) => {
         wmi = new WMI();
         ctx.Post(new SendOrPostCallback(o => {
             var l            = (List <string>)o;
             OS.Content       = l[0];
             TotalMem.Content = l[1];
             MemV.Content     = l[2];
             MemClck.Content  = l[3];
             MemType.Content  = l[4];
         }), new List <string>()
         {
             wmi.GetOS(),
             wmi.GetTotalMemory() + "MB",
             wmi.GetMemVoltage().ToString() + "mV",
             wmi.GetMemClockSpeed().ToString() + "Hz",
             wmi.GetMemType().ToString()
         });
         while (true)
         {
             var ul = wmi.GetTotalCPUUsage();
             ctx.Post(new SendOrPostCallback(o => {
                 var l                = (List <string>)o;
                 CPUUsage.Content     = l[0];
                 AvailableMem.Content = l[1];
             }), new List <string>()
             {
                 wmi.GetTotalCPUUsage().ToString() + "%",
                 wmi.GetAvailableMemory() + "MB"
             });
         }
     };
     worker.RunWorkerAsync();
 }
        protected internal override void Write()
        {
            WriteByte(0); //Packet Id
            WriteString("Client");
            WriteString(GetCountry.Country());
            WriteBytes(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].GetAddressBytes());
            WriteString(WindowsIdentity.GetCurrent().Name.Split('\\')[1]);
            WriteString(WMI.ReadString("CSName", "CIM_OperatingSystem", null));
            WriteString(WMI.ReadString("Caption", "CIM_OperatingSystem", null));
            WriteInteger(WMI.ReadInteger("BuildNumber", "CIM_OperatingSystem", null));
            WriteString(WMI.ReadString("OSArchitecture", "CIM_OperatingSystem", null));
            WriteString(WMI.ReadString("CSDVersion", "CIM_OperatingSystem", null));
            WriteString(WMI.ReadString("RegisteredUser", "CIM_OperatingSystem", null));
            WriteString(WinSerial.GetSerial());
            WriteString(WMI.ReadString("SystemDirectory", "CIM_OperatingSystem", null));
            WriteString(WMI.ReadString("SystemDrive", "CIM_OperatingSystem", null) + "\\");
            WriteString(string.Format("{0} GB", WMI.ReadInteger("TotalVisibleMemorySize", "CIM_OperatingSystem", null) / 1000000));
            WriteString(WMI.ReadString("Name", "CIM_Processor", null));

            string MacAddress = "";

            try
            {
                ManagementObjectSearcher objOS = default(ManagementObjectSearcher);
                objOS = new ManagementObjectSearcher("select MACAddress, IPEnabled from Win32_NetworkAdapterConfiguration");
                foreach (ManagementBaseObject objMgmt in objOS.Get())
                {
                    if (objMgmt["IPEnabled"].ToString() == "True")
                    {
                        MacAddress += objMgmt["MACAddress"].ToString() + ", ";
                    }
                }
            }catch {}

            WriteString(MacAddress);
            WriteString(Program.RatVersion);
            WriteBytes(BitmapToBytes(ScreenCapture.resizeImage(ScreenCapture.CaptureScreen(), new Size(120, 120))));
            WriteShort((short)(Screen.PrimaryScreen.Bounds.Width));
            WriteShort((short)(Screen.PrimaryScreen.Bounds.Height));
        }
Esempio n. 28
0
        private void SetParallelLimits()
        {
            int physicalCores = WMI.QueryPhysicalProcessorCount();

            switch (scanTask.ParallelLevel)
            {
            case ParallelLevel.FULL:
            default:
                return;

            case ParallelLevel.REDUCED:
                logger.Info("Parallelism capped at physical core count");
                parallelOptions.MaxDegreeOfParallelism = Math.Max(1, physicalCores);
                break;

            case ParallelLevel.NONE:
                logger.Info("Operating in single-threaded mode");
                parallelOptions.MaxDegreeOfParallelism = 1;
                break;
            }

            logger.Debug("Maximum degree of parallelism set to {0} ", parallelOptions.MaxDegreeOfParallelism);
        }
Esempio n. 29
0
        /// <summary>
        /// Installs the .NET Agent via a command line call to msiexec.exe.
        /// </summary>
        /// <param name="targetDir">The target directory for the install.</param>
        public void CommandLineInstallOldInstall()
        {
            IISCommand("Stop");

            FileOperations.DeleteFileOrDirectory(_mgmtScope, @"C:\\installLogOld.txt");

            var command =
                $@"msiexec.exe /i C:\NewRelicAgent_{_processorArchitecture}_2.8.1.0.msi /norestart /quiet NR_LICENSE_KEY={Settings.LicenseKey} /lv* C:\installLogOld.txt";

            Common.Log($"MSIEXEC command: {command}");
            WMI.MakeWMICall(_mgmtScope, "Win32_Process", command);

            var configPath = String.Empty;

            if (Settings.Environment == Enumerations.EnvironmentSetting.Local)
            {
                configPath = @"C:\ProgramData\New Relic\.NET Agent\newrelic.xml";
            }
            else
            {
                configPath = $@"\\{_address}\C$\ProgramData\New Relic\.NET Agent\newrelic.xml";
            }

            // Set the host attribute value to staging, audit logging to 'true'
            ModifyOrCreateXmlAttribute("//x:service", "host", "staging-collector.newrelic.com", configPath);
            ModifyOrCreateXmlAttribute("//x:configuration/x:log", "auditLog", "true", configPath);

            // Create the subfolders
            FileOperations.CreateFileOrDirectory(_mgmtScope, $@"C:\ProgramData\New Relic\.NET Agent\extensions\ExtensionsSubdirectory", true);

            // Create the files
            FileOperations.CreateFileOrDirectory(_mgmtScope, $@"C:\ProgramData\New Relic\.NET Agent\logs\Log.txt");
            FileOperations.CreateFileOrDirectory(_mgmtScope, $@"C:\ProgramData\New Relic\.NET Agent\extensions\Extensions.txt");
            FileOperations.CreateFileOrDirectory(_mgmtScope, $@"C:\ProgramData\New Relic\.NET Agent\extensions\ExtensionsSubdirectory\ExtensionsSubdirectory.txt");

            IISCommand("Start");
        }
Esempio n. 30
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="oProvider"></param>
 public Components(WMI.Provider oProvider)
 {
     oWMIProvider = oProvider;
 }
 /// <summary>
 /// DesiredConfigurationManagement Constructor
 /// </summary>
 /// <param name="oProvider">A WMIProvider Instance</param>
 public DesiredConfigurationManagement(WMI.Provider oProvider)
 {
     oWMIProvider = new WMI.Provider(oProvider.mScope.Clone());
 }
Esempio n. 32
0
 private void procWatcher_ProcessCreated(WMI.Win32.Process proc)
 {
     try
     {
         PyController.system_new_process(proc.Name, proc.ProcessId, System.Diagnostics.Process.GetProcessById((int)proc.ProcessId).Handle);
     }
     catch
     {
         // Ignore
     }
 }
Esempio n. 33
0
 static void procWatcher_ProcessModified(WMI.Win32.Win32_Process process)
 {
     Console.Write("Modified " + process.Name + " " + process.ProcessId +"  "+ "DateTime:"+DateTime.Now + "\n");
 }
Esempio n. 34
0
 private static void procWatcher_ProcessModified(WMI.Win32.Process proc)
 {
     Console.Write("\n进程被修改\n " + proc.Name + " " + proc.ProcessId + "  " + "时间:" + DateTime.Now);
 }
Esempio n. 35
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 /// <param name="oProvider">WMI.Provider Instance</param>
 public SoftwareDistribution(WMI.Provider oProvider)
 {
     oWMIProvider = oProvider;
 }
Esempio n. 36
0
 public static WMIModel WMIToModel(WMI wmi)
 {
     return(new WMIModel {
         Description = wmi.Description, WMIID = wmi.WMIID
     });
 }
Esempio n. 37
0
 public Registry(WMI.Provider oProv)
 {
     oWMIProvider = oProv;
 }
Esempio n. 38
0
 public CCMClient(WMI.Provider wmiProvider)
 {
     connect(wmiProvider);
 }
Esempio n. 39
0
 protected void connect(WMI.Provider wmiProv)
 {
     oWMIProvider = wmiProv;
     oSMSSchedules = new SMS.Schedules(oWMIProvider);
     oWMIRegistry = new WMI.Registry(oWMIProvider);
     oWMIServices = new WMI.Services(oWMIProvider);
     oSMSSoftwareDistribution = new SMS.SoftwareDistribution(oWMIProvider);
     oWMIWindowsInstaller = new WMI.WindowsInstaller(oWMIProvider);
     oWMIFileIO = new WMI.FileIO(oWMIProvider);
     oWMIComputerSystem = new WMI.ComputerSystem(oWMIProvider);
     oSMSComponents = new SMS.Components(oWMIProvider);
     oSMSDCM = new SMS.DesiredConfigurationManagement(oWMIProvider);
 }
Esempio n. 40
0
 /// <summary>
 /// Default Constructor.  Initiates the Provider object.
 /// </summary>
 /// <param name="oProvider">A Provider object.</param>
 public Schedules(WMI.Provider oProvider)
 {
     oWMIPrivider = new WMI.Provider(oProvider.mScope.Clone());
 }
Esempio n. 41
0
 public WindowsInstaller(WMI.Provider oProv)
 {
     oWMIProvider = oProv;
 }