コード例 #1
2
ファイル: WmiProcess.cs プロジェクト: davidduffett/dropkick
        //private char NULL_VALUE = char(0);
        public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory)
        {
            var connOptions = new ConnectionOptions
                                  {
                                      EnablePrivileges = true
                                  };

            var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions);
            scope.Connect();
            var managementPath = new ManagementPath(CLASSNAME);
            using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions()))
            {
                var inParams = processClass.GetMethodParameters("Create");
                commandLine = System.IO.Path.Combine(currentDirectory, commandLine);
                inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args);

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

                var rtn = Convert.ToUInt32(outParams["returnValue"]);
                var pid = Convert.ToUInt32(outParams["processId"]);
                if (pid != 0)
                {
                    WaitForPidToDie(machineName, pid);
                }

                return (ProcessReturnCode)rtn;
            }
        }
コード例 #2
0
ファイル: WmiSpecs.cs プロジェクト: GorelH/dropkick
        public void Bob()
        {
            var connOptions = new ConnectionOptions
                                  {
                                      EnablePrivileges = true,
                                      //Username = "******",
                                      //Password = "******"
                                  };

            string server = "SrvTestWeb01";
            ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", server), connOptions);
            manScope.Connect();
            

            var managementPath = new ManagementPath("Win32_Process");
            var processClass = new ManagementClass(manScope, managementPath, new ObjectGetOptions());

            var inParams = processClass.GetMethodParameters("Create");
            inParams["CommandLine"] = @"C:\Temp\dropkick.remote\dropkick.remote.exe create_queue msmq://localhost/dk_test";

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

            var rtn = System.Convert.ToUInt32(outParams["returnValue"]);
            var processID = System.Convert.ToUInt32(outParams["processId"]);
        }
コード例 #3
0
        public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName)
        {
            /*ConnectionOptions connOptions = new ConnectionOptions();
            connOptions.Impersonation = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            connOptions.Username = "******";
            connOptions.Password = "******";
            */
            ManagementScope scope =
               new ManagementScope(@"\\" + dnsServerName + "\\root\\MicrosoftDNS"); //,connOptions);

            scope.Connect();

            ManagementClass wmiClass =
               new ManagementClass(scope,
                                   new ManagementPath("MicrosoftDNS_AType"),
                                   null);

            ManagementBaseObject inParams =
                wmiClass.GetMethodParameters("CreateInstanceFromPropertyData");

            inParams["DnsServerName"] = dnsServerName;
            inParams["ContainerName"] = zone;
            inParams["OwnerName"] = hostName + "." + zone;
            inParams["IPAddress"] = iPAddress;

            wmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null);
        }
コード例 #4
0
        private bool SendCommand(string command, string username, string password)
        {
            Logger.EnteringMethod(command);
            try
            {
                ConnectionOptions connectoptions = new ConnectionOptions();
                if (username != null && password != null && this.Name.ToLower() != GetFullyQualifiedDomainName().ToLower())
                {
                    connectoptions.Username = username;
                    connectoptions.Password = password;
                }
                connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

                System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", this.Name), connectoptions);
                mgmtScope.Connect();
                System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
                System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
                System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
                System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
                ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");
                startupInfo.Properties["ShowWindow"].Value = 0;

                inParams["CommandLine"] = command;
                inParams["ProcessStartupInformation"] = startupInfo;

                processClass.InvokeMethod("Create", inParams, null);
                Logger.Write("Command Sent Successfuly on : " + this.Name);
            }
            catch (Exception ex)
            {
                Logger.Write("**** " + ex.Message);
                return(false);
            }
            return(true);
        }
コード例 #5
0
        private static void ReportNow()
        {
            Logger.Write("Sending ReportNow.");
            try
            {
                ConnectionOptions connectoptions = new ConnectionOptions();

                System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(@"\\.\ROOT\CIMV2", connectoptions);
                mgmtScope.Connect();
                System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
                System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
                System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
                System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
                ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");
                startupInfo.Properties["ShowWindow"].Value = 0;

                inParams["CommandLine"] = "WuAuClt.exe /ReportNow";
                inParams["ProcessStartupInformation"] = startupInfo;

                processClass.InvokeMethod("Create", inParams, null);
            }
            catch (Exception ex)
            {
                Logger.Write("Problem when doing ReportNow. " + ex.Message);
            }
            Logger.Write("ReportNow done.");
        }
コード例 #6
0
        /// <summary>
        /// Creates the share.
        /// </summary>
        /// <param name="shareName">Name of the share.</param>
        /// <param name="folderPath">The folder path.</param>
        /// <returns>WindwsShare instance.</returns>
        public static WindowsShare CreateShare(string shareName, string folderPath)
        {
            ManagementClass shareClass = null;
            ManagementClass sd = null;
            ManagementBaseObject inParams = null;
            ManagementBaseObject outParams = null;

            try
            {
                sd = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);

                sd["ControlFlags"] = 0x4;
                sd["DACL"] = new ManagementBaseObject[] { };

                shareClass = new ManagementClass("Win32_Share");

                inParams = shareClass.GetMethodParameters("Create");
                inParams["Name"] = shareName;
                inParams["Path"] = new DirectoryInfo(folderPath).FullName;
                //// inParams["Description"] = description;
                inParams["Type"] = 0x0;  // Type of Disk Drive
                inParams["Access"] = sd;

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

                if ((uint)outParams["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to create share. Win32_Share.Create Error Code: " + outParams["ReturnValue"]);
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to create share", ex);
            }
            finally
            {
                if (shareClass != null)
                {
                    shareClass.Dispose();
                }

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

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

                if (sd != null)
                {
                    sd.Dispose();
                }
            }

            return new WindowsShare(shareName);
        }
コード例 #7
0
ファイル: wmi.cs プロジェクト: rogerlio/csharp-proj
 public static void ExportReg(string RegKey, string SavePath, string ServerName)
 {
     string path = "\"" + SavePath + "\"";
     string key = "\"" + RegKey + "\"";
     object[] theProcessToRun = { "regedit.exe /e " + path + " " + key + "" };
     ManagementClass mClass = new ManagementClass(@"\\" + ServerName + @"\root\cimv2:Win32_Process");
     mClass.InvokeMethod("Create", theProcessToRun);
 }
コード例 #8
0
ファイル: ProcessMethod.cs プロジェクト: oblivious/Oblivious
 public static string StartProcess(string machineName, string processPath)
 {
     ManagementClass processTask = new ManagementClass(@"\\" + machineName + @"\root\CIMV2", 
                                                                     "Win32_Process", null);
     ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");
     methodParams["CommandLine"] = processPath;
     ManagementBaseObject exitCode = processTask.InvokeMethod("Create", methodParams, null);
     return ProcessMethod.TranslateProcessStartExitCode(exitCode["ReturnValue"].ToString());
 }
コード例 #9
0
        public override void Execute(object context = null)
        {
            ActionsHomeModel pc = context as ActionsHomeModel;
            //Can only be processed if the machine is online...
            if (pc.Status == ComputerStates.Online || pc.Status == ComputerStates.LoggedOn)
            {
                ManagementScope oMs = ConnectToClient(pc.Name);
                if (oMs != null)
                {
                    this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_SoftwareDistribution");
                    this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_Scheduler_ScheduledMessage");
                    this.DeleteQueryData(oMs, @"root\ccm\Scheduler", "SELECT * FROM CCM_Scheduler_History");

                    //oMs.Path.NamespacePath = @"ROOT\CCM";
                    ManagementClass oClass = new ManagementClass(oMs, new ManagementPath("SMS_Client"), null);
                    oClass.Get();
                    ManagementBaseObject inParams = oClass.GetMethodParameters("ResetPolicy");
                    inParams["uFlags"] = 1;
                    oClass.InvokeMethod("ResetPolicy", inParams, new InvokeMethodOptions());

                    ManagementBaseObject newParams = oClass.GetMethodParameters("RequestMachinePolicy");
                    oClass.InvokeMethod("RequestMachinePolicy", newParams, new InvokeMethodOptions());

                    App.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.State = RemoteActionState.Completed;
                    }), null);
                }
                else
                {
                    App.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.State = RemoteActionState.Error;
                    }), null);
                }
            }
            else
            {
                App.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.State = RemoteActionState.Pending;
                }), null);
            }
        }
コード例 #10
0
ファイル: RemoteExecForm.cs プロジェクト: mind0n/hive
 private void RemoteExec()
 {
     var processToRun = new[] { "notepad.exe" };
     var connection = new ConnectionOptions();
     connection.Username = "******";
     connection.Password = "******";
     connection.Authentication = AuthenticationLevel.Connect;
     var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "192.168.9.101"), connection);
     var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
     wmiProcess.InvokeMethod("Create", processToRun);
 }
コード例 #11
0
ファイル: RemoteExecuteCommand.cs プロジェクト: mind0n/hive
		public object RemoteExecute(string command)
		{
			object[] theProcessToRun = { command };
			ConnectionOptions theConnection = new ConnectionOptions();
			theConnection.Timeout = TimeSpan.FromSeconds(Timeout_Second);
			theConnection.Username = CommandExecutionContext.Instance.CurrentMachine.DomainUsername;
			theConnection.Password = CommandExecutionContext.Instance.CurrentMachine.Password;
			ManagementScope theScope = new ManagementScope("\\\\" + CommandExecutionContext.Instance.CurrentMachine.Address + "\\root\\cimv2", theConnection);
			ManagementClass theClass = new ManagementClass(theScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
			object rlt = theClass.InvokeMethod("Create", theProcessToRun);
			return rlt;
		}
コード例 #12
0
ファイル: RegistryMethod.cs プロジェクト: cpm2710/cellbank
        public static void CreateKey(ManagementScope connectionScope,
            baseKey BaseKey,
            string key)
        {
            ManagementClass registryTask = new ManagementClass(connectionScope,
                           new ManagementPath("DEFAULT:StdRegProv"), new ObjectGetOptions());
            ManagementBaseObject methodParams = registryTask.GetMethodParameters("CreateKey");

            methodParams["hDefKey"] = BaseKey;
            methodParams["sSubKeyName"] = key;

            ManagementBaseObject exitCode = registryTask.InvokeMethod("CreateKey",
                                                                        methodParams, null);
        }
コード例 #13
0
        public ManagementBaseObject RunCommand(Dictionary<string, string> inArgs)
        {
            // WMI: Use Win32_Process in root\cimv2 namespace.
            var processClass = new ManagementClass(
                new ManagementScope(String.Format(@"\\{0}\root\cimv2", this.hostName), this.connectionOptions),
                new ManagementPath("Win32_Process"),
                new ObjectGetOptions());
            ManagementBaseObject parameters = processClass.GetMethodParameters("Create");

            foreach (var item in inArgs)
            {
                parameters[item.Key] = item.Value;
            }

            return processClass.InvokeMethod("Create", parameters, null);
        }
コード例 #14
0
        public static bool DeleteSystemStore()
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams  = null;
                System.Management.ManagementPath       mgmtPath  = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj  = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("DeleteSystemStore", inParams, null);
                return(System.Convert.ToBoolean(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToBoolean(0));
            }
        }
コード例 #15
0
ファイル: WmiHelper.cs プロジェクト: domitienda/DomiLibrary
        /// <summary>
        /// Invoca un comando en un servidor remotamente.
        /// </summary>
        /// <param name="ipServer"></param>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public static string InvokeRemoteCommand(string ipServer, string user, string password, string command)
        {
            try
            {
                var processToRun = new[] { command };
                var connection = new ConnectionOptions { Username = user, Password = password };
                var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", ipServer), connection);
                var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                var result = wmiProcess.InvokeMethod("Create", processToRun);

                return result.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #16
0
ファイル: RegistryMethod.cs プロジェクト: oblivious/Oblivious
        public static string[] EnumerateKeys(ManagementScope connectionScope,
                                             baseKey BaseKey,
                                             string key)
        {
            ManagementClass registryTask = new ManagementClass(connectionScope,
                           new ManagementPath("DEFAULT:StdRegProv"), new ObjectGetOptions());
            ManagementBaseObject methodParams = registryTask.GetMethodParameters("EnumKey");

            methodParams["hDefKey"] = BaseKey;
            methodParams["sSubKeyName"] = key;

            ManagementBaseObject exitCode = registryTask.InvokeMethod("EnumKey",
                                                        methodParams, null);
            System.String[] subKeys;
            subKeys = (string[])exitCode["sNames"];
            return subKeys;
        }
コード例 #17
0
ファイル: SystemRestore.cs プロジェクト: gtrant/eraser
        public static uint GetLastRestoreStatus()
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams  = null;
                System.Management.ManagementPath       mgmtPath  = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj  = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("GetLastRestoreStatus", inParams, null);
                return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToUInt32(0));
            }
        }
コード例 #18
0
        /*
         *Method that execute a WMI command on a remote computer and return all the profile folders' name
         * in an arraylist
         */
        public static ArrayList getProfile(string computername)
        {
            //List to store the user profiles
            ArrayList profileList = new ArrayList();

            //Line of the file written on the client
            string line;

            ConnectionOptions connOptions = new ConnectionOptions();
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            ManagementPath managementPath = new ManagementPath("Win32_Process");

            //To use caller credential
            connOptions.Impersonation = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions);
            manScope.Connect();
            InvokeMethodOptions methodOptions = new InvokeMethodOptions(null, System.TimeSpan.MaxValue);
            ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

            //The command to execute to get the profile folder and write the result to C:\\tmp.txt
            inParams["CommandLine"] = "cmd /c " + "dir C:\\Users /B" + " > c:\\tmp.txt";
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams,methodOptions);

            //Arbitratry delay to make sure that the command is done
            Thread.Sleep(2000);

            //Reading the result file
            StreamReader sr = new StreamReader("\\\\" + computername + "\\c$\\tmp.txt");
            line = sr.ReadLine();

            //While there are profile
            while (line != null)
            {
              //Add the profile to the arraylist
              profileList.Add(line);
              line = sr.ReadLine();

            }

            sr.Close();

            return profileList;
        }
コード例 #19
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Management.ConnectionOptions connOptions =
                new System.Management.ConnectionOptions();

            connOptions.Impersonation    = System.Management.ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            connOptions.Username         = "******";
            connOptions.Password         = "******";

            string compName = "chan-PC";

            System.Management.ManagementScope manScope =
                new System.Management.ManagementScope(
                    String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions);
            manScope.Connect();

            System.Management.ObjectGetOptions objectGetOptions =
                new System.Management.ObjectGetOptions();

            System.Management.ManagementPath managementPath =
                new System.Management.ManagementPath("Win32_Process");

            System.Management.ManagementClass processClass =
                new System.Management.ManagementClass(manScope, managementPath, objectGetOptions);

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

            inParams["CommandLine"] = @"c:\MalCode\hiWinForm.exe";

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

            var returnvalue = outParams["returnValue"];

            if (outParams["returnValue"].ToString().Equals("0"))
            {
                MessageBox.Show("Process execution returned " + unchecked ((int)outParams["returnValue"]));
            }
            else
            {
                MessageBox.Show("No type specified " + unchecked ((int)outParams["returnValue"]));
            }
        }
コード例 #20
0
ファイル: SystemRestore.cs プロジェクト: gtrant/eraser
        public static uint Disable(string Drive)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath       mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams          = classObj.GetMethodParameters("Disable");
                inParams["Drive"] = ((System.String)(Drive));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Disable", inParams, null);
                return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToUInt32(0));
            }
        }
コード例 #21
0
ファイル: SystemRestore.cs プロジェクト: gtrant/eraser
        public static uint Restore(uint SequenceNumber)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath       mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams = classObj.GetMethodParameters("Restore");
                inParams["SequenceNumber"] = ((System.UInt32)(SequenceNumber));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Restore", inParams, null);
                return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToUInt32(0));
            }
        }
コード例 #22
0
        public static bool GetSystemPartition(out string Partition)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams  = null;
                System.Management.ManagementPath       mgmtPath  = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj  = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("GetSystemPartition", inParams, null);
                Partition = System.Convert.ToString(outParams.Properties["Partition"].Value);
                return(System.Convert.ToBoolean(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                Partition = null;
                return(System.Convert.ToBoolean(0));
            }
        }
コード例 #23
0
        public static bool ImportStore(string File)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath       mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams         = classObj.GetMethodParameters("ImportStore");
                inParams["File"] = ((System.String)(File));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("ImportStore", inParams, null);
                return(System.Convert.ToBoolean(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToBoolean(0));
            }
        }
コード例 #24
0
ファイル: ShareFolder.cs プロジェクト: jwsmith41/TAFlashShare
 internal int ShareCreate(string ShareName, string FolderPath, string Description)
 {
     ManagementClass mgmtClass = new ManagementClass("Win32_Share");
     ManagementBaseObject inParams = mgmtClass.GetMethodParameters("Create");
     ManagementBaseObject outParams;
     inParams["Description"] = Description;
     inParams["Name"] = ShareName;
     inParams["Path"] = FolderPath;
     inParams["Type"] = 0x0; //disk drive
     inParams["Access"] = SecurityDescriptor();  //for Everyone full perms
     outParams = mgmtClass.InvokeMethod("Create", inParams, null);
     if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
     {
         string errCode = Enum.GetName(typeof(shareCreateErrorCodes), outParams.Properties["ReturnValue"].Value);
         MessageBox.Show(String.Format("Unable to create a network share. The error message was {0}\n\nShareName = {1}\nFolderPath = {2}", errCode, ShareName, FolderPath) );
         return 1;
     }
     else return 0;
 }
コード例 #25
0
ファイル: Applications.cs プロジェクト: pengyancai/cs-util
 /// <summary>
 /// Loads applications
 /// </summary>
 /// <param name="Name">Computer name</param>
 /// <param name="UserName">User name</param>
 /// <param name="Password">Password</param>
 private void LoadApplications(string Name, string UserName, string Password)
 {
     ApplicationList = new List<Application>();
     ManagementScope Scope = null;
     if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
     {
         ConnectionOptions Options = new ConnectionOptions();
         Options.Username = UserName;
         Options.Password = Password;
         Scope = new ManagementScope("\\\\" + Name + "\\root\\default", Options);
     }
     else
     {
         Scope = new ManagementScope("\\\\" + Name + "\\root\\default");
     }
     ManagementPath Path = new ManagementPath("StdRegProv");
     using (ManagementClass Registry = new ManagementClass(Scope, Path, null))
     {
         const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
         object[] Args = new object[] { HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", null };
         uint MethodValue = (uint)Registry.InvokeMethod("EnumKey", Args);
         string[] Keys = Args[2] as String[];
         using (ManagementBaseObject MethodParams = Registry.GetMethodParameters("GetStringValue"))
         {
             MethodParams["hDefKey"] = HKEY_LOCAL_MACHINE;
             foreach (string SubKey in Keys)
             {
                 MethodParams["sSubKeyName"] = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + SubKey;
                 MethodParams["sValueName"] = "DisplayName";
                 using (ManagementBaseObject Results = Registry.InvokeMethod("GetStringValue", MethodParams, null))
                 {
                     if (Results != null && (uint)Results["ReturnValue"] == 0)
                     {
                         Application Temp = new Application();
                         Temp.Name = Results["sValue"].ToString();
                         ApplicationList.Add(Temp);
                     }
                 }
             }
         }
     }
 }
コード例 #26
0
        private void Execute()
        {
            ConnectionOptions options = new ConnectionOptions();
            if (!String.IsNullOrEmpty(textBoxPassword.Text) &&
                !String.IsNullOrEmpty(textBoxUsername.Text))
            {
                options.Username = String.Format("{0}\\{1}", textBoxHost.Text, textBoxUsername.Text);
                options.Password = textBoxPassword.Text;
            }

            try
            {
                Cursor = Cursors.WaitCursor;

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

                scope.Connect();

                ManagementClass win32ProcessClass =
                    new ManagementClass("Win32_Process");

                ManagementBaseObject inParameters =
                    win32ProcessClass.GetMethodParameters("Create");

                win32ProcessClass.Scope = scope;

                inParameters["CommandLine"] = textBoxExecute.Text;

                win32ProcessClass.InvokeMethod("Create", inParameters, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: dblock/codeproject
        static void Main(string[] args)
        {
            try
            {
                CmdArgs parsedArgs = new CmdArgs();
                if (!CommandLine.Parser.ParseArgumentsWithUsage(args, parsedArgs))
                    return;

                ConnectionOptions connOptions = new ConnectionOptions();
                connOptions.Impersonation = ImpersonationLevel.Impersonate;
                connOptions.Authentication = AuthenticationLevel.Default;
                connOptions.Username = parsedArgs.username;
                connOptions.Password = parsedArgs.password;
                connOptions.EnablePrivileges = true;
                ManagementScope scope = new ManagementScope(@"\\" + parsedArgs.machine + @"\root\cimv2", connOptions);
                scope.Connect();

                ManagementPath mgmtPath = new ManagementPath("Win32_Process");
                ManagementClass mgmtClass = new ManagementClass(scope, mgmtPath, null);
                ManagementBaseObject mgmtBaseObject = mgmtClass.GetMethodParameters("Create");
                mgmtBaseObject["CommandLine"] = parsedArgs.command;
                ManagementBaseObject outputParams = mgmtClass.InvokeMethod("Create", mgmtBaseObject, null);
                uint pid = (uint) outputParams["processId"];
                Console.Write("Pid: {0}", pid);

                SelectQuery sQuery = new SelectQuery("Win32_Process", string.Format("processId = {0}", pid));
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(sQuery);
                ManagementObjectCollection processes = null;
                while ((processes = searcher.Get()).Count > 0)
                {
                    Console.Write(".");
                    Thread.Sleep(1000);
                }

                Console.WriteLine(", done.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex.Message);
            }
        }
コード例 #28
0
ファイル: WMI.cs プロジェクト: huoxudong125/WCFLoadUI
        /// <summary>
        /// create client agents on nodes and start agents using WMI
        /// </summary>
        public static void CreateClientAgents()
        {
            Parallel.ForEach(TestEngine.TestPackage.Nodes.NodeList, node =>
            {
                for (int i = 0; i < TestEngine.TestPackage.Nodes.NoOfClientsPerNode; i++)
                {
                    string clientNumber = i.ToString();
                    //copy exe and other files to client location and start the exe
                    string remoteServerName = node;
                    if (!Directory.Exists(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber))
                    {
                        Directory.CreateDirectory(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber);
                    }

                    foreach (string newPath in Directory.GetFiles(Environment.CurrentDirectory + @"\WCFService", "*.*",
                        SearchOption.AllDirectories))
                        File.Copy(newPath,
                            newPath.Replace(Environment.CurrentDirectory + @"\WCFService",
                                @"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber), true);

                    ConnectionOptions connectionOptions = new ConnectionOptions();

                    ManagementScope scope =
                        new ManagementScope(
                            @"\\" + remoteServerName + "." + Domain.GetComputerDomain().Name + @"\root\CIMV2",
                            connectionOptions);
                    scope.Connect();

                    ManagementPath p = new ManagementPath("Win32_Process");
                    ObjectGetOptions objectGetOptions = new ObjectGetOptions();

                    ManagementClass classInstance = new ManagementClass(scope, p, objectGetOptions);

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

                    inParams["CommandLine"] = @"C:\WCFLoadUI"  + clientNumber + @"\WCFService.exe " + Environment.MachineName + " 9090";
                    inParams["CurrentDirectory"] = @"C:\WCFLoadUI" + clientNumber;
                    classInstance.InvokeMethod("Create", inParams, null);
                }
            });
        }
コード例 #29
0
        public void SendCommand(string hostname, string command, Credential credential)
        {
            ConnectionOptions connectoptions = GetConnectionOptions(hostname, credential);

            connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

            System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", hostname), connectoptions);
            mgmtScope.Connect();
            System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
            System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
            System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
            System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
            ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");

            startupInfo.Properties["ShowWindow"].Value = 0;

            inParams["CommandLine"] = command;
            inParams["ProcessStartupInformation"] = startupInfo;

            processClass.InvokeMethod("Create", inParams, null);
        }
コード例 #30
0
ファイル: SystemRestore.cs プロジェクト: gtrant/eraser
        public static uint CreateRestorePoint(string Description, uint EventType, uint RestorePointType)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath       mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams = classObj.GetMethodParameters("CreateRestorePoint");
                inParams["Description"]      = ((System.String)(Description));
                inParams["EventType"]        = ((System.UInt32)(EventType));
                inParams["RestorePointType"] = ((System.UInt32)(RestorePointType));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("CreateRestorePoint", inParams, null);
                return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToUInt32(0));
            }
        }
コード例 #31
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);
                }
            }
        }
コード例 #32
0
ファイル: Utility.cs プロジェクト: margro/TVServerXBMC
        public static bool CreateUncShare(string shareName, string localPath)
        {
            ManagementScope scope = new System.Management.ManagementScope(@"root\CIMV2");
              scope.Connect();

              using (ManagementClass managementClass = new ManagementClass(scope, new ManagementPath("Win32_Share"), (ObjectGetOptions) null))
              {
            SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier) null);
            byte[] binaryForm = new byte[securityIdentifier.BinaryLength];
            securityIdentifier.GetBinaryForm(binaryForm, 0);

            using (ManagementObject wmiTrustee = new ManagementClass(scope, new ManagementPath("Win32_Trustee"), (ObjectGetOptions) null).CreateInstance())
            {
              wmiTrustee["SID"] = (object) binaryForm;
              using (ManagementObject wmiACE = new ManagementClass(scope, new ManagementPath("Win32_ACE"), (ObjectGetOptions) null).CreateInstance())
              {
            wmiACE["AccessMask"] = 131241; //READ_CONTROL | FILE_READ | FILE_TRAVERSE | FILE_READ_EA | FILE_LIST_DIRECTORY
            wmiACE["AceFlags"] = 3;        //OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
            wmiACE["AceType"] = 0; //ACCESS_ALLOWED
            wmiACE["Trustee"] = wmiTrustee;
            using (ManagementObject wmiSecurityDescriptor = new ManagementClass(scope, new ManagementPath("Win32_SecurityDescriptor"), (ObjectGetOptions) null).CreateInstance())
            {
              wmiSecurityDescriptor["ControlFlags"] = 4;
              wmiSecurityDescriptor["DACL"] = new ManagementObject[] { wmiACE };
              using (ManagementBaseObject inParamsCreate = managementClass.GetMethodParameters("Create"))
              {
                inParamsCreate["Access"] = wmiSecurityDescriptor;
                inParamsCreate["Path"] = localPath;
                inParamsCreate["Name"] = shareName;
                inParamsCreate["Type"] = 0;
                inParamsCreate["Description"] = "TVServerXBMC share";
                using (ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParamsCreate, (InvokeMethodOptions) null))
                  return ((int) (uint) outParams["returnValue"] == 0);
              }
            }
              }
            }
              }
        }
コード例 #33
0
        public static uint Create(string Description, string DfsEntryPath, string ServerName, string ShareName)
        {
            bool IsMethodStatic = true;

            if ((IsMethodStatic == true))
            {
                System.Management.ManagementBaseObject inParams = null;
                System.Management.ManagementPath       mgmtPath = new System.Management.ManagementPath(CreatedClassName);
                System.Management.ManagementClass      classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
                inParams = classObj.GetMethodParameters("Create");
                inParams["Description"]  = ((System.String)(Description));
                inParams["DfsEntryPath"] = ((System.String)(DfsEntryPath));
                inParams["ServerName"]   = ((System.String)(ServerName));
                inParams["ShareName"]    = ((System.String)(ShareName));
                System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
                return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value));
            }
            else
            {
                return(System.Convert.ToUInt32(0));
            }
        }
コード例 #34
0
ファイル: FolderShareTask.cs プロジェクト: fchen/dropkick
        public DeploymentResult Execute()
        {
            var result = new DeploymentResult();
            var managementClass = new ManagementClass("Win32_Share");

            ManagementBaseObject args = managementClass.GetMethodParameters("Create");
            args["Description"] = Description;
            args["Name"] = ShareName;
            args["Path"] = PointingTo;
            args["Type"] = 0x0; // Disk Drive

            ManagementBaseObject outParams = managementClass.InvokeMethod("Create", args, null);

            // Check to see if the method invocation was successful
            if (outParams != null && (uint) (outParams.Properties["ReturnValue"].Value) != 0)
            {
                throw new Exception("Unable to share directory '{0}' as '{2}' on '{1}'.".FormatWith(PointingTo, Server,
                                                                                                    ShareName));
            }

            result.AddGood("Created share");

            return result;
        }
コード例 #35
0
ファイル: Provider.cs プロジェクト: przemo098/ccmmanager
 /// <summary>
 /// Executes a method with a given Class and method name.
 /// </summary>
 /// <param name="oClass">The Class to be used.</param>
 /// <param name="method">The method name to be executed.</param>
 /// <returns>Returns a ManagementBaseObject</returns>
 public ManagementBaseObject ExecuteMethod(ManagementClass oClass, string method)
 {
     if (oClass != null)
     {
         oClass.Get();
         ManagementBaseObject inParams = oClass.GetMethodParameters(method);
         return oClass.InvokeMethod(method, inParams, new InvokeMethodOptions());
     }
     else
     {
         return null;
     }
 }
コード例 #36
0
        private void AddAssembly()
        {
            if (System.IO.File.Exists(this.AssemblyPath.GetMetadata("FullPath")) == false)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "The AssemblyPath was not found: {0}", this.AssemblyPath.GetMetadata("FullPath")));
            }
            else
            {
                if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "GAC Assembly: {0}", this.AssemblyPath.GetMetadata("FullPath")));
                    this.Install(this.AssemblyPath.GetMetadata("FullPath"), this.Force);
                }
                else
                {
                    if (string.IsNullOrEmpty(this.RemoteAssemblyPath))
                    {
                        this.Log.LogError("RemoteAssemblyPath is Required");
                        return;
                    }

                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "GAC Assembly: {0} on Remote Server: {1}", this.RemoteAssemblyPath, this.MachineName));

                    // the assembly needs to be copied to the remote server for gaccing.
                    if (System.IO.File.Exists(this.RemoteAssemblyPath))
                    {
                        this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deleting old Remote Assembly: {0}", this.RemoteAssemblyPath));
                        System.IO.File.Delete(this.RemoteAssemblyPath);
                    }

                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Copying Assembly from: {0} to: {1}", this.AssemblyPath.GetMetadata("FullPath"), this.RemoteAssemblyPath));
                    System.IO.File.Copy(this.AssemblyPath.GetMetadata("FullPath"), this.RemoteAssemblyPath);
                    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 /i " + "\"" + this.RemoteAssemblyPath + "\"";
                        ManagementBaseObject outParams = m.InvokeMethod("Create", methodParameters, null);

                        if (outParams != null)
                        {
                            if (int.Parse(outParams["returnValue"].ToString(), CultureInfo.InvariantCulture) != 0)
                            {
                                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Remote AddAssembly returned non-zero returnValue: {0}", outParams["returnValue"]));
                                return;
                            }

                            this.LogTaskMessage(MessageImportance.Low, "Process ReturnValue: " + outParams["returnValue"]);
                            this.LogTaskMessage(MessageImportance.Low, "Process ID: " + outParams["processId"]);
                        }
                        else
                        {
                            Log.LogError("Remote Create returned null");
                            return;
                        }
                    }
                }
            }
        }
コード例 #37
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");
                        return;
                    }
                }
            }
        }
コード例 #38
0
 public static uint Create(string CommandLine, string CurrentDirectory, System.Management.ManagementBaseObject ProcessStartupInformation, out uint ProcessId) {
     bool IsMethodStatic = true;
     if ((IsMethodStatic == true)) {
         System.Management.ManagementBaseObject inParams = null;
         System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
         System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null);
         bool EnablePrivileges = classObj.Scope.Options.EnablePrivileges;
         classObj.Scope.Options.EnablePrivileges = true;
         inParams = classObj.GetMethodParameters("Create");
         inParams["CommandLine"] = ((System.String )(CommandLine));
         inParams["CurrentDirectory"] = ((System.String )(CurrentDirectory));
         inParams["ProcessStartupInformation"] = ((System.Management.ManagementBaseObject )(ProcessStartupInformation));
         System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
         ProcessId = System.Convert.ToUInt32(outParams.Properties["ProcessId"].Value);
         classObj.Scope.Options.EnablePrivileges = EnablePrivileges;
         return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);
     }
     else {
         ProcessId = System.Convert.ToUInt32(0);
         return System.Convert.ToUInt32(0);
     }
 }
        private void btnCreateProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBoxUseWmi.Checked)
                {
                    _token.SetDefaultDacl(new Acl(IntPtr.Zero, false));
                    using (var imp = _token.Impersonate())
                    {
                        using (var managementClass = new ManagementClass(@"\\.\root\cimv2", 
                                                        "Win32_Process",
                                                         new ObjectGetOptions()))
                        {
                            var inputParams = managementClass.GetMethodParameters("Create");

                            inputParams["CommandLine"] = txtCommandLine.Text;
                            var outParams = managementClass.InvokeMethod("Create",
                                                                         inputParams,
                                                                         new InvokeMethodOptions());
                            System.Diagnostics.Trace.WriteLine(outParams["ReturnValue"].ToString());
                        }
                    }
                }
                else
                {
                    using (var token = TokenUtils.CreateProcessForToken(txtCommandLine.Text, _token, checkBoxMakeInteractive.Checked))
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }            
        }
コード例 #40
0
ファイル: WKSType.cs プロジェクト: drorgl/MSDNSWebAdmin
        /// <summary>
        /// Instantiates a WKS Type of RR based on the data in the method's input parameters: the record's DNS Server Name, Container Name, Owner Name, class (default = IN), time-to-live value, and the owner's Internet Address, IP protocol and port bit mask. It returns a reference to the new object as an output parameter. 
        /// </summary>
        /// <param name="server">Server object</param>
        /// <param name="dnsServerName">Fully Qualified Domain Name (FQDN) or IP address of the DNS Server that contains this RR.</param>
        /// <param name="containerName">Name of the Container for the Zone, Cache, or RootHints instance which contains this RR.</param>
        /// <param name="ownerName">Owner FQDN for the RR.</param>
        /// <param name="recordClass">Class of the RR.</param>
        /// <param name="ttl">Time, in seconds, that the RR can be cached by a DNS resolver.</param>
        /// <param name="internetAddress">Internet IP address for the record's owner.</param>
        /// <param name="ipProtocol">String representing the IP protocol for this record. Valid values are UDP or TCP.</param>
        /// <param name="services">String containing all services used by the Well Known Service (WKS) record.</param>
        /// <returns>the new object.</returns>
        public static WKSType CreateInstanceFromPropertyData(
            Server server,
            string dnsServerName,
            string containerName,
            string ownerName,
            RecordClassEnum? recordClass,
            TimeSpan? ttl,
            string internetAddress, string ipProtocol
                                            , string services)
        {
            if (server == null)
                throw new ArgumentNullException("server is required");

            ManagementClass dnsClass = new ManagementClass(server.m_scope, new ManagementPath("MicrosoftDNS_WKSType"), null);
            ManagementBaseObject inParams = dnsClass.GetMethodParameters("CreateInstanceFromPropertyData");
            inParams["DnsServerName"] = dnsServerName;
            inParams["ContainerName"] = containerName;
            inParams["OwnerName"] = ownerName;
            if (recordClass != null)
                inParams["RecordClass"] = (UInt32)recordClass.Value;
            if (ttl != null)
                inParams["TTL"] = ttl.Value.TotalSeconds;

            inParams["InternetAddress"] = internetAddress;
            inParams["IPProtocol"] = ipProtocol;
            inParams["Services"] = services;

            try
            {
                return new WKSType(new ManagementObject(server.m_scope, new ManagementPath(dnsClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null)["RR"].ToString()), null));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
コード例 #41
0
ファイル: Wmi.cs プロジェクト: modulexcite/CustomActivities
        private void ExecuteWmi()
        {
            this.GetManagementScope(this.Namespace.Get(this.ActivityContext));
            string managementPath = this.Class.Get(this.ActivityContext);
            if (!string.IsNullOrEmpty(this.Instance.Get(this.ActivityContext)))
            {
                managementPath += "." + this.Instance.Get(this.ActivityContext);

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

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

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = classInstance.InvokeMethod(this.Method.Get(this.ActivityContext), inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue.Set(this.ActivityContext, 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.Get(this.ActivityContext));
                    this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Method: {0}", this.Method.Get(this.ActivityContext)), BuildMessageImportance.Low);

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

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = mgmtClass.InvokeMethod(this.Method.Get(this.ActivityContext), inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue.Set(this.ActivityContext, outParams["ReturnValue"].ToString());
                    }
                }
            }
        }
コード例 #42
0
        } // end _DoInstall()


        // This can throw a Win32Exception, a ManagementException, or an
        // OperationCanceledException.
        private int _RunCommand( string command, bool instaKill, ICauPluginCallbackBase callback )
        {
            int exitCode = -1;
            int processId = 0;
            string username = null;
            SecureString password = null;
            if( null != m_cred )
            {
                username = m_cred.UserName;
                password = m_cred.Password;
            }

            object gate = new object();

            ConnectionOptions co = new ConnectionOptions( null,        // locale
                                                          username,
                                                          password,
                                                          null,        // authority
                                                          ImpersonationLevel.Impersonate,
                                                          AuthenticationLevel.PacketPrivacy,
                                                          true,        // enable privileges
                                                          null,        // context
                                                          TimeSpan.Zero );
            string path = String.Format( CultureInfo.InvariantCulture, @"\\{0}\root\cimv2", m_machine );
            ManagementScope scope = new ManagementScope( path, co );
            ObjectGetOptions objGetOptions = new ObjectGetOptions();

            scope.Connect();

            // We start the query before launching the process to prevent any possibility
            // of a timing or PID recycling problem.
            WqlEventQuery query = new WqlEventQuery( "Win32_ProcessStopTrace" );
            EventWatcherOptions watcherOptions = new EventWatcherOptions( null, TimeSpan.MaxValue, 1 );
            using( ManagementEventWatcher watcher = new ManagementEventWatcher( scope, query, watcherOptions ) )
            {
                watcher.EventArrived += (sender, arg) =>
                {
                    int stoppedProcId = (int) (uint) arg.NewEvent[ "ProcessID" ];
                    if( stoppedProcId == processId )
                    {
                        exitCode = (int) (uint) arg.NewEvent[ "ExitStatus" ];

                        if( null != callback )
                        {
                            callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                                  "Process ID {0} on {1} exited with code: {2}",
                                                                  processId,
                                                                  m_machine,
                                                                  exitCode ) );
                        }

                        lock( gate )
                        {
                            Monitor.PulseAll( gate );
                        }
                    }
                };

                watcher.Start();

                int timeout = Timeout.Infinite;
                ManagementPath mPath = new ManagementPath( "Win32_Process" );
                using( ManagementClass mc = new ManagementClass( scope, mPath, objGetOptions ) )
                using( ManagementBaseObject inParams = mc.GetMethodParameters( "Create" ) )
                {
                    inParams[ "CommandLine" ] = command;
                    using( ManagementBaseObject outParams = mc.InvokeMethod( "Create", inParams, null ) )
                    {
                        int err = (int) (uint) outParams[ "returnValue" ];
                        if( 0 != err )
                        {
                            throw new Win32Exception( err );
                        }
                        processId = (int) (uint) outParams[ "processId" ];
                        Debug.Assert( processId > 0 );
                    }
                }

                if( null != callback )
                {
                    callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                          "Process launched on {0} with ID: {1}",
                                                          m_machine,
                                                          processId ) );
                }

                // If instaKill is true, we are trying to test our ability to receive
                // Win32_ProcessStopTrace events, so kill the process immediately.
                if( instaKill )
                {
                    SelectQuery killQuery = new SelectQuery( "SELECT * FROM Win32_Process WHERE ProcessId = " + processId );
                    using( ManagementObjectSearcher searcher = new ManagementObjectSearcher( scope, killQuery ) )
                    {
                        foreach( ManagementObject obj in searcher.Get() )
                        {
                            obj.InvokeMethod( "Terminate", new object[] { (uint) c_TestWmiExitCode } );
                            obj.Dispose();
                        }
                    }

                    // If we don't receive the Win32_ProcessStopTrace event within 10
                    // seconds, we'll assume it's not coming. In that case, there's
                    // probably a firewall problem blocking WMI.
                    timeout = 10000;
                }

                // Wait until the process exits (or we get canceled).
                lock( gate )
                {
                    // If we get canceled, we stop waiting for the remote process to
                    // finish and just leave it running.
                    using( m_cancelToken.Register( () => { lock( gate ) { Monitor.PulseAll( gate ); } } ) )
                    {
                        if( !Monitor.Wait( gate, timeout ) )
                        {
                            Debug.Assert( instaKill, "This call should not time out unless we are in the instaKill scenario." );
                            throw new ClusterUpdateException( "The Fabrikam CAU plugin is able to create a process on cluster node \"{0}\" using WMI, but is not able to receive process lifetime events. Check the firewalls on both this computer and the target node and ensure that the appropriate WMI rules are enabled.",
                                                              "WmiTestReceiveEventFailed",
                                                              ErrorCategory.ResourceUnavailable );
                        }
                    }
                }

                watcher.Stop();
                m_cancelToken.ThrowIfCancellationRequested();
            }

            return exitCode;
        } // end _RunCommand()