Exemplo n.º 1
0
        /// <summary>
        /// WMI ctor
        /// </summary>
        /// <param name="remoteMachine">The remote machine.</param>
        /// <param name="rootpath">The rootpath.</param>
        /// <param name="creds">The creds.</param>
        public WMI(string remoteMachine, string rootpath = null, ResourceCredential creds = null)
        {
            try
            {
                // ResourceCredential tempcreds = creds ?? new ResourceCredential();
                ResourceCredential tempcreds = creds.Clone() ?? new ResourceCredential();

                _remoteMachine = remoteMachine;

                if (string.IsNullOrEmpty(rootpath))
                {
                    rootpath = @"\\{0}\ROOT\CIMV2";
                }

                SecureString securePassword = null;
                if (!string.IsNullOrEmpty(tempcreds.UserName) && !string.IsNullOrEmpty(tempcreds.Password) &&
                    CDFMonitor.Instance.Config.AppSettings.UseCredentials)
                {
                    unsafe
                    {
                        // Instantiate a new secure string.
                        fixed(char *pChars = tempcreds.Password.ToCharArray())
                        {
                            securePassword = new SecureString(pChars, tempcreds.Password.Length);
                        }
                    }
                }
                else
                {
                    tempcreds.UserName = null;
                    tempcreds.Password = null;
                    tempcreds.Domain   = null;
                }

                CDFMonitor.LogOutputHandler(string.Format("WMI using credentials: user:{0} domain:{1}", tempcreds.UserName, tempcreds.Domain));

                var options =
                    new ConnectionOptions("MS_409",
                                          string.IsNullOrEmpty(tempcreds.UserName) ? null : tempcreds.UserName,
                                          securePassword,
                                          string.IsNullOrEmpty(tempcreds.Domain)
                                              ? null
                                              : "ntlmdomain:" + tempcreds.Domain,
                                          ImpersonationLevel.Impersonate,
                                          AuthenticationLevel.Default,
                                          true,
                                          null,
                                          new TimeSpan(0, 0, 0, 0, CONNECT_TIMEOUT));

                _manScope = new ManagementScope(String.Format(rootpath, _remoteMachine), options);
                _manScope.Connect();
                Status = true;
                CDFMonitor.LogOutputHandler("DEBUG:WMI initialization: " + Status);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("WMI exception: " + e.ToString());
                Status = false;
            }
        }