Exemplo n.º 1
0
        /// <summary>
        /// Creates a new DNS zone and all associated record types.
        /// </summary>
        /// <param name="zone">DNS zone to create.</param>
        public void CreateZone(MsDnsZone zone)
        {
            ManagementPath       path     = new ManagementPath("MicrosoftDNS_Zone");
            ManagementClass      newZone  = new ManagementClass(WmiScope, path, null);
            ManagementBaseObject inParams =
                newZone.GetMethodParameters("CreateZone");

            inParams.Properties["ZoneName"].Value = zone.Name;
            inParams.Properties["ZoneType"].Value = (int)zone.Type;

            try
            {
                newZone.InvokeMethod("CreateZone", inParams, null);
            }
            catch (ManagementException ex)
            {
                throw new Exception("Could not create new DNS zone. " +
                                    "It is possible that this domain already exists.", ex);
            }

            // Defaults the SOA, and removes NS records.
            DefaultSoaRecord(zone);
            DeleteNsRecords(zone);

            // Now create the records for the zone.
            CreateRecords(zone.NsRecords);
            CreateRecords(zone.MxRecords);
            CreateRecords(zone.ARecords);
            CreateRecords(zone.CnameRecords);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 创建远程目录
        /// </summary>
        /// <param name="scope">ManagementScope Instance</param>
        /// <param name="DirectoryName">要建立的目录名</param>
        /// <param name="CurrentDirectory">根目录所在位置,缺省为C:\</param>
        /// <returns>0表示建立成功,-1表示建立失败</returns>
        public static int CreateRemoteDirectory(ManagementScope scope, string DirectoryName, string CurrentDirectory)
        {
            try
            {
                string currentDirectory = CurrentDirectory;
                if (String.IsNullOrEmpty(CurrentDirectory))
                {
                    currentDirectory = @"C:\";
                }
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                ManagementPath   managementPath   = new ManagementPath("Win32_Process");

                ManagementClass      processBatch = new ManagementClass(scope, managementPath, objectGetOptions);
                ManagementBaseObject inParams     = processBatch.GetMethodParameters("Create");

                inParams["CommandLine"]      = @"cmd /CMd " + DirectoryName;
                inParams["CurrentDirectory"] = currentDirectory;

                ManagementBaseObject outParams = null;
                outParams = processBatch.InvokeMethod("Create", inParams, null);

                //Wmilog.WriteToLog("Excute CreateRemoteDirectory:" + outParams.ToString());
            }
            catch (Exception ex)
            {
                //Wmilog.WriteToLog("in CreateRemoteDirectory Exception:" + ex.Message);
                return(-1);
            }
            //Wmilog.WriteToLog("建远程目录成功!");
            return(0);
        }
Exemplo n.º 3
0
        public bool Run(ManagementScope connection)
        {
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            ManagementPath   managementPath   = new ManagementPath("Win32_Process");

            using (ManagementClass processClass = new ManagementClass(connection, managementPath, objectGetOptions))
            {
                using (ManagementBaseObject inParams = processClass.GetMethodParameters("Create"))
                {
                    inParams["CommandLine"] = CommandLine;
                    using (ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null))
                    {
                        uint ret = (uint)outParams["returnValue"];
                        if (ret != 0)
                        {
                            throw new Exception("Error while starting process '" + CommandLine +
                                                "' creation returned an exit code of " + outParams["returnValue"]);
                        }

                        WriteInfo("Process executed", outParams["processId"].ToString(), ConsoleColor.Green);
                        return(true);
                    }
                }
            }
        }
Exemplo n.º 4
0
    public string LateralWMI(string command) // Based on SharpSploit
    {
        string            Username     = null;
        string            Password     = null;
        string            Command      = "ping 127.0.0.1";
        string            ComputerName = "127.0.0.1";
        ConnectionOptions options      = new ConnectionOptions();

        if ((Username != null && Username != "") && Password != null)
        {
            options.Username = Username;
            options.Password = Password;
        }

        ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", ComputerName), options);

        try
        {
            scope.Connect();
            var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());

            ManagementBaseObject   inParams   = wmiProcess.GetMethodParameters("Create");
            PropertyDataCollection properties = inParams.Properties;
            inParams["CommandLine"] = Command;
            ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null);
            return("WMI Success");
        }
        catch (Exception e)
        {
            return("WMI Exception:" + e.Message);
        }
    }
Exemplo n.º 5
0
        /*
         * static ManagementObject GetLastVirtualSystemSnapshot(ManagementObject vm)
         * {
         *  ManagementObjectCollection settings = vm.GetRelated(
         *      "Msvm_VirtualSystemsettingData",
         *      "Msvm_PreviousSettingData",
         *      null,
         *      null,
         *      "SettingData",
         *      "ManagedElement",
         *      false,
         *      null);
         *
         *  ManagementObject virtualSystemsetting = null;
         *  foreach (ManagementObject setting in settings)
         *  {
         *      Console.WriteLine(setting.Path.Path);
         *      Console.WriteLine(setting["ElementName"]);
         *      virtualSystemsetting = setting;
         *  }
         *
         *  return virtualSystemsetting;
         * }
         *
         * static void RemoveVirtualSystemSnapshot(string vmName)
         * {
         *  ManagementScope scope = new ManagementScope(@"root\virtualization\v2", null);
         *  ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
         *
         *  ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("RemoveVirtualSystemSnapshot");
         *
         *  ManagementObject vm = Utility.GetTargetComputer(vmName, scope);
         *
         *  ManagementObject vmSnapshot = GetLastVirtualSystemSnapshot(vm);
         *
         *  inParams["SnapshotSettingData"] = vmSnapshot.Path.Path;
         *
         *  ManagementBaseObject outParams = virtualSystemService.InvokeMethod("RemoveVirtualSystemSnapshot", inParams, null);
         *
         *  if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
         *  {
         *      if (Utility.JobCompleted(outParams, scope))
         *      {
         *          Console.WriteLine("Snapshot was removed successfully.");
         *
         *      }
         *      else
         *      {
         *          Console.WriteLine("Failed to remove snapshot VM");
         *      }
         *  }
         *  else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
         *  {
         *      Console.WriteLine(outParams["SnapshotsettingData"].ToString());
         *      Console.WriteLine("Snapshot was removed successfully.");
         *  }
         *  else
         *  {
         *      Console.WriteLine("Remove virtual system snapshot failed with error {0}", outParams["ReturnValue"]);
         *  }
         *
         *  inParams.Dispose();
         *  outParams.Dispose();
         *  vmSnapshot.Dispose();
         *  vm.Dispose();
         *  virtualSystemService.Dispose();
         * }*/
        #endregion

        #region Private methods

        private uint ChangeState(HyperVStatus state)
        {
            var raw   = AsRawMachine;
            var scope = AsRawMachine.Scope;

            var managementService = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemManagementService"), null)
                                    .GetInstances()
                                    .OfType <ManagementObject>().FirstOrDefault();

            if (managementService != null)
            {
                var inParameters = managementService.GetMethodParameters("RequestStateChange");

                inParameters["RequestedState"] = (object)state;

                var outParameters = raw.InvokeMethod("RequestStateChange", inParameters, null);
                if (outParameters != null)
                {
                    return((uint)outParameters["ReturnValue"]);
                }
            }
            else
            {
                throw new HyperVException("Could not find machine management service for rstate change");
            }

            return(0);
        }
Exemplo n.º 6
0
        public static int uninstallCB(string ComputerName)
        {
            int returnval   = -1;
            var commandLine = @"\\" + ComputerName + @"\admin$\CarbonBlack\uninst.exe /S";


            try
            {
                ConnectionOptions connOptions = new ConnectionOptions();
                connOptions.Impersonation    = ImpersonationLevel.Impersonate;
                connOptions.EnablePrivileges = true;
                ManagementScope manScope = new ManagementScope(string.Format(@"\\{0}\ROOT\CIMV2", ComputerName), connOptions);
                manScope.Connect();
                ObjectGetOptions     objectGetOptions = new ObjectGetOptions();
                ManagementPath       managementPath   = new ManagementPath("Win32_Process");
                ManagementClass      processClass     = new ManagementClass(manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
                inParams["CommandLine"] = commandLine;
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                Console.WriteLine("Creation of the process returned: " + outParams["returnValue"]);
                Console.WriteLine("Process ID: " + outParams["processId"]);
                returnval = Convert.ToInt32(outParams["processId"]);
            }
            catch
            {
            }
            return(returnval);
        }
Exemplo n.º 7
0
        public static ResourceRecord GetObjectByTextRepresentation(
            Server server,
            string dnsServerName,
            string containerName,
            string textRepresentation)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server is required");
            }

            ManagementClass      dnsRRClass = new ManagementClass(server.m_scope, new ManagementPath("MicrosoftDNS_ResourceRecord"), null);
            ManagementBaseObject inParams   = dnsRRClass.GetMethodParameters("GetObjectByTextRepresentation");

            inParams["DnsServerName"]      = dnsServerName;
            inParams["ContainerName"]      = containerName;
            inParams["TextRepresentation"] = textRepresentation;

            //return new ResourceRecord((ManagementObject)dnsRRClass.InvokeMethod("GetObjectByTextRepresentation", inParams, null));
            try
            {
                return(new ResourceRecord(new ManagementObject(server.m_scope, new ManagementPath(dnsRRClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null)["RR"].ToString()), null)));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
    private async Task <string> GetRegistryValue(string regKey, string valueName)
    {
        string value = null;
        await Task.Run(() =>
        {
            ManagementClass registry      = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
            ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue");

            inParams["hDefKey"]     = 0x80000002;
            inParams["sSubKeyName"] = regKey;
            inParams["sValueName"]  = valueName;

            ManagementBaseObject outParams = registry.InvokeMethod("GetStringValue", inParams, null);

            try
            {
                if (outParams.Properties["sValue"].Value != null)
                {
                    value = outParams.Properties["sValue"].Value.ToString();
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(value);
        });

        return(value);
    }
    private void SetRegistryValue(string keyPath, string valueName, string method, string keyValue = null)
    {
        try
        {
            ManagementClass      registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
            ManagementBaseObject inParams = registry.GetMethodParameters(method);

            if (keyValue != null)
            {
                inParams["hDefKey"]     = 0x80000002;
                inParams["sSubKeyName"] = keyPath;
                inParams["sValueName"]  = valueName;
                inParams["sValue"]      = keyValue;
            }
            else
            {
                inParams["hDefKey"]     = 0x80000002;
                inParams["sSubKeyName"] = keyPath;
                inParams["sValueName"]  = valueName;
            }

            var outParams = registry.InvokeMethod(method, inParams, null);
        }
        catch (Exception)
        {
        }
    }
 public static bool CreateRestorePoint(string description)
 {
     try
     {
         Logger.Log($"Creating restore point {description}...", Logger.LogType.INFO);
         var mScope  = new ManagementScope("\\\\localhost\\root\\default");
         var mPath   = new ManagementPath("SystemRestore");
         var options = new ObjectGetOptions();
         using (var mClass = new ManagementClass(mScope, mPath, options))
             using (var parameters = mClass.GetMethodParameters("CreateRestorePoint"))
             {
                 parameters["Description"]      = description;
                 parameters["EventType"]        = 0x66;
                 parameters["RestorePointType"] = 0xc;
                 mClass.InvokeMethod("CreateRestorePoint", parameters, null);
             }
         Logger.Log($"Created restore point {description}...", Logger.LogType.SUCCESS);
         return(true);
     }
     catch (Exception e)
     {
         Logger.Log($"Restore point create falied. Exception: {e.ToString()}", Logger.LogType.ERROR);
         return(false);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Runs the process.
        /// </summary>
        /// <param name="remoteCommand">The remote command.</param>
        /// <returns>System.Int32.</returns>
        public int RunProcess(string remoteCommand)
        {
            try
            {
                CDFMonitor.LogOutputHandler("Runprocess:enter:" + remoteCommand);

                var objectGetOptions          = new ObjectGetOptions();
                var managementPath            = new ManagementPath("Win32_Process");
                var processClass              = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
                inParams["CommandLine"] = remoteCommand;
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Creation of the process returned: " +
                                            outParams["returnValue"]);
                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Process ID: " + outParams["processId"]);

                return(Convert.ToInt32(outParams["processId"]));
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("Fail:Runprocess:exception:" + e.ToString());
                return(0);
            }
        }
Exemplo n.º 12
0
        private void launchButtonClicked(object sender, RoutedEventArgs e)
        {
            if (launchButton.IsEnabled == false)
            {
                return;
            }
            Settings    s = GlobalAppData.settings;
            String      executablePath = System.IO.Path.Combine(s.swgDirectory, s.executableName);
            GameProcess proc           = new GameProcess(executablePath);

            using (var managementClass = new ManagementClass("Win32_Process"))
            {
                var processInfo = new ManagementClass("Win32_ProcessStartup");
                processInfo.Properties["CreateFlags"].Value = 0x00000008;

                var inParameters = managementClass.GetMethodParameters("Create");
                inParameters["CommandLine"] = executablePath;
                inParameters["ProcessStartupInformation"] = processInfo;

                var result = managementClass.InvokeMethod("Create", inParameters, null);
                if ((result != null) && ((uint)result.Properties["ReturnValue"].Value != 0))
                {
                    Console.WriteLine("Process ID: {0}", result.Properties["ProcessId"].Value);
                }
            }
        }
        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}\\[WMINAMESPACE]", ComputerName), Conn);
                }
                else
                {
                    Scope = new ManagementScope(String.Format("\\\\{0}\\[WMINAMESPACE]", ComputerName), null);
                }

                Scope.Connect();
                ObjectGetOptions     Options       = new ObjectGetOptions();
                ManagementPath       Path          = new ManagementPath("[WMICLASSNAME]");
                ManagementClass      ClassInstance = new ManagementClass(Scope, Path, Options);
                ManagementBaseObject inParams      = ClassInstance.GetMethodParameters("[WMIMETHOD]");
Exemplo n.º 14
0
        private void Create()
        {
            if (this.Parameters == null)
            {
                this.Log.LogError("Parameters is required");
                return;
            }

            using (ManagementClass mgmtClass = new ManagementClass(this.Scope, new ManagementPath("Win32_Process"), null))
            {
                // Obtain in-parameters for the method
                ManagementBaseObject inParams = mgmtClass.GetMethodParameters("Create");
                if (this.Parameters != null)
                {
                    // Add the input parameters.
                    foreach (string[] data in this.Parameters.Select(param => param.ItemSpec.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
                    {
                        this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]));
                        inParams[data[0]] = data[1];
                    }
                }

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = mgmtClass.InvokeMethod("Create", inParams, null);
                if (outParams != null)
                {
                    this.ReturnValue = outParams["ReturnValue"].ToString();
                    this.ProcessId   = Convert.ToInt32(outParams["ProcessId"], CultureInfo.CurrentCulture);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Executes an instance method with parameters. Returns a dynamic object.
        /// </summary>
        /// <param name="obj">Instance which will be instanciated to call the method.</param>
        /// <param name="parameters">Anonymous object with properties matching the parameter names of the method.</param>
        /// <returns></returns>
        public static dynamic ExecuteMethod(object obj, dynamic parameters)
        {
            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

#if NET45
            WindowsImpersonationContext impersonatedUser = windowsIdentity.Impersonate();
#endif
#if NETSTANDARD20
            return WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () =>
#endif
            {
                var frame = new StackTrace().GetFrames().Skip(1).First(x => x.GetMethod().DeclaringType.Namespace != "System.Dynamic");

                string methodName = frame.GetMethod().Name;

                ManagementClass genericClass = new ManagementClass(TypeHelper.GetNamespace(obj), TypeHelper.GetClassName(obj), null);

                ManagementObject instance = TypeHelper.GetManagementObject(genericClass, obj);

                ManagementBaseObject inParams = genericClass.GetMethodParameters(methodName);

                foreach (PropertyInfo p in parameters.GetType().GetProperties())
                {
                    inParams[p.Name] = p.GetValue(parameters);
                }

                ManagementBaseObject result = instance.InvokeMethod(methodName, inParams, null);

                return result == null ? null : TypeHelper.LoadDynamicObject(result);
            }
#if NETSTANDARD20
                );
#endif
        }
Exemplo n.º 16
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表键值
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <param name="valueName">键值名称</param>
        /// <param name="value">键值</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteValue(ManagementScope connectionScope,
                                            string machineName,
                                            RootKey BaseKey,
                                            string key,
                                            string valueName,
                                            string value)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                                                                   new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("SetStringValue");

                methodParams["hDefKey"]     = BaseKey;
                methodParams["sSubKeyName"] = key;
                methodParams["sValue"]      = value;
                methodParams["sValueName"]  = valueName;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("SetStringValue",
                                                                          methodParams, null);

                //Wmilog.WriteToLog("in CreateRemoteValue:" + exitCode.ToString());
            }
            catch (ManagementException e)
            {
                //Wmilog.WriteToLog("in CreateRemoteValue(ManagementException):" + e.Message);
                return(-1);
            }
            //Wmilog.WriteToLog("注册表键值写入成功!");
            return(0);
        }
Exemplo n.º 17
0
 private void resetToolStripMenuItem_Click(object sender, EventArgs e)
 {
     //Если флаг установлен, то перезагрузка уже инициирована
     if (fReset)
     {
         return;
     }
     fReset = true;
     if (wdt.isWDT)
     {
         timer2.Stop();
         wdt.SetWDT(1);
         toolStripProgressBar1.Value = 0;
         pbTT.SetToolTip(this.statusStrip1, "WDT reset computer after 1 min.");
     }
     else
     {
         ManagementBaseObject mboReboot = null;
         ManagementClass      mcWin32   = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get();
         // You can't shutdown without security privileges
         mcWin32.Scope.Options.EnablePrivileges = true;
         ManagementBaseObject mboRebootParams = mcWin32.GetMethodParameters("Win32Shutdown");
         // Flags: - 0 (0x0) Log Off - 4 (0x4) Forced Log Off (0 4) - 1 (0x1) Shutdown - 5 (0x5) Forced Shutdown (1 4) - 2 (0x2) Reboot
         // - 6 (0x6) Forced Reboot (2 4) - 8 (0x8) Power Off - 12 (0xC) Forced Power Off (8 4)
         mboRebootParams["Flags"]    = "6";
         mboRebootParams["Reserved"] = "0";
         foreach (ManagementObject manObj in mcWin32.GetInstances())
         {
             mboReboot = manObj.InvokeMethod("Win32Shutdown", mboRebootParams, null);
         }
     }
 }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            string folderName = @"C:\MyTestShare";
            string shareName  = @"My Files Share";

            try
            {
                // Создаем объект ManagementClass
                ManagementClass managementClass =
                    new ManagementClass("Win32_Share");
                // Создаем объект ManagementBaseObjects
                ManagementBaseObject inParams =
                    managementClass.GetMethodParameters("Create");
                ManagementBaseObject outParams;
                // Задаем параметры вызова
                inParams["Description"] = shareName;
                inParams["Name"]        = shareName;
                inParams["Path"]        = folderName;
                inParams["Type"]        = 0x0;          // Disk Drive
                // Вызываем метод Create
                outParams = managementClass.InvokeMethod(
                    "Create", inParams, null);
                // Проверяем результат
                if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                {
                    throw new Exception("Ну удалось сделать каталог общим.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Retrieve String value from registry path.
        /// </summary>
        /// <param name="wmiRegistry">Management Object</param>
        /// <param name="keyPath">Registry Path</param>
        /// <param name="keyName">Key Name</param>
        /// <param name="stringValue">Key Value</param>
        /// <returns></returns>
        private ResultCodes getRegistryStringValue(
            ManagementClass wmiRegistry,
            string keyPath,
            string keyName,
            out string stringValue)
        {
            ManagementBaseObject inputParameters = wmiRegistry.GetMethodParameters(RegistryMethodNames.GET_MULTI_STRING_VALUE);

            inputParameters.SetPropertyValue(RegistryPropertyNames.DEF_KEY, RegistryTrees.HKEY_LOCAL_MACHINE);
            inputParameters.SetPropertyValue(RegistryPropertyNames.SUB_KEY_NAME, keyPath);
            inputParameters.SetPropertyValue(RegistryPropertyNames.VALUE_NAME, keyName);

            ManagementBaseObject outputParameters = null;

            stringValue = null;
            ResultCodes resultCode = Lib.InvokeRegistryMethod(m_taskId,
                                                              wmiRegistry,
                                                              RegistryMethodNames.GET_STRING_VALUE,
                                                              keyPath,
                                                              inputParameters,
                                                              out outputParameters);

            if (resultCode == ResultCodes.RC_SUCCESS && null != outputParameters)
            {
                using (outputParameters) {
                    stringValue = outputParameters.GetPropertyValue(RegistryPropertyNames.S_VALUE) as string;
                }
            }
            return(resultCode);
        }
Exemplo n.º 20
0
        public bool shareFolder(string FolderPath, string ShareName, string Description)
        {
            // 创建共享目录            
            try
            {
                ManagementClass      managementClass = new ManagementClass("Win32_Share");
                ManagementBaseObject inParams        = managementClass.GetMethodParameters("Create");
                ManagementBaseObject outParams;
                inParams["Description"] = Description;
                inParams["Name"]        = ShareName;
                inParams["Path"]        = FolderPath;
                inParams["Type"]        = 0x0;
                outParams = managementClass.InvokeMethod("Create", inParams, null);

                if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                {
                    return(false);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
    private string GetRegistryBaseKey(string parentKey, string childKey, string getmethParam)
    {
        ManagementClass      registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
        ManagementBaseObject inParams = registry.GetMethodParameters(getmethParam);

        inParams["hDefKey"]     = 0x80000002;
        inParams["sSubKeyName"] = parentKey;

        ManagementBaseObject outParams = registry.InvokeMethod(getmethParam, inParams, null);

        try
        {
            var subKeyNames = (String[])outParams.Properties["sNames"].Value;

            foreach (var key in subKeyNames)
            {
                if (key == childKey)
                {
                    return(key);
                }
            }
        }
        catch (Exception)
        {
            return(null);
        }


        return(null);
    }
Exemplo n.º 22
0
        public static void Restart()
        {
            _cw("Asked for reboot");
            _cw("Rebooting...");
            var mcWin32 = new ManagementClass("Win32_OperatingSystem");

            mcWin32.Get();

            Console.WriteLine(!TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true)
                                  ? "Could not enable SeShutdownPrivilege"
                                  : "Enabled SeShutdownPrivilege");

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            var mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system
            mboShutdownParams["Flags"]    = "6";
            mboShutdownParams["Reserved"] = "0";

            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                try
                {
                    manObj.InvokeMethod("Win32Shutdown",
                                        mboShutdownParams, null);
                }
                catch (ManagementException mex)
                {
                    Console.WriteLine(mex.ToString());
                    Console.ReadKey();
                }
            }
        }
Exemplo n.º 23
0
        public override uint Create(string Name, string DisplayName, string PathName, ushort ServiceType, byte ErrorControl, string StartMode,
                                    bool DesktopInteract, string StartName, string StartPassword, string LoadOrderGroup, string[] LoadOrderGroupDependencies,
                                    string[] ServiceDependencies)
        {
            byte b = 0;

            if (ServiceType != 256)
            {
                b = byte.Parse(ServiceType.ToString());
            }

            ManagementClass      processClass = wmi.GetManagementClass("Win32_Service");
            ManagementBaseObject inbo         = processClass.GetMethodParameters("Create");

            inbo["Name"]                       = Name;
            inbo["DisplayName"]                = DisplayName;
            inbo["PathName"]                   = PathName;
            inbo["ServiceType"]                = b;
            inbo["ErrorControl"]               = ErrorControl;
            inbo["StartMode"]                  = StartMode;
            inbo["DesktopInteract"]            = DesktopInteract;
            inbo["StartName"]                  = StartName;
            inbo["StartPassword"]              = StartPassword;
            inbo["LoadOrderGroup"]             = LoadOrderGroup;
            inbo["LoadOrderGroupDependencies"] = LoadOrderGroupDependencies;
            inbo["ServiceDependencies"]        = ServiceDependencies;

            ManagementBaseObject outbo = processClass.InvokeMethod("Create", inbo, null);
            uint a = (uint)outbo["ReturnValue"];

            return(a);
        }
Exemplo n.º 24
0
        private void RemoveAssembly()
        {
            if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
            {
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "UnGAC Assembly: {0}", this.AssemblyName));
                this.Uninstall(this.AssemblyName);
            }
            else
            {
                this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "UnGAC Assembly: {0} on Remote Server: {1}", this.AssemblyName, this.MachineName));
                this.GetManagementScope(@"\root\cimv2");
                using (ManagementClass m = new ManagementClass(this.Scope, new ManagementPath("Win32_Process"), new ObjectGetOptions(null, System.TimeSpan.MaxValue, true)))
                {
                    ManagementBaseObject methodParameters = m.GetMethodParameters("Create");
                    methodParameters["CommandLine"] = @"gacutil.exe /u " + "\"" + this.AssemblyName + "\"";
                    ManagementBaseObject outParams = m.InvokeMethod("Create", methodParameters, null);

                    if (outParams != null)
                    {
                        this.LogTaskMessage(MessageImportance.Low, "Process returned: " + outParams["returnValue"]);
                        this.LogTaskMessage(MessageImportance.Low, "Process ID: " + outParams["processId"]);
                    }
                    else
                    {
                        this.Log.LogError("Remote Remove returned null");
                    }
                }
            }
        }
Exemplo n.º 25
0
        private void ExecuteWmi()
        {
            this.GetManagementScope(this.Namespace);
            string managementPath = this.Class;

            if (!string.IsNullOrEmpty(this.Instance))
            {
                managementPath += "." + this.Instance;

                using (var classInstance = new ManagementObject(this.Scope, new ManagementPath(managementPath), null))
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = classInstance.GetMethodParameters(this.Method);
                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Method: {0}", this.Method));

                    if (this.MethodParameters != null)
                    {
                        // Add the input parameters.
                        foreach (string[] data in this.MethodParameters.Select(param => param.ItemSpec.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
                        {
                            this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]));
                            inParams[data[0]] = data[1];
                        }
                    }

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = classInstance.InvokeMethod(this.Method, inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue = outParams["ReturnValue"].ToString();
                    }
                }
            }
            else
            {
                using (ManagementClass mgmtClass = new ManagementClass(this.Scope, new ManagementPath(managementPath), null))
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = mgmtClass.GetMethodParameters(this.Method);
                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Method: {0}", this.Method));

                    if (this.MethodParameters != null)
                    {
                        // Add the input parameters.
                        foreach (string[] data in this.MethodParameters.Select(param => param.ItemSpec.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
                        {
                            this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]));
                            inParams[data[0]] = data[1];
                        }
                    }

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = mgmtClass.InvokeMethod(this.Method, inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue = outParams["ReturnValue"].ToString();
                    }
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="delUserName">要删除的用户名</param>
        /// <returns>是否成功</returns>
        public bool DelUserByCmd(string delUserName)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Username = UserName;
                options.Password = PassWord;

                ManagementScope Conn = new ManagementScope(@"\\" + IP + @"\root\cimv2", options);
                Conn.Connect();

                ManagementPath  path         = new ManagementPath("Win32_Process");
                ManagementClass processClass = new ManagementClass(Conn, path, null);

                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

                inParams["CommandLine"] = "net user " + delUserName + " /delete";

                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 27
0
        public static RegType GetValueType(ManagementClass mc, uint hDefKey, string sSubKeyName, string sValueName)
        {
            ManagementBaseObject inParams = mc.GetMethodParameters("EnumValues");

            inParams["hDefKey"]     = hDefKey;
            inParams["sSubKeyName"] = sSubKeyName;

            ManagementBaseObject outParams = mc.InvokeMethod("EnumValues", inParams, null);

            if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
            {
                string[] sNames = outParams["sNames"] as String[];
                int[]    iTypes = outParams["Types"] as int[];

                for (int i = 0; i < sNames.Length; i++)
                {
                    if (sNames[i] == sValueName)
                    {
                        return((RegType)iTypes[i]);
                    }
                }
                // value not found
                return((RegType)1);
            }
            else
            {
                return((RegType)0);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// 修改帐号密码
        /// </summary>
        /// <param name="changeUserName">要修改的帐号</param>
        /// <param name="changePassWord">修改后的密码</param>
        /// <returns>是否成功</returns>
        public bool ChangePassWordByCmd(string changeUserName, string changePassWord)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Username = UserName;
                options.Password = PassWord;

                ManagementScope Conn = new ManagementScope(@"\\" + IP + @"\root\cimv2", options);
                Conn.Connect();

                ManagementPath  path         = new ManagementPath("Win32_Process");
                ManagementClass processClass = new ManagementClass(Conn, path, null);

                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

                //Parameters for creation of process.
                inParams["CommandLine"] = "net user " + changeUserName + " " + changePassWord + "";

                //Invoke Method.
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                return(true);
            }
            //报错
            catch (Exception ee)
            {
                return(false);
            }
        }
Exemplo n.º 29
0
        public void RestoreLastSnapShot()
        {
            var raw   = AsRawMachine;
            var scope = AsRawMachine.Scope;

            var lastSnapshot = raw.GetRelated(
                "Msvm_VirtualSystemSettingData",
                "Msvm_MostCurrentSnapshotInBranch",
                null,
                null,
                "Dependent",
                "Antecedent",
                false,
                null).OfType <ManagementObject>().FirstOrDefault();

            if (lastSnapshot == null)
            {
                throw new HyperVException("No Snapshot found");
            }

            var managementService = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemSnapshotService"), null).GetInstances().OfType <ManagementObject>().FirstOrDefault();

            var inParameters = managementService.GetMethodParameters("ApplySnapshot");

            inParameters["Snapshot"] = lastSnapshot.Path.Path;

            var outParameters = managementService.InvokeMethod("ApplySnapshot", inParameters, null);
        }
Exemplo n.º 30
0
        private void PowerControl(string flag)
        {
#pragma warning disable IDE0067 // 丢失范围之前释放对象
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
#pragma warning restore IDE0067 // 丢失范围之前释放对象
            try
            {
                mcWin32.Get();

                mcWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

                //"0" 注销 "1" 关机, "2" 重启 "8" 关闭计算机电源
                mboShutdownParams["Flags"]    = flag;
                mboShutdownParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    ManagementBaseObject mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mcWin32.Dispose();
            }
        }
    public async Task RunOfficeUpdateAsync(string version)
    {
        await Task.Run(async () => {
            try
            {
                var c2RPath = GetOfficeC2RPath() + @"\OfficeC2RClient.exe /update user displaylevel=false forceappshutdown=true updatepromptuser=false updatetoversion=" + version;
                var mainRegKey = GetOfficeCtrRegPath().Result;
                var c2rExe = new[] { c2RPath };
                var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create");
                inParams["CommandLine"] = c2RPath;

                await Task.Run(() => { return wmiProcess.InvokeMethod("Create", inParams, null); });

                Thread.Sleep(1000);

                var executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result;

                while(executingScenario != null)
                {
                    Thread.Sleep(1000);
                    executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result;
                }


                var updateStatus = GetRegistryValue(mainRegKey, "LastScenarioResult").Result;

                if(updateStatus != "Success")
                {
                    throw (new Exception("Channel/version change was not successful"));
                }

            }
            catch(Exception ex)
            {
                throw (new Exception(ex.Message));
            }
        });
    }
    private async void CreateRegistryValue(string regKey, string valueName, string value)
    {
      
            await Task.Run(() =>
            {
                


                    ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
                    ManagementBaseObject inParams = registry.GetMethodParameters("SetDWORDValue");

                    inParams["hDefKey"] = 0x80000002;
                    inParams["sSubKeyName"] = regKey;
                    inParams["sValueName"] = valueName;

                    ManagementBaseObject outParams = registry.InvokeMethod("SetDWORDValue", inParams, null);
                
            });

    }
    private async  Task<string> GetRegistryValue(string regKey, string valueName)
    {
        string value = null;
        await Task.Run(() =>
        {
            ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
            ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue");

            inParams["hDefKey"] = 0x80000002;
            inParams["sSubKeyName"] = regKey;
            inParams["sValueName"] = valueName;

            ManagementBaseObject outParams = registry.InvokeMethod("GetStringValue", inParams, null);

            try
            {
                if (outParams.Properties["sValue"].Value != null)
                {
                    value = outParams.Properties["sValue"].Value.ToString();
                }
            }
            catch (Exception)
            {
                return null;
            }
            return value;

        });

        return value;

    }
    private void SetRegistryValue(string keyPath, string valueName, string method, string keyValue = null)
    {
        try
        {

     
        ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
        ManagementBaseObject inParams = registry.GetMethodParameters(method);

        if(keyValue != null)
        {
            inParams["hDefKey"] = 0x80000002;
            inParams["sSubKeyName"] = keyPath;
            inParams["sValueName"] = valueName;
            inParams["sValue"] = keyValue;
        }
        else
        {
            inParams["hDefKey"] = 0x80000002;
            inParams["sSubKeyName"] = keyPath;
            inParams["sValueName"] = valueName;
        }

        var outParams = registry.InvokeMethod(method, inParams,null);
        }
        catch (Exception)
        {

        }



    }
    private string GetRegistryBaseKey(string parentKey, string childKey, string getmethParam)
    {
       
            ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
            ManagementBaseObject inParams = registry.GetMethodParameters(getmethParam);

            inParams["hDefKey"] = 0x80000002;
            inParams["sSubKeyName"] = parentKey;

            ManagementBaseObject outParams = registry.InvokeMethod(getmethParam, inParams, null);

            try
            {
                var subKeyNames = (String[])outParams.Properties["sNames"].Value;

                foreach (var key in subKeyNames)
                {
                    if (key == childKey)                    {
                        return key;
                    }
                }


            }
            catch (Exception)
            {
                return null;
            }
       

            return null;
    
    }