Ejemplo n.º 1
0
    //method to invoke command line on remote machine
    public void InvokeCommand(string command)
    {
        try
        {
            //connection options
            var connOptions = new System.Management.ConnectionOptions();
            connOptions.Authentication   = AuthenticationLevel.PacketPrivacy;
            connOptions.Impersonation    = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            connOptions.Username         = Domain + "\\" + Username;
            connOptions.Password         = Password;

            //management scope
            var manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", ComputerName), connOptions);
            manScope.Connect();
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            objectGetOptions.Timeout = TimeSpan.FromSeconds(20);
            ManagementPath       managementPath = new ManagementPath("Win32_Process");
            ManagementClass      processClass   = new ManagementClass(manScope, managementPath, objectGetOptions);
            ManagementBaseObject inParams       = processClass.GetMethodParameters("Create");

            //script to execute from passed parameter
            inParams["CommandLine"] = command;

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

            //loop through processes until process has quit
            SelectQuery CheckProcess = new SelectQuery("Select * from Win32_Process Where ProcessId = " + outParams["processId"]);

            //counter for loop
            int counter     = 0;
            int loopcounter = Convert.ToInt32(WmiTimeout) / 10;

            //loop until process has died
            while (counter != (loopcounter + 1))
            {
                // create searcher object
                ManagementObjectSearcher ProcessSearcher = new ManagementObjectSearcher(manScope, CheckProcess);
                ProcessSearcher.Options.Timeout = TimeSpan.FromSeconds(20);

                // if it is not null there is a process running
                if (ProcessSearcher.Get().Count != 0)
                {
                    if (counter == loopcounter)
                    {
                        // kill process
                        inParams["CommandLine"] = "cmd /c \"taskkill /f /pid " + outParams["processId"].ToString() + " /t \"";
                        processClass.InvokeMethod("Create", inParams, null);

                        // throw new exception for process timeout
                        throw new Exception("WMI process timeout");
                    }
                    else
                    {
                        counter++;
                        Thread.Sleep(10000);
                    }
                }
                // if it is null then process is not running and break from loop
                else if (ProcessSearcher.Get().Count == 0)
                {
                    break;
                }
            }
        }
        catch (Exception e)
        {
            //catch exception and remove directory
            RemoveDirectory(@"\\" + ComputerName + @"\c$\deploy_temp");
            throw new Exception(e.Message.ToString());
        }
    }
Ejemplo n.º 2
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()
 public ManagementObject(string path, ObjectGetOptions options)
 {
 }
 public ManagementObject(string scopeString, string pathString, ObjectGetOptions options)
 {
 }
Ejemplo n.º 5
0
        public override void Execute(Context context)
        {
            context.LogInfo("Start app pool: '{0}' on web server: '{1}'", AppPoolName, ServerName);

            ConnectionOptions options = null;
            ManagementScope   scope   = null;

            if (null != Username)
            {
                context.LogInfo("Connect with user: '******' and password: '******'", Username, Password);
                options = new ConnectionOptions()
                {
                    Username         = Username,
                    Password         = Password,
                    EnablePrivileges = true,
                    Authentication   = AuthenticationLevel.PacketPrivacy
                };
            }
            else if (null != ServerName)
            {
                context.LogInfo("Connect with impersonate");
                options = new ConnectionOptions()
                {
                    Impersonation    = ImpersonationLevel.Impersonate,
                    EnablePrivileges = true,
                    Authentication   = AuthenticationLevel.PacketPrivacy
                };
            }

            var path = !string.IsNullOrEmpty(ServerName) ?
                       new ManagementPath(string.Format("\\\\{0}\\root\\WebAdministration:ApplicationPool.Name='{1}'", ServerName, AppPoolName)) :
                       new ManagementPath(string.Format("root\\WebAdministration:ApplicationPool.Name='{0}'", AppPoolName));

            context.LogInfo("Path = '{0}'", path.Path);

            if (null != options)
            {
                scope = new ManagementScope(path, options);
            }
            else
            {
                scope = new ManagementScope(path);
            }
            scope.Connect();

            int stateValue    = -1;
            var opt           = new ObjectGetOptions();
            var classInstance = new ManagementObject(scope, path, opt);
            var outState      = classInstance.InvokeMethod("GetState", null).ToString();

            if (!int.TryParse(outState, out stateValue))
            {
                context.LogInfo("Invalid Application Pool State = '{0}'", outState);
                return;
            }
            context.LogInfo("Application Pool State = '{0}'", IISHelper.GetFriendlyApplicationPoolState(stateValue));
            switch (IISHelper.GetFriendlyApplicationPoolState(stateValue))
            {
            case "Stopped":
                var outParams = classInstance.InvokeMethod("Start", null, null);
                context.LogInfo("Application Pool has been started");
                break;

            case "Started":
                context.LogInfo("Application Pool already started");
                break;

            default:
                context.LogInfo("Application Pool could not be started");
                break;
            }
        }
Ejemplo n.º 6
0
 public StorageAllocationSettingData(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 7
0
 public StorageExtendedStatus(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 8
0
 protected void InitializeObject(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     Initialize();
     if (path != null)
     {
         if (CheckIfProperClass(mgmtScope, path, getOptions) != true)
         {
             throw new ArgumentException(Properties.Exceptions.Default.ClassNameExceptionMessage);
         }
     }
     PrivateLateBoundObject = new ManagementObject(mgmtScope, path, getOptions);
     SystemProperties       = new ManagementSystemProperties(PrivateLateBoundObject);
     LateBoundObject        = PrivateLateBoundObject;
 }
Ejemplo n.º 9
0
 public Memory(ManagementPath path, ObjectGetOptions getOptions) : base(path, getOptions, ClassName)
 {
 }
Ejemplo n.º 10
0
 public Memory(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 11
0
        public void EnumObjects(string className)
        {
            View.LV.Clear();

            var op = new ObjectGetOptions(null, TimeSpan.MaxValue, true);

            using (var mc = new ManagementClass(m_Namespace, new ManagementPath(className), op))
            {
                mc.Options.UseAmendedQualifiers = true;
                m_Class = mc;
            }
            if (!SetupColumns())
            {
                return;
            }

            var query = new ObjectQuery("select * from " + className);

            using (var searcher = new ManagementObjectSearcher(m_Namespace, query))
            {
                try
                {
                    foreach (ManagementObject wmiObject in searcher.Get())
                    {
                        if (wmiObject == null)
                        {
                            continue;
                        }
                        var lvi = new ListViewItem {
                            Tag = wmiObject
                        };
                        int index = 0;
                        foreach (ColumnHeader header in View.LV.Columns)
                        {
                            var prop = wmiObject.Properties[header.Text];

                            var value = prop.Value == null ? NULL : prop.Value.ToString();
                            if (prop.Name.Equals("Name"))
                            {
                                string[] sList = value.Split('|');
                                if (sList.Length > 0)
                                {
                                    value = sList[0];
                                }
                            }
                            if (index == 0)
                            {
                                lvi.Text = value;
                            }
                            else
                            {
                                lvi.SubItems.Add(value);
                            }
                            index++;
                        }
                        View.LV.Items.Add(lvi);
                    }
                }
                catch (ManagementException ex)
                {
                    Debug.Print(ex.Message);
                }
            }
        }
Ejemplo n.º 12
0
 public MsvmBase(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(mgmtScope, path, getOptions);
 }
Ejemplo n.º 13
0
 protected bool CheckIfProperClass(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions OptionsParam)
 {
     if ((path != null) && (string.Compare(path.ClassName, ManagementClassName, true, CultureInfo.InvariantCulture) == 0))
     {
         return(true);
     }
     else
     {
         using (ManagementObject theObj = new ManagementObject(mgmtScope, path, OptionsParam))
         {
             return(CheckIfProperClass(theObj));
         }
     }
 }
	public ManagementClass(ManagementPath path, ObjectGetOptions options) {}
Ejemplo n.º 15
0
 public ExternalEthernetPort(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
	public ManagementObject(string path, ObjectGetOptions options) {}
Ejemplo n.º 17
0
 public BcdObject(ManagementPath path, ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Ejemplo n.º 18
0
 public ConcreteComponent(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 19
0
 public BcdObject(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Ejemplo n.º 20
0
 public EthernetSwitchFeatureCapabilities(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 21
0
        public static DataTable GroupMembers(string srv, string usr, string pwd)
        {
            StringBuilder result = new StringBuilder();

            try
            {
                //
                MPSfwk.Model.Server s = new MPSfwk.Model.Server();
                s.IPHOST  = srv;
                s.USUARIO = usr;
                s.SENHA   = pwd;
                ManagementScope  ms = scopeMgmt(false, s);
                ObjectGetOptions objectGetOptions = new ObjectGetOptions();
                //
                string targethost = "";
                string groupname  = "";
                string aux_qry    = "";
                if ((srv.IndexOf(".") == -1) && (srv.ToUpper() != "LOCALHOST"))
                {
                    aux_qry = "select * from Win32_Group Where Domain = '" + srv + "'";
                }
                else
                {
                    aux_qry = "select * from Win32_Group Where LocalAccount = True";
                }
                //
                //MPS teste - 10/out
                //
                Console.WriteLine("DEBUG - aux_qry = " + aux_qry);
                //
                DataTable dt_aux = dtlistaClasse("Win32_Group",
                                                 aux_qry,
                                                 srv,
                                                 usr,
                                                 pwd);
                //
                //Cria tabela para preencher os campos
                DataTable dt1 = new DataTable();
                dt1.TableName = "GroupMembers";
                dt1.Columns.Add("Domain");
                dt1.Columns.Add("Group Name");
                dt1.Columns.Add("Users");
                //
                foreach (DataRow drow in dt_aux.Rows)
                {
                    //
                    DataRow dr = dt1.NewRow();
                    //
                    targethost = drow["Domain"].ToString();
                    groupname  = drow["Name"].ToString();

                    StringBuilder qs = new StringBuilder();
                    qs.Append("SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \"Win32_Group.Domain='");
                    qs.Append(targethost);
                    qs.Append("',Name='");
                    qs.Append(groupname);
                    qs.AppendLine("'\"");
                    ObjectQuery query = new ObjectQuery(qs.ToString());
                    ManagementObjectSearcher   searcher        = new ManagementObjectSearcher(ms, query);
                    ManagementObjectCollection queryCollection = searcher.Get();
                    foreach (ManagementObject m in queryCollection)
                    {
                        ManagementPath path = new ManagementPath(m["PartComponent"].ToString());
                        {
                            String[] names = path.RelativePath.Split(',');
                            result.Append(names[0].Substring(names[0].IndexOf("=") + 1).Replace("\"", " ").Trim() + "\\");
                            result.AppendLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace("\"", " ").Trim() + " ; ");
                        }
                    }
                    //Console.WriteLine("Domain =  " + targethost + " Name = " + groupname + " Users = " + result.ToString());
                    dr["Domain"]     = targethost;
                    dr["Group Name"] = groupname;
                    dr["Users"]      = result.ToString();
                    dt1.Rows.Add(dr);
                    //
                    result = new StringBuilder();
                }
                return(dt1);
                //
            }
            catch (Exception e)
            {
                Console.WriteLine("|!| GroupMembers Error - " + e.Message);
                return(null);
            }
        }
 public MetricServiceCapabilities(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
Ejemplo n.º 23
0
 public async Task <ManagementObject> GetManagementObjectAsync(String _managementPath, ObjectGetOptions _get_options = null)
 {
     return(new ManagementObject(await GetManagementScopeAsync(), new ManagementPath(_managementPath), _get_options));
 }
 public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
 {
 }
 private bool CheckIfProperClass(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions OptionsParam)
 {
     if (((path != null) &&
          (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)))
     {
         return(true);
     }
     return(this.CheckIfProperClass(new ManagementObject(mgmtScope, path, OptionsParam)));
 }
        private void ClientAction(IResultObject resultObject)
        {
            ListViewItem item = listViewHosts.FindItemWithText(resultObject["Name"].StringValue);

            try
            {
                item.SubItems[1].Text = "Connecting";
                ObjectGetOptions o = new ObjectGetOptions
                {
                    Timeout = new TimeSpan(0, 0, 5)
                };
                if (mode)
                {
                    using (ManagementClass clientaction = new ManagementClass(string.Format(@"\\{0}\root\{1}", resultObject["Name"].StringValue, "ccm"), "SMS_Client", o))
                    {
                        object[] methodArgs = { "False" };
                        clientaction.InvokeMethod("SetClientProvisioningMode", methodArgs);
                    }
                    item.SubItems[1].Text = "Completed";
                }
                else
                {
                    //using (ManagementClass registry = new ManagementClass(string.Format(@"\\{0}\root\{1}", resultObject["Name"].StringValue, "cimv2"), "StdRegProv", o))
                    //{
                    //    ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue");
                    //    inParams["hDefKey"] = 0x80000002;
                    //    inParams["sSubKeyName"] = @"SOFTWARE\Microsoft\CCM\CcmExec";
                    //    inParams["sValueName"] = "ProvisioningMode";

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

                    //    if (outParams.Properties["sValue"].Value != null)
                    //    {
                    //        item.SubItems[1].Text = outParams.Properties["sValue"].Value.ToString();
                    //    }
                    //    else
                    //    {
                    //        item.SubItems[1].Text = "No value";
                    //    }
                    //}
                }
                ++completed;
            }
            catch (ManagementException ex)
            {
                ExceptionUtilities.TraceException(ex);
                item.SubItems[1].Text = "WMI error: " + ex.Message;
                ++other;
            }
            catch (COMException ex)
            {
                ExceptionUtilities.TraceException(ex);
                item.SubItems[1].Text = "Offline";
                ++other;
            }
            catch (Exception ex)
            {
                ExceptionUtilities.TraceException(ex);
                item.SubItems[1].Text = "Error: " + ex.Message;
                ++other;
            }
            finally
            {
                try
                {
                    Invoke(new BarDelegate(UpdateBar));
                }
                catch { }
            }
        }
 private void InitializeObject(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     this.Initialize();
     if ((path != null))
     {
         if ((this.CheckIfProperClass(mgmtScope, path, getOptions) != true))
         {
             throw new System.ArgumentException("クラス名が一致しません。");
         }
     }
     this.PrivateLateBoundObject  = new ManagementObject(mgmtScope, path, getOptions);
     this.PrivateSystemProperties = new ManagementSystemProperties(this.PrivateLateBoundObject);
     this.curObj = this.PrivateLateBoundObject;
 }
Ejemplo n.º 28
0
 public VirtualSystemSettingDataComponent(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
 public BcdDeviceLocateElementData(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
	public ManagementClass(string scope, string path, ObjectGetOptions options) {}
Ejemplo n.º 31
0
 public ProcessorSettingData(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName)
 {
 }
	public ManagementObject(string scopeString, string pathString, ObjectGetOptions options) {}
Ejemplo n.º 33
0
 public MetricService(ManagementPath path, ObjectGetOptions getOptions) : base(path, getOptions, ClassName)
 {
 }
	public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options) {}
Ejemplo n.º 35
0
 public MsftBase(ManagementPath path, ObjectGetOptions getOptions, string ClassName)
 {
     CreatedClassName = ClassName;
     InitializeObject(null, path, getOptions);
 }