private void ClassSetup(string ComputerName, string Domain, string UserName, SecureString Password, uint Port)
 {
     if (AuthType == PasswordAuthenticationMechanism.Default)
     {
         AuthType = PasswordAuthenticationMechanism.Kerberos;
     }
     Credentials    = new CimCredential(AuthType, Domain, UserName, Password);
     SessionOptions = new WSManSessionOptions()
     {
         DestinationPort = Port
     };
     SessionOptions.AddDestinationCredentials(Credentials);
     SystemSession = CimSession.Create(ComputerName, SessionOptions);
     if (PortTest(ComputerName))
     {
         Connected = SystemSession.TestConnection(out CimInstance TmpInstance, out CimException TmpExeption);
         if (!Connected)
         {
             Err = TmpExeption;
             ConnectionStatuMessage = Err.Message;
         }
         else
         {
             ConnectionStatuMessage = "Connected";
         }
     }
     else
     {
         Connected = false;
         ConnectionStatuMessage = "Port not open on host";
     }
     RegSoftwareUninstall = new List <string>();
 }
        private void SessionConnect()
        {
            try
            {
                SecureString securepassword = new SecureString();
                foreach (char c in PasswordTextBox.Password)
                {
                    securepassword.AppendChar(c);
                }

                // create Credentials
                CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Domain, Username, securepassword);

                // create SessionOptions using Credentials
                WSManSessionOptions SessionOptions = new WSManSessionOptions();
                SessionOptions.AddDestinationCredentials(Credentials);

                // create Session using computer, SessionOptions
                Session = CimSession.Create(Server, SessionOptions);
            }
            catch (Exception ex)
            {
                snackMessageQueue.Enqueue(ex);
                SnackbarNotify.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D63031"));
                log.Error(ex.Message);
            }
        }
示例#3
0
        private CimSessionProxy CreateSessionProxy(string computerName, GetCimClassCommand cmdlet)
        {
            CimSessionProxy cimSessionProxyGetCimClass = null;

            if (!string.IsNullOrEmpty(computerName) && !computerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
            {
                /* Set on the fly credentials */
                System.Management.Automation.PSCredential credential = GetOnTheFlyCredentials(cmdlet);
                if (credential == null)
                {
                    cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName);
                }
                else
                {
                    CimSessionOptions options = new WSManSessionOptions();
                    options.AddDestinationCredentials(cmdlet.CreateCimCredentials(credential, PasswordAuthenticationMechanism.Default, "Get-CimClass", "Authentication"));
                    cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName, options);
                }
            }
            else
            {
                cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName);
            }
            base.SubscribeEventAndAddProxytoCache(cimSessionProxyGetCimClass);
            this.SetSessionProxyProperties(ref cimSessionProxyGetCimClass, cmdlet);
            return(cimSessionProxyGetCimClass);
        }
示例#4
0
        static CimSession CreateSession(string target, string user, string pass, string domain, string proto, bool ssl)
        {
            if (target == "." || target == "127.0.0.1" || target == "localhost")
            {
                Console.WriteLine("Querying localhost");
                return(CimSession.Create(target));
            }
            else
            {
                Console.WriteLine("Querying " + target);
                SecureString secpass = new SecureString();
                foreach (char c in pass)
                {
                    secpass.AppendChar(c);
                }
                CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, domain, user, secpass);

                if (proto == "dcom")
                {
                    var dcomOptions = new DComSessionOptions();
                    dcomOptions.AddDestinationCredentials(Credentials);
                    return(CimSession.Create(target, dcomOptions));
                }
                else
                {
                    var wsmanOptions = new WSManSessionOptions();
                    wsmanOptions.AddDestinationCredentials(Credentials);
                    wsmanOptions.UseSsl = ssl;
                    return(CimSession.Create(target, wsmanOptions));
                }
            }
        }
示例#5
0
        private CimSession CreateCimSession()
        {
            CimSessionOptions options = null;

            switch (_protocol)
            {
            case WindowsRemotingProtocol.DCOM:
                options = new DComSessionOptions();
                if (!string.IsNullOrEmpty(_username))
                {
                    options.AddDestinationCredentials(new CimCredential(_authMechanism, _domain, _username, _password));
                }
                break;

            case WindowsRemotingProtocol.WinRM:
                var wsmanOptions = new WSManSessionOptions();
                if (!string.IsNullOrEmpty(_username))
                {
                    wsmanOptions.AddDestinationCredentials(new CimCredential(_authMechanism, _domain, _username, _password));
                    wsmanOptions.UseSsl = true;
                }
                options = wsmanOptions;
                break;
            }
            return(CimSession.Create(_serverConnectionName, options));
        }
示例#6
0
        protected CimSessionProxy CreateSessionProxy(string computerName, CimBaseCommand cmdlet)
        {
            CimSessionProxy cimSessionProxy = null;

            if (!string.IsNullOrEmpty(computerName) && !computerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
            {
                /* Set on the fly credentials */
                System.Management.Automation.PSCredential credential = GetOnTheFlyCredentials(cmdlet);
                if (credential == null)
                {
                    cimSessionProxy = base.CreateCimSessionProxy(computerName);
                }
                else
                {
                    CimSessionOptions options = new WSManSessionOptions();
                    options.AddDestinationCredentials(cmdlet.CreateCimCredentials(credential, PasswordAuthenticationMechanism.Default, "Get-CimIstance", "Authentication"));
                    cimSessionProxy = base.CreateCimSessionProxy(computerName, options);
                }
            }
            else
            {
                cimSessionProxy = base.CreateCimSessionProxy(computerName);
            }
            this.SetSessionProxyProperties(ref cimSessionProxy, cmdlet);
            return(cimSessionProxy);
        }
示例#7
0
        /// <summary>
        /// Constructor that configures connection to host using specified credential object and takes WMI namespace
        /// </summary>
        /// <param name="computerName">Computer name or IP address to connect</param>
        /// <param name="nameSpace">Namespace to configure</param>
        /// <param name="credential">Preconfigured credential object to be used in connection</param>
        public CimConnection(string computerName, string nameSpace, CimCredential credential)
        {
            var sessionOptions = new WSManSessionOptions();

            sessionOptions.AddDestinationCredentials(credential);
            _connection = CimSession.Create(computerName, sessionOptions);
            _nameSpace  = nameSpace;
        }
示例#8
0
        private CimSession DoCimConnection(Planter planter)
        {
            //Block for connecting to the remote system and returning a CimSession object
            SystemToConn = planter.System;
            Domain       = planter.Domain;
            Username     = planter.User;
            Password     = planter.Password;
            WSManSessionOptions sessionOptions = new WSManSessionOptions();
            CimSession          connectedCimSession;

            if (SystemToConn == null)
            {
                SystemToConn = "localhost";
            }
            if (Username == null)
            {
                Username = Environment.UserName;
            }

            switch (SystemToConn)
            {
            case "127.0.0.1":
            case "localhost":
                Messenger.GoodMessage("[+] Connecting to local CIM instance using " + Username + "...");
                break;

            default:
                Messenger.GoodMessage("[+] Connecting to remote CIM instance using " + Username + "...");
                break;
            }

            if (!string.IsNullOrEmpty(Password?.ToString()))
            {
                // create Credentials
                CimCredential credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Domain, Username, Password);
                sessionOptions.AddDestinationCredentials(credentials);
                sessionOptions.MaxEnvelopeSize = 256000; // Not sure how else to get around this
                connectedCimSession            = CimSession.Create(SystemToConn, sessionOptions);
            }

            else
            {
                DComSessionOptions options = new DComSessionOptions {
                    Impersonation = ImpersonationType.Impersonate
                };
                connectedCimSession = CimSession.Create(SystemToConn, options);
            }

            // Test connection to make sure we're connected
            if (!connectedCimSession.TestConnection())
            {
                return(null);
            }

            Messenger.GoodMessage("[+] Connected\n");
            return(connectedCimSession);
        }
示例#9
0
        private CimSession CreateCimSession()
        {
            var options = new WSManSessionOptions();

            if (!string.IsNullOrEmpty(_username))
            {
                options.AddDestinationCredentials(new CimCredential(_authMechanism, _domain, _username, _password));
                options.UseSsl = true;
            }
            return(CimSession.Create(_serverConnectionName, options));
        }
示例#10
0
        public static CimSession Connect(string hostName, string userName, string passWord, string domain)
        {
            SecureString securePassword = new SecureString();

            Array.ForEach(passWord.ToArray(), securePassword.AppendChar);
            securePassword.MakeReadOnly();
            WSManSessionOptions sessionOptions = new WSManSessionOptions();

            sessionOptions.AddDestinationCredentials(new CimCredential(PasswordAuthenticationMechanism.Default, domain, userName, securePassword));
            return(CimSession.Create(hostName, sessionOptions));
        }
        static void Main(string[] args)
        {
            string computer = "Computer_B";
            string domain   = "DOMAIN";
            string username = "******";
            string plaintextpassword;

            Console.WriteLine("Enter password:"******"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
            var        allPDisks  = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");

            // Loop through all volumes
            foreach (CimInstance oneVolume in allVolumes)
            {
                // Show volume information
                if (oneVolume.CimInstanceProperties["DriveLetter"].ToString()[0] > ' ')
                {
                    Console.WriteLine("Volume ‘{0}’ has {1} bytes total, {2} bytes available",
                                      oneVolume.CimInstanceProperties["DriveLetter"],
                                      oneVolume.CimInstanceProperties["Size"],
                                      oneVolume.CimInstanceProperties["SizeRemaining"]);
                }
            }
            // Loop through all physical disks
            foreach (CimInstance onePDisk in allPDisks)
            {
                // Show physical disk information
                Console.WriteLine("Disk {0} is model {1}, serial number {2}",
                                  onePDisk.CimInstanceProperties["DeviceId"],
                                  onePDisk.CimInstanceProperties["Model"].ToString().TrimEnd(),
                                  onePDisk.CimInstanceProperties["SerialNumber"]);
            }
            Console.ReadLine();
        }
        public string GetHostname()
        {
            string hostname = string.Empty;

            if (string.IsNullOrEmpty(wincred.Domain))
            {
                wincred.Domain = ip.ToString();
            }
            CimCredential       Credentials    = new CimCredential(PasswordAuthenticationMechanism.Default, wincred.Domain, wincred.Username, wincred.Password);
            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (ssl)
            {
                SessionOptions.UseSsl = true;
            }
            else
            {
                SessionOptions.UseSsl = false;
            }
            SessionOptions.DestinationPort = port;
            if (checkcert)
            {
                SessionOptions.CertCACheck         = true;
                SessionOptions.CertCNCheck         = true;
                SessionOptions.CertRevocationCheck = true;
            }
            else
            {
                SessionOptions.CertCACheck         = false;
                SessionOptions.CertCNCheck         = false;
                SessionOptions.CertRevocationCheck = false;
            }

            try
            {
                Session = CimSession.Create(ip.ToString(), SessionOptions);
                CimInstance searchInstance = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT CSNAME from win32_operatingsystem").FirstOrDefault();
                if (searchInstance != null)
                {
                    hostname = searchInstance.CimInstanceProperties["CSName"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                log.Error("IPADDRESS: " + ip + " ;MESSAGE: " + ex.Message);
            }
            return(hostname);
        }
 private void ClassSetup(string ComputerName, PasswordAuthenticationMechanism AuthType, string Domain, string UserName, SecureString Password, uint Port)
 {
     if (AuthType == PasswordAuthenticationMechanism.Default)
     {
         AuthType = PasswordAuthenticationMechanism.Kerberos;
     }
     Credentials    = new CimCredential(AuthType, Domain, UserName, Password);
     SessionOptions = new WSManSessionOptions()
     {
         DestinationPort = Port
     };
     SessionOptions.AddDestinationCredentials(Credentials);
     SystemSession = CimSession.Create(ComputerName, SessionOptions);
     Connected     = SystemSession.TestConnection(out CimInstance TmpInstance, out CimException TmpExeption);
 }
示例#14
0
        /// <summary>
        /// Returns the default wsman options object
        /// </summary>
        /// <returns>Something very default-y</returns>
        private WSManSessionOptions GetDefaultCimWsmanOptions()
        {
            WSManSessionOptions options = new WSManSessionOptions();

            options.DestinationPort     = 0;
            options.MaxEnvelopeSize     = 0;
            options.CertCACheck         = true;
            options.CertCNCheck         = true;
            options.CertRevocationCheck = true;
            options.UseSsl         = false;
            options.PacketEncoding = PacketEncoding.Utf8;
            options.NoEncryption   = false;
            options.EncodePortInServicePrincipalName = false;

            return(options);
        }
示例#15
0
        /// <summary>
        /// Constructor that configures connection to host using specified credentials and takes WMI namespace
        /// </summary>
        /// <param name="computerName">Computer name or IP address to connect</param>
        /// <param name="nameSpace">Namespace to configure</param>
        /// <param name="authenticationMechanism">Authentication mechanism to be used</param>
        /// <param name="domain">User domain</param>
        /// <param name="userName">User name</param>
        /// <param name="password">User password</param>
        public CimConnection(string computerName, string nameSpace,
                             PasswordAuthenticationMechanism authenticationMechanism, string domain, string userName, string password)
        {
            var securePassword = new SecureString();

            foreach (var c in password)
            {
                securePassword.AppendChar(c);
            }

            var credential     = new CimCredential(authenticationMechanism, domain, userName, securePassword);
            var sessionOptions = new WSManSessionOptions();

            sessionOptions.AddDestinationCredentials(credential);
            _connection = CimSession.Create(computerName, sessionOptions);
            _nameSpace  = nameSpace;
        }
        public static MSMQConnectSession connect(String host, String domain, String username, String password)
        {
            SecureString securepassword = new SecureString();

            foreach (Char p in password.ToCharArray())
            {
                securepassword.AppendChar(p);
            }


            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Kerberos
                                                          + "", domain, username, securepassword);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);

            return(new MSMQConnectSession(CimSession.Create(host, SessionOptions)));
        }
示例#17
0
        public static CimSession newSession(string computername, string domain, string username, string password, bool impersonate = false)
        {
            CimSession cimSession;

            if (impersonate)
            {
                DComSessionOptions options = new DComSessionOptions {
                    Impersonation = ImpersonationType.Impersonate
                };
                cimSession = CimSession.Create(computername, options);
            }
            else
            {
                CimCredential       credentials    = new CimCredential(PasswordAuthenticationMechanism.Negotiate, domain, username, Misc.CreateSecuredString(password));
                WSManSessionOptions sessionOptions = new WSManSessionOptions();
                sessionOptions.AddDestinationCredentials(credentials);
                sessionOptions.MaxEnvelopeSize = 256000;
                cimSession = CimSession.Create(computername, sessionOptions);
            }
            return(cimSession);
        }
示例#18
0
        public static List <MachineHardwareInfo> GetHardwareInfo(string computer, string domain, string username, string plaintextpassword)
        {
            MachineName = computer;
            List <MachineHardwareInfo> info = new List <MachineHardwareInfo>();

            SecureString securepassword = new SecureString();

            foreach (char c in plaintextpassword)
            {
                securepassword.AppendChar(c);
            }

            // create Credentials
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default,
                                                          domain,
                                                          username,
                                                          securepassword);

            // create SessionOptions using Credentials
            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);

            // create Session using computer, SessionOptions
            using (CimSession Session = CimSession.Create(computer, SessionOptions))
            {
                var usb       = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_USBControllerDevice");
                var disks     = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_LogicalDisk");
                var ram       = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                var processor = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Processor");
                var sound     = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_SoundDevice");
                info.AddRange(RamInfo(ram));
                info.AddRange(ProcessorInfo(processor));
                info.AddRange(USBInfo(usb));
                info.AddRange(DiskInfo(disks));
            }
            return(info);
        }
示例#19
0
        public static void ConnectingToWMI(string Computer_B)
        {
            //string Namespace = @"root\cimv2";
            //string OSQuery = "SELECT * FROM Win32_OperatingSystem";
            //CimSession mySession = CimSession.Create(Computer_B);
            //IEnumerable<CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);


            //foreach (CimInstance cimInstance in queryInstance)
            //{
            //    Console.WriteLine("Process name: {0}", cimInstance.CimInstanceProperties["Name"].Value);
            //}


            //*************************************
            //string domain = "DESKTOP-3KU7CQB";
            //string username = "******";
            //string password = "******";

            string domain   = "devstation";
            string username = "******";
            string password = "******";


            //PerformanceCounter freeSpaceCounter = null;
            //using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
            //{
            //    freeSpaceCounter = new PerformanceCounter("LogicalDisk",
            //                               "Free Megabytes", "D:", "RemoteMachine12");
            //}

            ConnectionOptions con = new ConnectionOptions();

            con.Username = "******";
            con.Password = "******";

            ManagementScope scope = new ManagementScope(@"\\" + Computer_B + @"\root\cimv2", con);

            scope.Connect();



            SecureString securepassword = new SecureString();

            foreach (char c in password)
            {
                securepassword.AppendChar(c);
            }

            // create Credentials
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default,
                                                          Computer_B,
                                                          username,
                                                          securepassword);

            // create SessionOptions using Credentials
            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            // create Session using computer, SessionOptions
            CimSession Session = CimSession.Create(Computer_B, SessionOptions);


            var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
            var allPDisks  = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");

            // Loop through all volumes
            foreach (CimInstance oneVolume in allVolumes)
            {
                // Show volume information

                if (oneVolume.CimInstanceProperties["DriveLetter"].ToString()[0] > ' ')
                {
                    Console.WriteLine("Volume ‘{0}’ has {1} bytes total, {2} bytes available",
                                      oneVolume.CimInstanceProperties["DriveLetter"],
                                      oneVolume.CimInstanceProperties["Size"],
                                      oneVolume.CimInstanceProperties["SizeRemaining"]);
                }
            }

            // Loop through all physical disks
            foreach (CimInstance onePDisk in allPDisks)
            {
                // Show physical disk information
                Console.WriteLine("Disk {0} is model {1}, serial number {2}",
                                  onePDisk.CimInstanceProperties["DeviceId"],
                                  onePDisk.CimInstanceProperties["Model"].ToString().TrimEnd(),
                                  onePDisk.CimInstanceProperties["SerialNumber"]);
            }
        }
        private void DiskScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);

            if (PC1)
            {
                try
                {
                    CimSession Session1    = CimSession.Create(Data.computer1, SessionOptions);
                    var        allVolumes1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume1 in allVolumes1)
                    {
                        if (oneVolume1.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk1size   = String.Format("{0}", oneVolume1.CimInstanceProperties["Capacity"].Value);
                            Data.DD1size     = Math.Round(Convert.ToDouble(Data.disk1size) / 1073741824, 2);
                            Data.disk1size   = Data.DD1size.ToString() + " GB";
                            Data.disk1remain = String.Format("{0}", oneVolume1.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD1remain   = Math.Round(Convert.ToDouble(Data.disk1remain) / 1073741824, 2);
                            Data.disk1remain = Data.DD1remain.ToString() + " GB";
                        }
                        BarDD1.Maximum = (int)Data.DD1size;
                        BarDD1.Value   = (int)(Data.DD1size - Data.DD1remain);
                    }
                    labelDisk1Remain.Text = Data.disk1remain;
                    labelDisk1Total.Text  = Data.disk1size;
                    labelDisk1Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD1size - Data.DD1remain) / Data.DD1size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2    = CimSession.Create(Data.computer2, SessionOptions);
                    var        allVolumes2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume2 in allVolumes2)
                    {
                        if (oneVolume2.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk2size   = String.Format("{0}", oneVolume2.CimInstanceProperties["Capacity"].Value);
                            Data.DD2size     = Math.Round(Convert.ToDouble(Data.disk2size) / 1073741824, 2);
                            Data.disk2size   = Data.DD2size.ToString() + " GB";
                            Data.disk2remain = String.Format("{0}", oneVolume2.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD2remain   = Math.Round(Convert.ToDouble(Data.disk2remain) / 1073741824, 2);
                            Data.disk2remain = Data.DD2remain.ToString() + " GB";
                        }
                        BarDD2.Maximum = (int)Data.DD2size;
                        BarDD2.Value   = (int)(Data.DD2size - Data.DD2remain);
                    }
                    labelDisk2Remain.Text = Data.disk2remain;
                    labelDisk2Total.Text  = Data.disk2size;
                    labelDisk2Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD2size - Data.DD2remain) / Data.DD2size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3    = CimSession.Create(Data.computer3, SessionOptions);
                    var        allVolumes3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");
                    foreach (CimInstance oneVolume3 in allVolumes3)
                    {
                        if (oneVolume3.CimInstanceProperties["DriveLetter"].ToString() == "DriveLetter = \"C:\"")
                        {
                            Data.disk3size   = String.Format("{0}", oneVolume3.CimInstanceProperties["Capacity"].Value);
                            Data.DD3size     = Math.Round(Convert.ToDouble(Data.disk3size) / 1073741824, 2);
                            Data.disk3size   = Data.DD3size.ToString() + " GB";
                            Data.disk3remain = String.Format("{0}", oneVolume3.CimInstanceProperties["FreeSpace"].Value);
                            Data.DD3remain   = Math.Round(Convert.ToDouble(Data.disk3remain) / 1073741824, 2);
                            Data.disk3remain = Data.DD3remain.ToString() + " GB";
                        }
                        BarDD3.Maximum = (int)Data.DD3size;
                        BarDD3.Value   = (int)(Data.DD3size - Data.DD3remain);
                    }
                    labelDisk3Remain.Text = Data.disk3remain;
                    labelDisk3Total.Text  = Data.disk3size;
                    labelDisk3Used.Text   = "Espace occupé (" + (Math.Round(((Data.DD3size - Data.DD3remain) / Data.DD3size), 2) * 100) + "%) :";
                }
                catch { Data.LoadPC3 = false; }
            }
        }
        private void RamScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1   = CimSession.Create(Data.computer1, SessionOptions);
                    var        allMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory1size = 0;
                    foreach (CimInstance oneMemory1 in allMemory1)
                    {
                        Data.ram1size      = String.Format("{0}", oneMemory1.CimInstanceProperties["Capacity"].Value);
                        Data.memory1size  += Math.Round(Convert.ToDouble(Data.ram1size) / 1073741824, 2);
                        Data.ram1size      = Data.memory1size.ToString() + " GB";
                        labelRam1Size.Text = Data.ram1size;
                    }
                    var allUsedMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory1 in allUsedMemory1)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory1.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram1percent);
                    }
                    labelRam1Used.Text = Data.ram1percent + "%";
                    BarRAM1.Value      = Data.ram1percent;
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2   = CimSession.Create(Data.computer2, SessionOptions);
                    var        allMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory2size = 0;
                    foreach (CimInstance oneMemory2 in allMemory2)
                    {
                        Data.ram2size      = String.Format("{0}", oneMemory2.CimInstanceProperties["Capacity"].Value);
                        Data.memory2size  += Math.Round(Convert.ToDouble(Data.ram2size) / 1073741824, 2);
                        Data.ram2size      = Data.memory2size.ToString() + " GB";
                        labelRam2Size.Text = Data.ram2size;
                    }
                    var allUsedMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory2 in allUsedMemory2)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory2.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram2percent);
                    }
                    labelRam2Used.Text = Data.ram2percent + "%";
                    BarRAM2.Value      = Data.ram2percent;
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3   = CimSession.Create(Data.computer3, SessionOptions);
                    var        allMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory");
                    Data.memory3size = 0;
                    foreach (CimInstance oneMemory3 in allMemory3)
                    {
                        Data.ram3size      = String.Format("{0}", oneMemory3.CimInstanceProperties["Capacity"].Value);
                        Data.memory3size  += Math.Round(Convert.ToDouble(Data.ram3size) / 1073741824, 2);
                        Data.ram3size      = Data.memory3size.ToString() + " GB";
                        labelRam3Size.Text = Data.ram3size;
                    }
                    var allUsedMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                    foreach (CimInstance oneUsedMemory3 in allUsedMemory3)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedMemory3.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram3percent);
                    }
                    labelRam3Used.Text = Data.ram3percent + "%";
                    BarRAM3.Value      = Data.ram3percent;
                }
                catch { Data.LoadPC3 = false; }
            }
        }
示例#22
0
        protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context)
        {
            string empty;
            string str;
            string empty1;
            string str1;

            typeof(GenericCimCmdletActivity).IsAssignableFrom(base.GetType());
            string[]     strArrays       = this.PSComputerName.Get(context);
            CimSession[] cimSessionArray = this.CimSession.Get(context);
            Uri          uri             = null;

            if (this.ResourceUri != null)
            {
                uri = this.ResourceUri.Get(context);
            }
            List <ActivityImplementationContext> activityImplementationContexts = new List <ActivityImplementationContext>();

            if (strArrays == null || (int)strArrays.Length <= 0)
            {
                ActivityImplementationContext    powerShell = this.GetPowerShell(context);
                CimActivityImplementationContext cimActivityImplementationContext = new CimActivityImplementationContext(powerShell, null, null, null, new AuthenticationMechanism?(AuthenticationMechanism.Default), false, 0, null, null, null, this.ModuleDefinition, uri);
                activityImplementationContexts.Add(cimActivityImplementationContext);
            }
            else
            {
                WSManSessionOptions wSManSessionOption = new WSManSessionOptions();
                uint?nullable = base.PSActionRunningTimeoutSec.Get(context);
                if (nullable.HasValue)
                {
                    wSManSessionOption.Timeout = TimeSpan.FromSeconds((double)((float)nullable.Value));
                }
                bool?nullable1 = this.PSUseSsl.Get(context);
                bool value     = false;
                if (nullable1.HasValue)
                {
                    wSManSessionOption.UseSsl = nullable1.Value;
                    value = nullable1.Value;
                }
                uint?nullable2 = this.PSPort.Get(context);
                uint num       = 0;
                if (nullable2.HasValue)
                {
                    wSManSessionOption.DestinationPort = nullable2.Value;
                    num = nullable2.Value;
                }
                PSSessionOption pSSessionOption = this.PSSessionOption.Get(context);
                if (pSSessionOption != null)
                {
                    wSManSessionOption.NoEncryption        = pSSessionOption.NoEncryption;
                    wSManSessionOption.CertCACheck         = pSSessionOption.SkipCACheck;
                    wSManSessionOption.CertCNCheck         = pSSessionOption.SkipCNCheck;
                    wSManSessionOption.CertRevocationCheck = pSSessionOption.SkipRevocationCheck;
                    if (pSSessionOption.UseUTF16)
                    {
                        wSManSessionOption.PacketEncoding = PacketEncoding.Utf16;
                    }
                    if (pSSessionOption.Culture != null)
                    {
                        wSManSessionOption.Culture = pSSessionOption.Culture;
                    }
                    if (pSSessionOption.UICulture != null)
                    {
                        wSManSessionOption.UICulture = pSSessionOption.UICulture;
                    }
                    if (pSSessionOption.ProxyCredential != null)
                    {
                        char[] chrArray = new char[1];
                        chrArray[0] = '\\';
                        string[] strArrays1 = pSSessionOption.ProxyCredential.UserName.Split(chrArray);
                        if ((int)strArrays1.Length >= 2)
                        {
                            empty = strArrays1[0];
                            str   = strArrays1[1];
                        }
                        else
                        {
                            empty = string.Empty;
                            str   = strArrays1[0];
                        }
                        wSManSessionOption.AddProxyCredentials(new CimCredential(PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pSSessionOption.ProxyAuthentication), empty, str, pSSessionOption.ProxyCredential.Password));
                    }
                    ProxyAccessType proxyAccessType = pSSessionOption.ProxyAccessType;
                    if (proxyAccessType == ProxyAccessType.IEConfig)
                    {
                        wSManSessionOption.ProxyType = ProxyType.InternetExplorer;
                        goto Label0;
                    }
                    else if (proxyAccessType == ProxyAccessType.WinHttpConfig)
                    {
                        wSManSessionOption.ProxyType = ProxyType.WinHttp;
                        goto Label0;
                    }
                    else if (proxyAccessType == (ProxyAccessType.IEConfig | ProxyAccessType.WinHttpConfig))
                    {
                        goto Label0;
                    }
                    else if (proxyAccessType == ProxyAccessType.AutoDetect)
                    {
                        wSManSessionOption.ProxyType = ProxyType.Auto;
                        goto Label0;
                    }
                }
Label0:
                PSCredential pSCredential = this.PSCredential.Get(context);
                string str2 = this.PSCertificateThumbprint.Get(context);
                if (pSCredential == null || str2 == null)
                {
                    PasswordAuthenticationMechanism cimPasswordAuthenticationMechanism = PasswordAuthenticationMechanism.Default;
                    AuthenticationMechanism?        nullable3 = this.PSAuthentication.Get(context);
                    if (nullable3.HasValue)
                    {
                        cimPasswordAuthenticationMechanism = PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(nullable3.Value);
                    }
                    if (str2 != null)
                    {
                        wSManSessionOption.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, str2));
                    }
                    if (pSCredential != null)
                    {
                        char[] chrArray1 = new char[1];
                        chrArray1[0] = '\\';
                        string[] strArrays2 = pSCredential.UserName.Split(chrArray1);
                        if ((int)strArrays2.Length >= 2)
                        {
                            empty1 = strArrays2[0];
                            str1   = strArrays2[1];
                        }
                        else
                        {
                            empty1 = string.Empty;
                            str1   = strArrays2[0];
                        }
                        wSManSessionOption.AddDestinationCredentials(new CimCredential(cimPasswordAuthenticationMechanism, empty1, str1, pSCredential.Password));
                    }
                    if (cimSessionArray == null || (int)cimSessionArray.Length <= 0)
                    {
                        string[] strArrays3 = strArrays;
                        for (int i = 0; i < (int)strArrays3.Length; i++)
                        {
                            string str3 = strArrays3[i];
                            ActivityImplementationContext    activityImplementationContext     = this.GetPowerShell(context);
                            CimActivityImplementationContext cimActivityImplementationContext1 = new CimActivityImplementationContext(activityImplementationContext, str3, pSCredential, str2, nullable3, value, num, pSSessionOption, null, wSManSessionOption, this.ModuleDefinition, uri);
                            activityImplementationContexts.Add(cimActivityImplementationContext1);
                        }
                    }
                    else
                    {
                        CimSession[] cimSessionArray1 = cimSessionArray;
                        for (int j = 0; j < (int)cimSessionArray1.Length; j++)
                        {
                            CimSession cimSession = cimSessionArray1[j];
                            ActivityImplementationContext    powerShell1 = this.GetPowerShell(context);
                            CimActivityImplementationContext cimActivityImplementationContext2 = new CimActivityImplementationContext(powerShell1, cimSession.ComputerName, pSCredential, str2, nullable3, value, num, pSSessionOption, cimSession, wSManSessionOption, this.ModuleDefinition, uri);
                            activityImplementationContexts.Add(cimActivityImplementationContext2);
                        }
                    }
                }
                else
                {
                    throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint);
                }
            }
            return(activityImplementationContexts);
        }
        private void CpuScan(bool PC1, bool PC2, bool PC3)
        {
            var password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1     = CimSession.Create(Data.computer1, SessionOptions);
                    var        allUsedCore1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore1 in allUsedCore1)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore1.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu1percent);
                    }
                    labelCpu1Used.Text = Data.cpu1percent + "%";
                    BarCPU1.Value      = Data.cpu1percent;
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2     = CimSession.Create(Data.computer2, SessionOptions);
                    var        allUsedCore2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore2 in allUsedCore2)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore2.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu2percent);
                    }
                    labelCpu2Used.Text = Data.cpu2percent + "%";
                    BarCPU2.Value      = Data.cpu2percent;
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3     = CimSession.Create(Data.computer3, SessionOptions);
                    var        allUsedCore3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
                    foreach (CimInstance oneUsedCore3 in allUsedCore3)
                    {
                        Int32.TryParse(String.Format("{0}", oneUsedCore3.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu3percent);
                    }
                    labelCpu3Used.Text = Data.cpu3percent + "%";
                    BarCPU3.Value      = Data.cpu3percent;
                }
                catch { Data.LoadPC3 = false; }
            }
        }
示例#24
0
        internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential)
        {
            WSManSessionOptions             wSManSessionOption;
            PasswordAuthenticationMechanism authentication;

            DebugHelper.WriteLogEx();
            CimSessionOptions dComSessionOption = null;

            /* Requires Authentication for Remote Host */
            if (this.credential == null && ComputerName != null)
            {
                bool requiredAuth = false;
                foreach (var c in ComputerName)
                {
                    if (c != null && !c.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                    {
                        requiredAuth = true;
                        break;
                    }
                }
                if (requiredAuth)
                {
                    TrySetCredentials();
                }
            }

            if (this.SessionOption != null)
            {
                if (this.SessionOption as WSManSessionOptions == null)
                {
                    dComSessionOption = new DComSessionOptions(this.sessionOption as DComSessionOptions);
                }
                else
                {
                    dComSessionOption = new WSManSessionOptions(this.sessionOption as WSManSessionOptions);
                }
            }
            outputOptions    = null;
            outputCredential = null;
            if (dComSessionOption != null)
            {
                DComSessionOptions dComSessionOption1 = dComSessionOption as DComSessionOptions;
                if (dComSessionOption1 != null)
                {
                    bool   flag  = false;
                    string empty = string.Empty;
                    if (this.CertificateThumbprint != null)
                    {
                        flag  = true;
                        empty = "CertificateThumbprint";
                    }
                    if (this.portSet)
                    {
                        flag  = true;
                        empty = "Port";
                    }
                    if (flag)
                    {
                        base.ThrowConflictParameterWasSet("New-CimSession", empty, "DComSessionOptions");
                        return;
                    }
                }
            }

            if (this.portSet || this.CertificateThumbprint != null)
            {
                if (dComSessionOption == null)
                {
                    wSManSessionOption = new WSManSessionOptions();
                }
                else
                {
                    wSManSessionOption = dComSessionOption as WSManSessionOptions;
                }
                WSManSessionOptions port = wSManSessionOption;
                if (this.portSet)
                {
                    port.DestinationPort = this.Port;
                    this.portSet         = false;
                }
                if (this.CertificateThumbprint != null)
                {
                    CimCredential cimCredential = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint);
                    port.AddDestinationCredentials(cimCredential);
                }
                dComSessionOption = port;
            }
            if (this.operationTimeoutSet && dComSessionOption != null)
            {
                dComSessionOption.Timeout = TimeSpan.FromSeconds((double)((float)this.OperationTimeoutSec));
            }

            if (this.authenticationSet || this.credential != null)
            {
                if (this.authenticationSet)
                {
                    authentication = this.Authentication;
                }
                else
                {
                    authentication = PasswordAuthenticationMechanism.Default;
                }
                PasswordAuthenticationMechanism passwordAuthenticationMechanism = authentication;
                if (this.authenticationSet)
                {
                    this.authenticationSet = false;
                }
                CimCredential cimCredential1 = base.CreateCimCredentials(this.Credential, passwordAuthenticationMechanism, "New-CimSession", "Authentication");
                if (cimCredential1 != null)
                {
                    object[] objArray = new object[1];
                    objArray [0] = cimCredential1;
                    DebugHelper.WriteLog("Credentials: {0}", 1, objArray);
                    outputCredential = cimCredential1;
                    if (dComSessionOption != null)
                    {
                        object[] objArray1 = new object[1];
                        objArray1 [0] = dComSessionOption;
                        DebugHelper.WriteLog("Add credentials to option: {0}", 1, objArray1);
                        dComSessionOption.AddDestinationCredentials(cimCredential1);
                    }
                }
                else
                {
                    return;
                }
            }

            object[] objArray2 = new object[1];
            objArray2[0] = outputOptions;
            DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, objArray2);
            outputOptions = dComSessionOption;
        }
示例#25
0
        protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context)
        {
            bool needRunspace = !typeof(GenericCimCmdletActivity).IsAssignableFrom(this.GetType());

            string[]     computernames = PSComputerName.Get(context);
            CimSession[] sessions      = this.CimSession.Get(context);
            Uri          resourceUri   = null;

            if (ResourceUri != null)
            {
                resourceUri = ResourceUri.Get(context);
            }

            List <ActivityImplementationContext> commands = new List <ActivityImplementationContext>();

            // Configure the remote connectivity options...
            if (computernames != null && computernames.Length > 0)
            {
                WSManSessionOptions sessionOptions = new WSManSessionOptions();

                // Set a timeout on the connection...
                uint?timeout = PSActionRunningTimeoutSec.Get(context);
                if (timeout.HasValue)
                {
                    sessionOptions.Timeout = TimeSpan.FromSeconds((double)(timeout.Value));
                }

                // See if we should use SSL or not...
                bool?useSsl = PSUseSsl.Get(context);
                bool sessionOptionUseSsl = false;

                if (useSsl.HasValue)
                {
                    sessionOptions.UseSsl = useSsl.Value;
                    sessionOptionUseSsl   = useSsl.Value;
                }

                // Set the port to use
                uint?port = PSPort.Get(context);
                uint sessionOptionPort = 0;

                if (port.HasValue)
                {
                    sessionOptions.DestinationPort = port.Value;
                    sessionOptionPort = port.Value;
                }

                // Map over options from PSSessionConfig to WSManSessionOptions
                PSSessionOption pso = PSSessionOption.Get(context);
                if (pso != null)
                {
                    sessionOptions.NoEncryption        = pso.NoEncryption;
                    sessionOptions.CertCACheck         = pso.SkipCACheck;
                    sessionOptions.CertCNCheck         = pso.SkipCNCheck;
                    sessionOptions.CertRevocationCheck = pso.SkipRevocationCheck;

                    if (pso.UseUTF16)
                    {
                        sessionOptions.PacketEncoding = PacketEncoding.Utf16;
                    }

                    if (pso.Culture != null)
                    {
                        sessionOptions.Culture = pso.Culture;
                    }

                    if (pso.UICulture != null)
                    {
                        sessionOptions.UICulture = pso.UICulture;
                    }

                    if (pso.ProxyCredential != null)
                    {
                        string[] parts = pso.ProxyCredential.UserName.Split('\\');
                        string   domain, userid;
                        if (parts.Length < 2)
                        {
                            domain = string.Empty;
                            userid = parts[0];
                        }
                        else
                        {
                            domain = parts[0];
                            userid = parts[1];
                        }

                        sessionOptions.AddProxyCredentials(
                            new CimCredential(ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pso.ProxyAuthentication),
                                              domain, userid, pso.ProxyCredential.Password));
                    }

                    switch (pso.ProxyAccessType)
                    {
                    case ProxyAccessType.WinHttpConfig:
                        sessionOptions.ProxyType = ProxyType.WinHttp;
                        break;

                    case ProxyAccessType.AutoDetect:
                        sessionOptions.ProxyType = ProxyType.Auto;
                        break;

                    case ProxyAccessType.IEConfig:
                        sessionOptions.ProxyType = ProxyType.InternetExplorer;
                        break;
                    }
                }

                PSCredential pscreds = PSCredential.Get(context);
                string       certificateThumbprint = PSCertificateThumbprint.Get(context);

                if (pscreds != null && certificateThumbprint != null)
                {
                    throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint);
                }

                PasswordAuthenticationMechanism passwordAuthenticationMechanism = PasswordAuthenticationMechanism.Default;
                AuthenticationMechanism?        authenticationMechanism         = PSAuthentication.Get(context);

                if (authenticationMechanism.HasValue)
                {
                    passwordAuthenticationMechanism = ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(authenticationMechanism.Value);
                }


                if (certificateThumbprint != null)
                {
                    sessionOptions.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, certificateThumbprint));
                }

                if (pscreds != null)
                {
                    string[] parts = pscreds.UserName.Split('\\');
                    string   domain, userid;
                    if (parts.Length < 2)
                    {
                        domain = string.Empty;
                        userid = parts[0];
                    }
                    else
                    {
                        domain = parts[0];
                        userid = parts[1];
                    }

                    sessionOptions.AddDestinationCredentials(new CimCredential(passwordAuthenticationMechanism, domain, userid, pscreds.Password));
                }

                // Create the PowerShell instance, and add the script to it.
                if (sessions != null && sessions.Length > 0)
                {
                    foreach (CimSession session in sessions)
                    {
                        ActivityImplementationContext configuredCommand = GetPowerShell(context);

                        CimActivityImplementationContext activityImplementationContext =
                            new CimActivityImplementationContext(
                                configuredCommand,
                                session.ComputerName,
                                pscreds,
                                certificateThumbprint,
                                authenticationMechanism,
                                sessionOptionUseSsl,
                                sessionOptionPort,
                                pso,
                                session,
                                sessionOptions,
                                ModuleDefinition,
                                resourceUri);

                        commands.Add(activityImplementationContext);
                        //if (needRunspace)
                        //    GetRunspaceForCimCmdlet(context, activityImplementationContext);
                    }
                }
                else if (this.PSCommandName.Equals("CimCmdlets\\New-CimSession", StringComparison.OrdinalIgnoreCase))
                {
                    // NewCimSession activity is a special one as it creates the required sessions based on number of computers specified in one go.

                    ActivityImplementationContext baseContext = GetPowerShell(context);

                    CimActivityImplementationContext activityImplementationContext =
                        new CimActivityImplementationContext(baseContext,
                                                             null,     // ComputerName
                                                             pscreds,
                                                             certificateThumbprint,
                                                             authenticationMechanism,
                                                             sessionOptionUseSsl,
                                                             sessionOptionPort,
                                                             pso,
                                                             null,    // session
                                                             sessionOptions,
                                                             ModuleDefinition,
                                                             resourceUri);

                    commands.Add(activityImplementationContext);
                }
                else
                {
                    foreach (string computer in computernames)
                    {
                        ActivityImplementationContext baseContext = GetPowerShell(context);

                        CimActivityImplementationContext activityImplementationContext =
                            new CimActivityImplementationContext(baseContext,
                                                                 computer,
                                                                 pscreds,
                                                                 certificateThumbprint,
                                                                 authenticationMechanism,
                                                                 sessionOptionUseSsl,
                                                                 sessionOptionPort,
                                                                 pso,
                                                                 null, // session
                                                                 sessionOptions,
                                                                 ModuleDefinition,
                                                                 resourceUri);

                        commands.Add(activityImplementationContext);
                    }
                }
            }
            // Configure the local invocation options
            else
            {
                // Create the PowerShell instance, and add the script to it.
                ActivityImplementationContext    baseContext = GetPowerShell(context);
                CimActivityImplementationContext activityImplementationContext =
                    new CimActivityImplementationContext(baseContext,
                                                         null,  // ComputerName
                                                         null,  // Credential
                                                         null,  // CertificateThumbprint
                                                         AuthenticationMechanism.Default,
                                                         false, // UseSsl
                                                         0,     // Port
                                                         null,  // PSSessionOption
                                                         null,  // Session
                                                         null,  // CimSessionOptions
                                                         ModuleDefinition,
                                                         resourceUri);

                commands.Add(activityImplementationContext);
            }

            return(commands);
        }
        private void AppScan(bool PC1, bool PC2, bool PC3)
        {
            Boolean isOn     = false;
            var     password = new SecureString();

            foreach (char c in Data.rudepassword)
            {
                password.AppendChar(c);
            }
            CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password);

            WSManSessionOptions SessionOptions = new WSManSessionOptions();

            SessionOptions.AddDestinationCredentials(Credentials);
            if (PC1)
            {
                try
                {
                    CimSession Session1 = CimSession.Create(Data.computer1, SessionOptions);
                    var        allApp1  = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp1 in allApp1)
                    {
                        if (oneApp1.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp1.Text = "Online";
                            buttonShowStatut1.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp1.Text = "Offline";
                        buttonShowStatut1.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC1 = false; }
            }

            if (PC2)
            {
                try
                {
                    CimSession Session2 = CimSession.Create(Data.computer2, SessionOptions);
                    var        allApp2  = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp2 in allApp2)
                    {
                        if (oneApp2.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp2.Text = "Online";
                            buttonShowStatut2.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp2.Text = "Offline";
                        buttonShowStatut2.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC2 = false; }
            }

            if (PC3)
            {
                try
                {
                    CimSession Session3 = CimSession.Create(Data.computer3, SessionOptions);
                    var        allApp3  = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    isOn = false;
                    foreach (CimInstance oneApp3 in allApp3)
                    {
                        if (oneApp3.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"")
                        {
                            labelApp3.Text = "Online";
                            buttonShowStatut3.BackColor = System.Drawing.Color.Lime;
                            isOn = true;
                        }
                    }
                    if (!isOn)
                    {
                        labelApp3.Text = "Offline";
                        buttonShowStatut3.BackColor = System.Drawing.Color.DarkRed;
                    }
                }
                catch { Data.LoadPC3 = false; }
            }
        }
示例#27
0
        internal WSManSessionOptions CreateWSMANSessionOptions()
        {
            WSManSessionOptions wSManSessionOption = new WSManSessionOptions();

            if (!this.noEncryptionSet)
            {
                wSManSessionOption.NoEncryption = false;
            }
            else
            {
                wSManSessionOption.NoEncryption = true;
                this.noEncryptionSet            = false;
            }
            if (!this.skipCACheckSet)
            {
                wSManSessionOption.CertCACheck = true;
            }
            else
            {
                wSManSessionOption.CertCACheck = false;
                this.skipCACheckSet            = false;
            }
            if (!this.skipCNCheckSet)
            {
                wSManSessionOption.CertCNCheck = true;
            }
            else
            {
                wSManSessionOption.CertCNCheck = false;
                this.skipCNCheckSet            = false;
            }
            if (!this.skipRevocationCheckSet)
            {
                wSManSessionOption.CertRevocationCheck = true;
            }
            else
            {
                wSManSessionOption.CertRevocationCheck = false;
                this.skipRevocationCheckSet            = false;
            }
            if (!this.encodeportinserviceprincipalnameSet)
            {
                wSManSessionOption.EncodePortInServicePrincipalName = false;
            }
            else
            {
                wSManSessionOption.EncodePortInServicePrincipalName = this.EncodePortInServicePrincipalName;
                this.encodeportinserviceprincipalnameSet            = false;
            }
            if (!this.encodingSet)
            {
                wSManSessionOption.PacketEncoding = PacketEncoding.Utf8;
            }
            else
            {
                wSManSessionOption.PacketEncoding = this.Encoding;
            }
            if (this.HttpPrefix != null)
            {
                wSManSessionOption.HttpUrlPrefix = this.HttpPrefix;
            }
            if (!this.maxenvelopesizekbSet)
            {
                wSManSessionOption.MaxEnvelopeSize = 0;
            }
            else
            {
                wSManSessionOption.MaxEnvelopeSize = this.MaxEnvelopeSizeKB;
            }
            if (!string.IsNullOrWhiteSpace(this.ProxyCertificateThumbprint))
            {
                CimCredential cimCredential = new CimCredential(CertificateAuthenticationMechanism.Default, this.ProxyCertificateThumbprint);
                wSManSessionOption.AddProxyCredentials(cimCredential);
            }
            if (this.proxyauthenticationSet)
            {
                this.proxyauthenticationSet = false;
                DebugHelper.WriteLogEx("create credential", 1);
                CimCredential cimCredential1 = base.CreateCimCredentials(this.ProxyCredential, this.ProxyAuthentication, "New-CimSessionOption", "ProxyAuthentication");
                if (cimCredential1 != null)
                {
                    try
                    {
                        DebugHelper.WriteLogEx("Add proxy credential", 1);
                        wSManSessionOption.AddProxyCredentials(cimCredential1);
                    }
                    catch (Exception exception1)
                    {
                        Exception exception = exception1;
                        DebugHelper.WriteLogEx(exception.ToString(), 1);
                        throw exception;
                    }
                }
            }
            if (!this.proxytypeSet)
            {
                wSManSessionOption.ProxyType = ProxyType.WinHttp;
            }
            else
            {
                wSManSessionOption.ProxyType = this.ProxyType;
                this.proxytypeSet            = false;
            }
            if (!this.usesslSet)
            {
                wSManSessionOption.UseSsl = false;
            }
            else
            {
                wSManSessionOption.UseSsl = this.UseSsl;
                this.usesslSet            = false;
            }
            wSManSessionOption.DestinationPort = 0;
            return(wSManSessionOption);
        }
        /// <summary>
        /// Build a CimSessionOptions, used to create CimSession.
        /// </summary>
        /// <returns>Null means no prefer CimSessionOptions.</returns>
        internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential)
        {
            DebugHelper.WriteLogEx();

            CimSessionOptions options = null;

            if (this.SessionOption != null)
            {
                // clone the sessionOption object
                if (this.SessionOption is WSManSessionOptions)
                {
                    options = new WSManSessionOptions(this.SessionOption as WSManSessionOptions);
                }
                else
                {
                    options = new DComSessionOptions(this.SessionOption as DComSessionOptions);
                }
            }

            outputOptions    = null;
            outputCredential = null;
            if (options != null)
            {
                DComSessionOptions dcomOptions = (options as DComSessionOptions);
                if (dcomOptions != null)
                {
                    bool   conflict      = false;
                    string parameterName = string.Empty;
                    if (this.CertificateThumbprint != null)
                    {
                        conflict      = true;
                        parameterName = @"CertificateThumbprint";
                    }

                    if (portSet)
                    {
                        conflict      = true;
                        parameterName = @"Port";
                    }

                    if (conflict)
                    {
                        ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions");
                        return;
                    }
                }
            }

            if (portSet || (this.CertificateThumbprint != null))
            {
                WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions;
                if (portSet)
                {
                    wsmanOptions.DestinationPort = this.Port;
                    portSet = false;
                }

                if (this.CertificateThumbprint != null)
                {
                    CimCredential credentials = new(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint);
                    wsmanOptions.AddDestinationCredentials(credentials);
                }

                options = wsmanOptions;
            }

            if (this.operationTimeoutSet)
            {
                if (options != null)
                {
                    options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec);
                }
            }

            if (this.authenticationSet || (this.Credential != null))
            {
                PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default;
                if (this.authenticationSet)
                {
                    this.authenticationSet = false;
                }

                CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication");
                if (credentials == null)
                {
                    return;
                }

                DebugHelper.WriteLog("Credentials: {0}", 1, credentials);
                outputCredential = credentials;
                if (options != null)
                {
                    DebugHelper.WriteLog("Add credentials to option: {0}", 1, options);
                    options.AddDestinationCredentials(credentials);
                }
            }

            DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions);
            outputOptions = options;
        }
        private void submitNameButton_Click(object sender, RoutedEventArgs e)
        {
            //clear out the textboxes
            outputTextbox.Text       = "";
            diskInfoTextbox.Text     = "";
            computerInfoTextbox.Text = "";
            logTextbox.Text          = "";

            //computer name, domain, username, and password
            //used to actually connect to a machine and authenticate
            string computerName = computerNameTextbox.Text;
            string domain       = "net.ucf.edu";

/*          string username = usernameTextbox.Text;
 *          string password = passwordTextbox.Password;*/

            if (validateComputerName(computerName) == true && pingHost(computerName) == true)
            {
                logTextbox.AppendText($"Ping Successful for {computerName}\n");

                //computerNameValidLabel.Content = "";

                SecureString securePassword = new SecureString(); //change the password to a secure string
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }

                CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, domain, username, securePassword);

                WSManSessionOptions SessionOptions = new WSManSessionOptions();
                SessionOptions.AddDestinationCredentials(Credentials);

                CimSession Session = CimSession.Create(computerName, SessionOptions);

                //var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Volume");

                //========================================== USERNAME ===================================================

                var allUserNames = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_ComputerSystem");

                foreach (CimInstance o in allUserNames)
                {
                    userLoggedInLablel1.Content = "User Logged In: " + Convert.ToString(o.CimInstanceProperties["Username"].Value);
                    logTextbox.AppendText($"{userLoggedInLablel1.Content}\n");
                }

                //========================================== RAM ===================================================

                var allComputerSystem = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");

                double freeRam       = 0;
                double totalRam      = 0;
                double usedRam       = 0;
                double ramPercentage = 0;

                foreach (CimInstance o in allComputerSystem)
                {
                    freeRam  = Convert.ToDouble(o.CimInstanceProperties["FreePhysicalMemory"].Value) / Math.Pow(2, 20);
                    totalRam = Convert.ToDouble(o.CimInstanceProperties["TotalVisibleMemorySize"].Value) / Math.Pow(2, 20);

                    usedRam = (totalRam - freeRam);

                    freeRam  = Math.Round(freeRam, 3);
                    usedRam  = Math.Round(usedRam, 3);
                    totalRam = Math.Round(totalRam, 3);

                    logTextbox.AppendText($"Used RAM: {Convert.ToString(usedRam)} GB\n");
                    logTextbox.AppendText($"Total RAM: {Convert.ToString(totalRam)} GB\n");
                }

                ramPercentage = (usedRam / totalRam) * 100;
                ramPercentage = Math.Round(ramPercentage, 3);

                liveRamProgressBar1.Value = ramPercentage;
                ramComputerLabel1.Content = $"RAM: {usedRam} GB / {totalRam} GB | {ramPercentage}%";

                //========================================== PROGRAMS ===================================================

                int totalPrograms = 0;

                if (programCheckbox.IsChecked == true)
                {
                    logTextbox.AppendText("Importing Programs\n");
                    var allPrograms = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Product");
                    foreach (CimInstance program in allPrograms)
                    {
                        string text = Convert.ToString(program.CimInstanceProperties["Name"].Value);
                        outputTextbox.AppendText(text + "\n");
                        totalPrograms++;
                    }
                }

                totalLabel.Content = $"Total Programs: {totalPrograms}";
                logTextbox.AppendText($"Total Programs: {totalPrograms}\n");
                //========================================== DISK INFO ===================================================
                if (diskInfoCheckbox.IsChecked == true)
                {
                    logTextbox.AppendText("Scanning Disk Drives\n");
                    var allPDisks = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive");
                    foreach (CimInstance pDisk in allPDisks)
                    {
                        string diskName     = Convert.ToString(pDisk.CimInstanceProperties["Name"].Value);
                        string modelName    = Convert.ToString(pDisk.CimInstanceProperties["Model"].Value);
                        string status       = Convert.ToString(pDisk.CimInstanceProperties["Status"].Value);
                        string serialNumber = Convert.ToString(pDisk.CimInstanceProperties["SerialNumber"].Value);

                        double size = Convert.ToDouble(pDisk.CimInstanceProperties["Size"].Value) / Math.Pow(2, 20);

                        diskInfoTextbox.AppendText($"Name: {diskName}\n" +
                                                   $"Model: {modelName}\n" +
                                                   $"Status: {status}\n" +
                                                   $"Serial Number: {serialNumber}\n" +
                                                   $"Size: {Math.Round(size, 3)} GB");
                    }
                }
                //======================================= COMPUTER INFO ===================================================
                if (computerInfoCheckbox.IsChecked == true)
                {
                    var allOS = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");
                    //var allComputerSystem = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_OperatingSystem");

                    //============== allOS ==============
                    foreach (CimInstance os in allOS)
                    {
                        //======= Available Memory =======
                        string availableMemory = Convert.ToString(Convert.ToDouble(os.CimInstanceProperties["FreePhysicalMemory"].Value) / Math.Pow(2, 10));
                        availableMemory = Convert.ToString(Math.Round(Convert.ToDouble(availableMemory), 0, MidpointRounding.AwayFromZero));
                        //======= Last Boot Up Time =======
                        DateTime lastBootUpTimeDate = Convert.ToDateTime(os.CimInstanceProperties["LastBootUpTime"].Value);
                        string   lastBootUpTime     = lastBootUpTimeDate.ToString(@"yyyy-MM-dd hh:mm:ss");
                        //======= Operating System =======
                        string osName = Convert.ToString(os.CimInstanceProperties["Caption"].Value);
                        //======= OS Install Date =======
                        DateTime osInstallDate = Convert.ToDateTime(os.CimInstanceProperties["InstallDate"].Value);
                        string   osInstall     = osInstallDate.ToString(@"yyyy-MM-dd hh:mm:ss");
                        //======= OS Version =======
                        string version = Convert.ToString(os.CimInstanceProperties["Version"].Value);

                        computerInfoTextbox.AppendText($"Operating System: {osName}\n");
                        computerInfoTextbox.AppendText($"Windows Version: {version}\n");
                        computerInfoTextbox.AppendText($"Free Memory [MB]: {availableMemory}\n");
                        computerInfoTextbox.AppendText($"Last Boot Up Time: {lastBootUpTime}\n");
                        computerInfoTextbox.AppendText($"OS Install Date: {osInstall}\n");
                    }

                    //============== allComputerSystem ==============
                    foreach (CimInstance comp in allComputerSystem)
                    {
                        //======= User Logged In =======
                        string userLoggedIn = "";
                        try { Convert.ToString(comp.CimInstanceProperties["UserName"].Value); } catch { userLoggedIn = "None"; }


                        computerInfoTextbox.AppendText($"User Logged In: {userLoggedIn}\n");
                    }
                }

                if (processCheckbox.IsChecked == true)
                {
                    var       allProcessList   = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process");
                    ArrayList processArrayList = new ArrayList();

                    foreach (CimInstance o in allProcessList)
                    {
                        processArrayList.Add(Convert.ToString(o.CimInstanceProperties["Name"].Value));
                        if (Convert.ToString(o.CimInstanceProperties["Name"].Value).Equals("svchost.exe") == false)
                        {
                            processComputerTextbox1.AppendText(Convert.ToString(o.CimInstanceProperties["Name"].Value) + "\n");
                        }
                    }

                    processCountLabel1.Content = $"Total Processes: {processArrayList.Count}";
                    logTextbox.AppendText($"Process Count: {processArrayList.Count}");
                }
            }
            else
            {
                //computerNameValidLabel.Content = "Computer Name Invalid";
                //computerNameValidLabel.Foreground = Brushes.Red;
            }
        }