/// <summary> /// Create a new <see cref="CimSession"/> base on given cmdlet /// and its parameter. /// </summary> /// <param name="cmdlet"></param> /// <param name="sessionOptions"></param> /// <param name="credential"></param> internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { DebugHelper.WriteLogEx(); IEnumerable <string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { CimSessionProxy proxy; if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); CimTestCimSessionContext context = new CimTestCimSessionContext(proxy, wrapper); proxy.ContextObject = context; // Skip test the connection if user intend to if (cmdlet.SkipTestConnection.IsPresent) { AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet)); } else { // CimSession will be returned as part of TestConnection this.cimTestSession.TestCimSession(computerName, proxy); } } }
protected CimSessionProxy CreateCimSessionProxy(string computerName, CimSessionOptions options) { CimSessionProxy cimSessionProxy = new CimSessionProxy(computerName, options); this.SubscribeEventAndAddProxytoCache(cimSessionProxy); return(cimSessionProxy); }
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)); }
public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism?authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri) { if (activityImplementationContext != null) { base.PowerShellInstance = activityImplementationContext.PowerShellInstance; this.ResourceUri = resourceUri; this.ComputerName = computerName; base.PSCredential = credential; base.PSCertificateThumbprint = certificateThumbprint; base.PSAuthentication = authenticationMechanism; base.PSUseSsl = new bool?(useSsl); base.PSPort = new uint?(port); base.PSSessionOption = sessionOption; this.Session = session; this.SessionOptions = cimSessionOptions; if (moduleDefinition != null) { CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition); this._moduleDefinition = moduleDefinition; } return; } else { throw new ArgumentNullException("activityImplementationContext"); } }
internal static CimSession CreateCimSession( string computerName, PSCredential credential, string authentication, bool isLocalHost, PSCmdlet cmdlet, CancellationToken cancellationToken) { if (isLocalHost) { return(CimSession.Create(null)); } var sessionOptions = new CimSessionOptions(); CimCredential cimCredentials = GetCimCredentials(authentication, credential); if (cimCredentials != null) { sessionOptions.AddDestinationCredentials(cimCredentials); } CimSession cimSession = CimSession.Create(computerName, sessionOptions); return(cimSession); }
protected override void ProcessRecord() { CimSessionOptions cimSessionOption = null; CimCredential cimCredential = null; this.BuildSessionOptions(out cimSessionOption, out cimCredential); this.cimNewSession.NewCimSession(this, cimSessionOption, cimCredential); this.cimNewSession.ProcessActions(this.CmdletOperation); }
public SessionEntry(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { SessionOptions = sessionOptions; _credential = credential; _certificateThumbprint = certificateThumbprint; _authenticationMechanism = authenticationMechanism; _useSsl = useSsl; _port = port; _psSessionOption = pssessionOption; Session = CimSession.Create(computerName, sessionOptions); }
internal static CimSession CreateCimSession(string computerName, PSCredential credential, string authentication, CancellationToken cancellationToken, PSCmdlet cmdlet) { CimSessionOptions sessionOptions = new CimSessionOptions(); CimCredential cimCredentials = GetCimCredentials(authentication, credential); if (cimCredentials != null) { sessionOptions.AddDestinationCredentials(cimCredentials); } return(CimSession.Create(computerName, sessionOptions)); }
public static CimSession Create(string computerName, CimSessionOptions sessionOptions) { IPAddress pAddress = null; InstanceHandle instanceHandle = null; SessionHandle sessionHandle = null; CimSession cimSession; string protocol; DestinationOptionsHandle destinationOptionsHandle; string str = computerName; if (!string.IsNullOrEmpty(str) && IPAddress.TryParse(str, out pAddress) && pAddress.AddressFamily == AddressFamily.InterNetworkV6 && str[0] != '[') { str = string.Concat("[", str, "]"); } IDisposable disposable = CimApplication.AssertNoPendingShutdown(); using (disposable) { ApplicationHandle handle = CimApplication.Handle; if (sessionOptions == null) { protocol = null; } else { protocol = sessionOptions.Protocol; } string str1 = str; if (sessionOptions == null) { destinationOptionsHandle = null; } else { destinationOptionsHandle = sessionOptions.DestinationOptionsHandle ?? sessionOptions.DestinationOptionsHandleOnDemand; } MiResult miResult = ApplicationMethods.NewSession(handle, protocol, str1, destinationOptionsHandle, out instanceHandle, out sessionHandle); if (miResult != MiResult.NOT_FOUND) { CimException.ThrowIfMiResultFailure(miResult, instanceHandle); CimSession cimSession1 = new CimSession(sessionHandle, computerName); cimSession = cimSession1; } else { throw new CimException(miResult, null, instanceHandle, System.Management.Automation.Strings.UnrecognizedProtocolName); } } return cimSession; }
static CimSession CreateSession(string host, bool DCOM) { Console.WriteLine("Querying localhost"); // if (DCOM) { var so = new DComSessionOptions { Timeout = TimeSpan.FromSeconds(30) }; return(CimSession.Create(host, so)); } else { CimSessionOptions so = new CimSessionOptions(); return(CimSession.Create(host, so)); } }
private static IReadOnlyCollection <HvKvpExchangeComponent> GetKvpExchangeComponents(HvVirtualMachine vm) { var options = new CimSessionOptions(); using (var session = CimSession.Create(vm.CimMetadata.ServerName, options)) { var cimOpsOptions = new CimOperationOptions(); var kvpExchangeComponents = GetRelatedInstance(session, VirtualizationNamespace, vm.CimMetadata.ObjectPath, "Msvm_SystemDevice", "Msvm_KvpExchangeComponent", "PartComponent", "GroupComponent", cimOpsOptions); var kvpComponents = new List <HvKvpExchangeComponent>(); foreach (var c in kvpExchangeComponents) { kvpComponents.Add(new HvKvpExchangeComponent(c)); c.Dispose(); } return(kvpComponents.AsReadOnly()); } }
static void Main(string[] args) { var hvHostMachine = "localhost"; var options = new CimSessionOptions(); using (var session = CimSession.Create(hvHostMachine, options)) { const string namespaceName = @"root\virtualization\v2"; const string query = "SELECT * FROM Msvm_ComputerSystem"; var cimOpsOptions = new CimOperationOptions(); var computerSystems = session.QueryInstances(namespaceName, "WQL", query, cimOpsOptions); foreach (var instance in computerSystems) { Console.WriteLine(instance.CimInstanceProperties["ElementName"].Value.ToString()); instance.Dispose(); } } }
public static CimAsyncResult<CimSession> CreateAsync(string computerName, CimSessionOptions sessionOptions) { IObservable<CimSession> cimAsyncDelegatedObservable = new CimAsyncDelegatedObservable<CimSession>((IObserver<CimSession> observer) => { CimSession cimSession = null; try { cimSession = CimSession.Create(computerName, sessionOptions); } catch (Exception exception1) { Exception exception = exception1; observer.OnError(exception); } observer.OnNext(cimSession); observer.OnCompleted(); } ); return new CimAsyncResult<CimSession>(cimAsyncDelegatedObservable); }
private static HvVirtualMachine GetVirtualMachine(string hvHostMachine, Guid vmGuid) { var vms = new List <HvVirtualMachine>(); var options = new CimSessionOptions(); using (var session = CimSession.Create(hvHostMachine, options)) { var vmQuery = string.Format("SELECT * FROM Msvm_ComputerSystem WHERE Name = '{0}'", vmGuid.ToString()); var cimOpsOptions = new CimOperationOptions(); var computerSystems = session.QueryInstances(VirtualizationNamespace, "WQL", vmQuery, cimOpsOptions); foreach (var cs in computerSystems) { vms.Add(new HvVirtualMachine(cs)); cs.Dispose(); } } return(vms.FirstOrDefault()); }
private static IReadOnlyCollection <HvVirtualMachine> GetVMs(string hvHostMachine) { var vms = new List <HvVirtualMachine>(); var options = new CimSessionOptions(); using (var session = CimSession.Create(hvHostMachine, options)) { const string query = "SELECT * FROM Msvm_ComputerSystem WHERE Caption = 'Virtual Machine'"; var cimOpsOptions = new CimOperationOptions(); var computerSystems = session.QueryInstances(VirtualizationNamespace, "WQL", query, cimOpsOptions); foreach (var instance in computerSystems) { vms.Add(new HvVirtualMachine(instance)); instance.Dispose(); } } return(vms.AsReadOnly()); }
/// <summary> /// Creates a new collection of <see cref="ComponentDescriptor"/> that describes the specified /// components installed in system associated with a network host-name. /// </summary> /// <param name="hostName"> /// The network host-name that should be described. /// </param> /// <returns> /// The resulting collection of <see cref="ComponentDescriptor"/> if successful. /// </returns> public static IEnumerable <ComponentDescriptor> Create(string hostName) { // Validate parameters. if (String.IsNullOrWhiteSpace(hostName)) { throw new ArgumentNullException("hostName"); } CimSessionOptions sessionOptions = new CimSessionOptions() { }; sessionOptions.AddDestinationCredentials(new CimCredential(ImpersonatedAuthenticationMechanism.Negotiate)); CimSession session = CimSession.Create(hostName, sessionOptions); return (ComponentDescriptor.GetProcessors(session) .Concat(ComponentDescriptor.GetMemory(session)) .Concat(ComponentDescriptor.GetHardDrives(session)) .ToList()); }
/// <summary> /// Creates a new <see cref="AssetDescriptor"/> that describes the specified /// network host-name. /// </summary> /// <param name="hostName"> /// The network host-name that should be described. /// </param> /// <returns> /// The resulting <see cref="AssetDescriptor"/> if successful. /// </returns> public static AssetDescriptor Create(string hostName) { CimSessionOptions sessionOptions = new CimSessionOptions() { }; sessionOptions.AddDestinationCredentials(new CimCredential(ImpersonatedAuthenticationMechanism.Negotiate)); CimSession session = CimSession.Create(hostName, sessionOptions); CimInstance computerDetails = session.EnumerateInstances(@"root\cimv2", "Win32_ComputerSystem").FirstOrDefault(); CimInstance productDetails = session.EnumerateInstances(@"root\cimv2", "Win32_ComputerSystemProduct").FirstOrDefault(); return(new AssetDescriptor() { Serial = Convert.ToString(productDetails.CimInstanceProperties["IdentifyingNumber"].Value, CultureInfo.InvariantCulture), Name = Convert.ToString(computerDetails.CimInstanceProperties["Name"].Value, CultureInfo.InvariantCulture), Manufacturer = Convert.ToString(computerDetails.CimInstanceProperties["Manufacturer"].Value, CultureInfo.InvariantCulture), Model = String.Join(" ", computerDetails.CimInstanceProperties["Manufacturer"].Value, computerDetails.CimInstanceProperties["Model"].Value), ModelNumber = Convert.ToString(computerDetails.CimInstanceProperties["Model"].Value, CultureInfo.InvariantCulture), Category = pcSystemTypeExMap[Convert.ToInt32(computerDetails.CimInstanceProperties["PCSystemTypeEx"].Value, CultureInfo.InvariantCulture)] }); }
internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { string localhostComputerName; DebugHelper.WriteLogEx(); IEnumerable <string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } CimSessionProxy cimSessionProxyTestConnection = new CimSessionProxyTestConnection(computerName, sessionOptions); if (computerName == ConstValue.NullComputerName) { localhostComputerName = ConstValue.LocalhostComputerName; } else { localhostComputerName = computerName; } string str = localhostComputerName; CimSessionWrapper cimSessionWrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, str, cimSessionProxyTestConnection.CimSession, cimSessionProxyTestConnection.Protocol); CimNewSession.CimTestCimSessionContext cimTestCimSessionContext = new CimNewSession.CimTestCimSessionContext(cimSessionProxyTestConnection, cimSessionWrapper); cimSessionProxyTestConnection.ContextObject = cimTestCimSessionContext; SwitchParameter skipTestConnection = cmdlet.SkipTestConnection; if (!skipTestConnection.IsPresent) { this.cimTestSession.TestCimSession(computerName, cimSessionProxyTestConnection); } else { this.AddSessionToCache(cimSessionProxyTestConnection.CimSession, cimTestCimSessionContext, new CmdletOperationBase(cmdlet)); } } }
/// <summary> /// Create an instance of the CIM activity implementation class /// </summary> /// <param name="activityImplementationContext"></param> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="sessionOption"></param> /// <param name="session"></param> /// <param name="cimSessionOptions"></param> /// <param name="moduleDefinition"></param> /// <param name="resourceUri"></param> public CimActivityImplementationContext( ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism?authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri) { if (activityImplementationContext == null) { throw new ArgumentNullException("activityImplementationContext"); } this.PowerShellInstance = activityImplementationContext.PowerShellInstance; ResourceUri = resourceUri; ComputerName = computerName; PSCredential = credential; PSCertificateThumbprint = certificateThumbprint; PSAuthentication = authenticationMechanism; PSUseSsl = useSsl; PSPort = port; PSSessionOption = sessionOption; Session = session; SessionOptions = cimSessionOptions; if (moduleDefinition != null) { // Creating a script block forces the string into the compiled script cache so we // don't need to reparse it at execution time. Locking the static _moduleDefinition is not // required since the operation is idempotent. _moduleScriptBlock = ScriptBlock.Create(moduleDefinition); _moduleDefinition = moduleDefinition; } }
private void KickOffCimAsync(Computer computer, Credential credential, string commandline, CimSessionOptions options) { var optionsBuilder = new DbContextOptionsBuilder <ACEWebServiceDbContext>(); optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=ACEWebService;Trusted_Connection=True;MultipleActiveResultSets=true"); using (ACEWebServiceDbContext context = new ACEWebServiceDbContext(optionsBuilder.Options)) { // Convert stored password to a secure string SecureString securePwd = new SecureString(); foreach (char c in _cryptoService.Decrypt(credential.Password)) { securePwd.AppendChar(c); } CimCredential cimCreds = null; if (credential.UserName.Contains('\\')) { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Kerberos, credential.UserName.Split('\\')[0], credential.UserName.Split('\\')[1], securePwd); } else { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Default, null, credential.UserName, securePwd); } // Create a CimSession with the remote system options.AddDestinationCredentials(cimCreds); CimSession session = CimSession.Create(computer.ComputerName, options); // Create a CimMethodParametersCollection to pass to method invocation CimMethodParametersCollection collection = new CimMethodParametersCollection(); collection.Add(CimMethodParameter.Create("CommandLine", commandline, CimFlags.None)); CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection); if (result.ReturnValue.ToString() == "0") { } else { } session.Dispose(); } }
/// <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 KickOffCim(Computer computer, Credential credential, string commandline, CimSessionOptions options) { // Convert stored password to a secure string SecureString securePwd = new SecureString(); foreach (char c in _cryptoService.Decrypt(credential.Password)) { Console.WriteLine("[char]: {0}", c); securePwd.AppendChar(c); } CimCredential cimCreds = null; if (credential.UserName.Contains('\\')) { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Kerberos, credential.UserName.Split('\\')[0], credential.UserName.Split('\\')[1], securePwd); } else { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Default, null, credential.UserName, securePwd); } // Create a CimSession with the remote system options.AddDestinationCredentials(cimCreds); CimSession session = CimSession.Create(computer.ComputerName, options); // Create a CimMethodParametersCollection to pass to method invocation CimMethodParametersCollection collection = new CimMethodParametersCollection { CimMethodParameter.Create("CommandLine", commandline, CimFlags.None) }; CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection); if (result.ReturnValue.ToString() == "0") { } else { } session.Dispose(); }
private static bool CompareSessionOptions(CimConnectionManager.SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { TimeSpan timeout = sessionEntry.SessionOptions.Timeout; if (timeout.Equals(options2.Timeout)) { if (string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) { if (sessionEntry.AuthenticationMechanism == authenticationMechanism) { if (WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) { if (sessionEntry.UseSsl == useSsl) { if (sessionEntry.Port == port) { if (!(pssessionOption == null ^ sessionEntry.PSSessionOption == null)) { if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType == pssessionOption.ProxyAccessType) { if (sessionEntry.PSSessionOption.ProxyAuthentication == pssessionOption.ProxyAuthentication) { if (WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) { if (sessionEntry.PSSessionOption.SkipCACheck == pssessionOption.SkipCACheck) { if (sessionEntry.PSSessionOption.SkipCNCheck == pssessionOption.SkipCNCheck) { if (sessionEntry.PSSessionOption.SkipRevocationCheck == pssessionOption.SkipRevocationCheck) { if (sessionEntry.PSSessionOption.NoEncryption == pssessionOption.NoEncryption) { if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } return(true); } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } }
internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { CimSession session; lock (this.SyncRoot) { if (this.availableSessions.ContainsKey(computerName)) { List <CimConnectionManager.SessionEntry> item = this.availableSessions[computerName]; if (item.Count > 0) { int num = 0; while (num < item.Count) { CimConnectionManager.SessionEntry sessionEntry = item[num]; if ((sessionEntry.SessionOptions != null || sessionOptions != null) && !CimConnectionManager.CompareSessionOptions(sessionEntry, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { num++; } else { sessionEntry.AddReference(); session = sessionEntry.Session; return(session); } } } } CimConnectionManager.SessionEntry sessionEntry1 = new CimConnectionManager.SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); sessionEntry1.IterationsRemaining = 6; sessionEntry1.AddReference(); if (!this.availableSessions.ContainsKey(computerName)) { this.availableSessions.Add(computerName, new List <CimConnectionManager.SessionEntry>()); } this.availableSessions[computerName].Add(sessionEntry1); session = sessionEntry1.Session; } return(session); }
public static void Main() { bool hasComputerNameChanged = true; CimSession cimSession = null; CimSessionOptions sessionOptions = null; string className = null; string computerName = @"."; //GetName("ComputerName"); if (String.IsNullOrEmpty(computerName)) { computerName = null; } string namespaceName = @"root\cimv2"; //GetName("Namespace"); CurrentOperation currentOperation = GetCurrentOption(true); while (true) { if (currentOperation == CurrentOperation.OperationQuit) { if (cimSession != null) { cimSession.Close(); cimSession = null; } return; } if (ClassNeeded(currentOperation)) { className = GetName("ClassName"); } try { // Create local CIM session if (hasComputerNameChanged) { if (cimSession != null) { cimSession.Close(); } sessionOptions = new DComSessionOptions(); sessionOptions.Timeout = new TimeSpan( 0, // Hours 2, // Minutes 0 // Seconds ); cimSession = CimSession.Create(computerName, sessionOptions); hasComputerNameChanged = false; } switch (currentOperation) { case CurrentOperation.EnumerateAsync: SampleCimOperation.EnumerateASync(cimSession, namespaceName, className); break; case CurrentOperation.EnumerateSync: SampleCimOperation.EnumerateSync(cimSession, namespaceName, className); break; case CurrentOperation.GetInstanceSync: SampleCimOperation.GetInstanceSync(cimSession, namespaceName, className); break; case CurrentOperation.GetInstanceAsync: SampleCimOperation.GetInstanceASync(cimSession, namespaceName, className); break; case CurrentOperation.CreateInstanceAsync: SampleCimOperation.CreateInstanceASync(cimSession, namespaceName, className); break; case CurrentOperation.CreateInstanceSync: SampleCimOperation.CreateInstanceSync(cimSession, namespaceName, className); break; case CurrentOperation.DeleteInstanceAsync: SampleCimOperation.DeleteInstanceASync(cimSession, namespaceName, className); break; case CurrentOperation.DeleteInstanceSync: SampleCimOperation.DeleteInstanceSync(cimSession, namespaceName, className); break; case CurrentOperation.ModifyInstanceAsync: SampleCimOperation.ModifyInstanceASync(cimSession, namespaceName, className); break; case CurrentOperation.ModifyInstanceSync: SampleCimOperation.ModifyInstanceSync(cimSession, namespaceName, className); break; case CurrentOperation.QueryInstanceAsync: SampleCimOperation.QueryInstanceASync(cimSession, namespaceName); break; case CurrentOperation.QueryInstanceSync: SampleCimOperation.QueryInstanceSync(cimSession, namespaceName); break; case CurrentOperation.QueryAssociationSync: SampleCimOperation.EnumerateAssociatedInstanceSync(cimSession, namespaceName, className); break; case CurrentOperation.QueryAssociationAsync: SampleCimOperation.EnumerateAssociatedInstanceASync(cimSession, namespaceName, className); break; case CurrentOperation.InvokeMethodSync: SampleCimOperation.InvokeMethodSync(cimSession, namespaceName, className); break; case CurrentOperation.InvokeMethodAsync: SampleCimOperation.InvokeMethodASync(cimSession, namespaceName, className); break; case CurrentOperation.SubscribeSync: SampleCimOperation.SubscribeSync(cimSession, namespaceName); break; case CurrentOperation.SubscribeAsync: SampleCimOperation.SubscribeASync(cimSession, namespaceName); break; case CurrentOperation.OperationComputerName: computerName = GetName("ComputerName"); if (String.IsNullOrEmpty(computerName)) { computerName = null; } hasComputerNameChanged = true; break; case CurrentOperation.OperationNamespaceName: namespaceName = GetName("Namespace"); break; default: break; } } catch (CimException ex) { Console.WriteLine(ex.Message); } currentOperation = GetCurrentOption(false); } }
public CimSessionProxyTestConnection(string computerName, CimSessionOptions sessionOptions) : base(computerName, sessionOptions) { }
public CimSessionProxyGetCimClass(string computerName, CimSessionOptions options) : base(computerName, options) { }
/// <summary> /// Get a CIM session for the target computer /// </summary> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="sessionOptions"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="pssessionOption"></param> /// <returns></returns> internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(computerName), "ComputerName is null in GetSession. GetSession should not be called in this case."); lock (SyncRoot) { SessionEntry newSessionEntry; if (availableSessions.ContainsKey(computerName)) { List <SessionEntry> sel = availableSessions[computerName]; if (sel.Count > 0) { for (int i = 0; i < sel.Count; i++) { SessionEntry se = sel[i]; // No session options specified or the object matches exactly... if ((se.SessionOptions == null && sessionOptions == null) || CompareSessionOptions(se, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { // Up the number of references to this session object... se.AddReference(); return(se.Session); } } } } // Allocate a new session entry for this computer newSessionEntry = new SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); newSessionEntry.IterationsRemaining = MaxIterations; newSessionEntry.AddReference(); if (!availableSessions.ContainsKey(computerName)) { availableSessions.Add(computerName, new List <SessionEntry>()); } availableSessions[computerName].Add(newSessionEntry); // Return the session object return(newSessionEntry.Session); } }
private static bool CompareSessionOptions(SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { if (!sessionEntry.SessionOptions.Timeout.Equals(options2.Timeout)) { return(false); } if (!string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) { return(false); } if (!string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) { return(false); } if (!string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) { return(false); } if (sessionEntry.AuthenticationMechanism != authenticationMechanism) { return(false); } if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) { return(false); } if (sessionEntry.UseSsl != useSsl) { return(false); } if (sessionEntry.Port != port) { return(false); } // check PSSessionOption if present if (pssessionOption == null ^ sessionEntry.PSSessionOption == null) { return(false); } if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType != pssessionOption.ProxyAccessType) { return(false); } if (sessionEntry.PSSessionOption.ProxyAuthentication != pssessionOption.ProxyAuthentication) { return(false); } if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) { return(false); } if (sessionEntry.PSSessionOption.SkipCACheck != pssessionOption.SkipCACheck) { return(false); } if (sessionEntry.PSSessionOption.SkipCNCheck != pssessionOption.SkipCNCheck) { return(false); } if (sessionEntry.PSSessionOption.SkipRevocationCheck != pssessionOption.SkipRevocationCheck) { return(false); } if (sessionEntry.PSSessionOption.NoEncryption != pssessionOption.NoEncryption) { return(false); } if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) { return(false); } } return(true); }
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; }