private RemoteRunspace CreateRunspaceWhenUriParameterSpecified() { RemoteRunspace runspace = null; try { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(this.ConnectionUri, this.ConfigurationName, this.Credential) { AuthenticationMechanism = this.Authentication }; base.UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = (bool) this.EnableNetworkAccess; runspace = this.CreateTemporaryRemoteRunspace(base.Host, connectionInfo); } catch (UriFormatException exception) { this.WriteErrorCreateRemoteRunspaceFailed(exception, this.ConnectionUri); } catch (InvalidOperationException exception2) { this.WriteErrorCreateRemoteRunspaceFailed(exception2, this.ConnectionUri); } catch (ArgumentException exception3) { this.WriteErrorCreateRemoteRunspaceFailed(exception3, this.ConnectionUri); } catch (PSRemotingTransportException exception4) { this.WriteErrorCreateRemoteRunspaceFailed(exception4, this.ConnectionUri); } catch (NotSupportedException exception5) { this.WriteErrorCreateRemoteRunspaceFailed(exception5, this.ConnectionUri); } return runspace; }
public WSManConnectionInfo ExchangeScriptInit() { try { var SHELL_URI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; // 邮件服务器地址赋值 //System.Uri serverUri = new Uri(String.Format("http://Xd-svr0185.xd-ad.com.cn/PowerShell", @"xd-ad\admin")); //System.Uri serverUri = new Uri(String.Format("http://exchangedag.xd-ad.com.cn/PowerShell", @"xd-ad\admin")); //var serverUri =new Uri(string.Format("http://" + _expath + "/PowerShell", @"" + _exadmin + "")); var serverUri = new Uri(string.Format("http://" + _exIp + "/PowerShell")); PSCredential creds; //在内存中加密字符串 var securePassword = new SecureString(); foreach (var c in _expwd) { securePassword.AppendChar(c); } //creds = new PSCredential(@"xd-ad\admin", securePassword); // 生成凭证(根据exchange的管理员用户名和密码) creds = new PSCredential(@"" + _exadmin + "", securePassword); // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据 WSManConnectionInfo connectionInfo = new WSManConnectionInfo(serverUri, SHELL_URI, creds); return(connectionInfo); } catch (Exception) { return(null); } #endregion }
public void Connect(PSCredential credentials, CultureInfo sessionUiCulture) { this.CheckDisposed(); try { Dns.GetHostEntry(this.targetServer); } catch (SocketException ex) { throw new CouldNotResolveServerException(this.targetServer, ex, ex); } Uri uri = null; string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; switch (this.connectionType) { case PowershellConnectionType.WSMan: uri = new Uri(string.Format("{0}{1}/wsman", this.useSSL ? "https://" : "http://", this.targetServer)); shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; break; case PowershellConnectionType.OnPrem: this.useSSL = false; uri = new Uri(string.Format("{0}{1}/powershell?serializationLevel=Full", this.useSSL ? "https://" : "http://", this.targetServer)); break; case PowershellConnectionType.Tenant: { string uriString = string.Format("{0}{1}/powershell-liveid?serializationLevel=Full", this.useSSL ? "https://" : "http://", this.targetServer); uri = new Uri(uriString); break; } } WSManConnectionInfo wsmanConnectionInfo = new WSManConnectionInfo(uri, shellUri, credentials); if (this.connectionType == PowershellConnectionType.Tenant) { wsmanConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; } else if (this.connectionType == PowershellConnectionType.OnPrem) { wsmanConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos; } PowershellHostUI hostUI = new PowershellHostUI(); RemotePowershellHost host = new RemotePowershellHost(hostUI); wsmanConnectionInfo.Culture = sessionUiCulture; wsmanConnectionInfo.MaximumConnectionRedirectionCount = 5; this.runspace = RunspaceFactory.CreateRunspace(host, wsmanConnectionInfo); this.logger.LogInformation(HybridStrings.HybridInfoOpeningRunspace(uri.ToString())); try { this.runspace.Open(); } catch (PSRemotingTransportException ex2) { throw new CouldNotOpenRunspaceException(ex2, ex2); } this.openedRunspace = true; }
public static WSManConnectionInfo ExchangeScriptInit() { var _exIp = "win-2ickeabl4tr.test.com"; //var _exIp = "Localhost"; var _exadmin = "*****@*****.**"; var _expwd = "P@ssw0rd"; try { var SHELL_URI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";; // 邮件服务器地址赋值 //System.Uri serverUri = new Uri(String.Format("http://Xd-svr0185.xd-ad.com.cn/PowerShell";, @"xd-ad\admin")); //System.Uri serverUri = new Uri(String.Format("http://exchangedag.xd-ad.com.cn/PowerShell";, @"xd-ad\admin")); //var serverUri =new Uri(string.Format("http://"; + _expath + "/PowerShell", @"" + _exadmin + "")); var serverUri = new Uri(string.Format("http://"; +_exIp + "/PowerShell")); PSCredential creds; //在内存中加密字符串 var securePassword = new SecureString(); foreach (var c in _expwd) { securePassword.AppendChar(c); } //creds = new PSCredential(@"xd-ad\admin", securePassword); // 生成凭证(根据exchange的管理员用户名和密码) creds = new PSCredential(@"" + _exadmin + "", securePassword); // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据 WSManConnectionInfo connectionInfo = new WSManConnectionInfo(serverUri, SHELL_URI, creds); connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos; return(connectionInfo); } catch (Exception) { return(null); } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { try { if (isConnected) { disconnect(); } } catch { } connectionInfo = null; Username = null; Password = null; Hostname = null; if (Client != null) { Client.Dispose(); } if (remoteRunspace != null) { remoteRunspace.Dispose(); } }
public IEnumerable <dynamic> Execute(ServerConfig server, string commandOrScript, Action <PowerShellModulesToLoad> modulesToLoad = null, IEnumerable <CommandParameter> parameters = null, bool logOutput = true) { var folders = new RemoteScriptFolders(server); var modules = new PowerShellModulesToLoad(); if (modulesToLoad != null) { modulesToLoad(modules); } var remoteCredential = new PSCredential(server.DeploymentUser.UserName, GetPasswordAsSecString(server.DeploymentUser.Password)); var connectionInfo = new WSManConnectionInfo(server.PowerShell.SSL, server.Name, ResolvePort(server), "/wsman", SHELL_URI, remoteCredential); if (UseCredSSP) { using (new CredSSPHandler(connectionInfo, server)) { return(ExecuteCommand(commandOrScript, connectionInfo, modules, folders, parameters, logOutput)); } } return(ExecuteCommand(commandOrScript, connectionInfo, modules, folders, parameters, logOutput)); }
public async Task<bool> InvokeAsync(WSManConnectionInfo ws) { try { using (var runspace = RunspaceFactory.CreateRunspace(ws)) using (var powershell = PowerShell.Create()) { runspace.Open(); powershell.Runspace = runspace; powershell.AddCommand(Command); // [dvalles] 20220601: Change .AddScript -> .AddCommand (AddScript is obsolete) Results = await Task.Factory.FromAsync(powershell.BeginInvoke(), pResult => powershell.EndInvoke(pResult)); if (powershell.HadErrors) { throw powershell.Streams.Error[0].Exception; } return true; } } catch (Exception ex) { //return false; throw ex; } }
internal static bool CompareConnectionUri(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { if (string.Compare(connectionInfo2.Scheme, connectionInfo1.Scheme, StringComparison.OrdinalIgnoreCase) == 0) { if (string.Compare(connectionInfo2.ComputerName, connectionInfo1.ComputerName, StringComparison.OrdinalIgnoreCase) == 0) { if (string.Compare(connectionInfo2.AppName, connectionInfo1.AppName, StringComparison.OrdinalIgnoreCase) == 0) { if (connectionInfo2.Port == connectionInfo1.Port) { return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } }
/// <summary> /// Creates a new class and stores the passed values containing connection information /// </summary> /// <param name="uri">The URI to the Exchange powershell virtual directory</param> /// <param name="username">DOMAIN\Username to authenticate with</param> /// <param name="password">Password for the domain user</param> /// <param name="isKerberos">True if using kerberos authentication, False if using basic authentication</param> /// <param name="domainController">The domain controller to communicate with</param> public ExchPowershell() { try { // Retrieve the settings from the database SchedulerRetrieve.GetSettings(); // Set our domain controller to communicate with this.domainController = Config.PrimaryDC; // Get the type of Exchange connection bool isKerberos = false; if (Config.ExchangeConnectionType == Enumerations.ConnectionType.Kerberos) isKerberos = true; // Create our connection this.wsConn = GetConnection(Config.ExchangeURI, Config.Username, Config.Password, isKerberos); // Create our runspace runspace = RunspaceFactory.CreateRunspace(wsConn); // Open our connection runspace.Open(); } catch (Exception ex) { // ERROR logger.Fatal("Unable to establish connection to Exchange.", ex); } }
// Отключение ActiveSync и WebApp у пользователя private void DisableActiveSyncWebAppPS(string userLogin, string mailServerAdr, string login, SecureString password, ref string errorMsg) { PSCredential credential = new PSCredential(login, password); WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(mailServerAdr)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos; Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo); PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("Set-CASMailbox"); command.AddParameter("Identity", userLogin); command.AddParameter("ActiveSyncEnabled", false); command.AddParameter("OWAEnabled", false); powershell.Commands = command; try { runspace.Open(); powershell.Runspace = runspace; powershell.Invoke(); } catch (Exception ex) { errorMsg = ex.Message; } finally { runspace.Dispose(); runspace = null; powershell.Dispose(); powershell = null; } }
public CredSSPHandler(WSManConnectionInfo connectionInfo, ServerConfig server) { _server = server; connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Credssp; EnableCredSSP(); }
private static object GetSessionOptions(WSManConnectionInfo wsmanConnectionInfo) { Collection <PSObject> collection; using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("New-WSManSessionOption"); if (wsmanConnectionInfo.ProxyAccessType != ProxyAccessType.None) { shell.AddParameter("ProxyAccessType", "Proxy" + wsmanConnectionInfo.ProxyAccessType.ToString()); shell.AddParameter("ProxyAuthentication", wsmanConnectionInfo.ProxyAuthentication.ToString()); if (wsmanConnectionInfo.ProxyCredential != null) { shell.AddParameter("ProxyCredential", wsmanConnectionInfo.ProxyCredential); } } if (wsmanConnectionInfo.IncludePortInSPN) { shell.AddParameter("SPNPort", wsmanConnectionInfo.Port); } shell.AddParameter("SkipCACheck", wsmanConnectionInfo.SkipCACheck); shell.AddParameter("SkipCNCheck", wsmanConnectionInfo.SkipCNCheck); shell.AddParameter("SkipRevocationCheck", wsmanConnectionInfo.SkipRevocationCheck); shell.AddParameter("OperationTimeout", wsmanConnectionInfo.OperationTimeout); shell.AddParameter("NoEncryption", wsmanConnectionInfo.NoEncryption); shell.AddParameter("UseUTF16", wsmanConnectionInfo.UseUTF16); collection = shell.Invoke(); } return(collection[0].BaseObject); }
public bool Execute() { var connectionInfo = new WSManConnectionInfo {ComputerName = ComputerName}; using (var runspace = RunspaceFactory.CreateRunspace(connectionInfo)) { try { runspace.Open(); } catch (System.Management.Automation.Remoting.PSRemotingTransportException ex) { MessageBox.Show("Could not connect. Please try run editor as administrator: \n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } using (var ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript("'aaa'"); var results = ps.Invoke(); Result = string.Join("\n", results); } return true; } }
internal static bool CompareConnectionUri(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { if (string.Compare(connectionInfo2.Scheme, connectionInfo1.Scheme, StringComparison.OrdinalIgnoreCase) == 0) { if (string.Compare(connectionInfo2.ComputerName, connectionInfo1.ComputerName, StringComparison.OrdinalIgnoreCase) == 0) { if (string.Compare(connectionInfo2.AppName, connectionInfo1.AppName, StringComparison.OrdinalIgnoreCase) == 0) { if (connectionInfo2.Port == connectionInfo1.Port) { return(true); } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } }
internal static bool CompareProxySettings(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { if (connectionInfo1.ProxyAccessType == connectionInfo2.ProxyAccessType) { if (connectionInfo1.ProxyAccessType != ProxyAccessType.None) { if (connectionInfo1.ProxyAuthentication == connectionInfo2.ProxyAuthentication) { if (WorkflowUtils.CompareCredential(connectionInfo1.ProxyCredential, connectionInfo2.ProxyCredential)) { return(true); } else { return(false); } } else { return(false); } } else { return(true); } } else { return(false); } }
internal static Collection<PSObject> GetRemotePools(WSManConnectionInfo wsmanConnectionInfo) { using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("Get-WSManInstance"); shell.AddParameter("ResourceURI", "Shell"); shell.AddParameter("Enumerate", true); shell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName); shell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism)); if (wsmanConnectionInfo.Credential != null) { shell.AddParameter("Credential", wsmanConnectionInfo.Credential); } if (wsmanConnectionInfo.CertificateThumbprint != null) { shell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } if (wsmanConnectionInfo.PortSetting != -1) { shell.AddParameter("Port", wsmanConnectionInfo.Port); } if (CheckForSSL(wsmanConnectionInfo)) { shell.AddParameter("UseSSL", true); } if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName)) { string str = wsmanConnectionInfo.AppName.TrimStart(new char[] { '/' }); shell.AddParameter("ApplicationName", str); } shell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo)); return shell.Invoke(); } }
public RemotePowerShell(string remoteHostUri, string username, string password, bool useWSMan = true) { RemoteHostUri = remoteHostUri; Credential = new PSCredential(username, (new NetworkCredential(username, password).SecurePassword)); if (useWSMan) { AddTrustedHost(RemoteHostUri); AllowUnencrypted(); Uri remoteComputerUri = new Uri(string.Format("http://{0}:5985/wsman", remoteHostUri)); WSManConnectionInfo connection = new WSManConnectionInfo(remoteComputerUri, "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", Credential); connection.AuthenticationMechanism = AuthenticationMechanism.Basic; connection.NoEncryption = true; connection.SkipCACheck = true; connection.SkipCNCheck = true; connection.SkipRevocationCheck = true; //string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; //WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, RemoteHostUri, 5985, "/wsman", shellUri, Credential); Runspace = RunspaceFactory.CreateRunspace(connection); Runspace.Open(); Session = PS.Create(); Session.Runspace = Runspace; } }
void OpenRemoteSession() { UI.ConnectionDialog dialog = new UI.ConnectionDialog("New remote interactive"); if (!dialog.Show()) { return; } string computerName = (dialog.ComputerName.Length == 0 || dialog.ComputerName == ".") ? "localhost" : dialog.ComputerName; PSCredential credential = null; if (dialog.UserName.Length > 0) { credential = NativeMethods.PromptForCredential(null, null, dialog.UserName, string.Empty, PSCredentialTypes.Generic | PSCredentialTypes.Domain, PSCredentialUIOptions.Default); if (credential == null) { return; } } WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, computerName, 0, null, null, credential); EnsureHost(); Runspace = RunspaceFactory.CreateRunspace(FarHost, connectionInfo); RunspaceOpen(); Editor.Title = "PS " + computerName + " session " + Path.GetFileName(Editor.FileName); InvokeProfile("Profile-Remote.ps1", true); }
private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified() { RemoteRunspace runspace = null; string computerName = base.ResolveComputerName(this.computerName); try { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(this.UseSSL.IsPresent, computerName, this.Port, this.ApplicationName, this.ConfigurationName, this.Credential) { AuthenticationMechanism = this.Authentication }; base.UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = (bool)this.EnableNetworkAccess; runspace = this.CreateTemporaryRemoteRunspace(base.Host, connectionInfo); } catch (InvalidOperationException exception) { this.WriteErrorCreateRemoteRunspaceFailed(exception, computerName); } catch (ArgumentException exception2) { this.WriteErrorCreateRemoteRunspaceFailed(exception2, computerName); } catch (PSRemotingTransportException exception3) { this.WriteErrorCreateRemoteRunspaceFailed(exception3, computerName); } return(runspace); }
public static void WinRMCodeExecutionNET(Computer computer, PlaybookTask playbook_task, Logger logger) { string target = ""; if (!computer.Fqdn.Equals("")) { target = computer.Fqdn; } else if (!computer.ComputerName.Equals("")) { target = computer.ComputerName; } else { target = computer.IPv4; } try { var connectTo = new Uri(String.Format("http://{0}:5985/wsman", target)); logger.TimestampInfo(String.Format("Connecting to http://{0}:5985/wsman", target)); var connection = new WSManConnectionInfo(connectTo); var runspace = RunspaceFactory.CreateRunspace(connection); runspace.Open(); using (var powershell = PowerShell.Create()) { powershell.Runspace = runspace; powershell.AddScript(playbook_task.command); var results = powershell.Invoke(); runspace.Close(); logger.TimestampInfo(String.Format("Successfully executed {0} using WinRM on {1}", playbook_task.command, computer.ComputerName)); /* * Console.WriteLine("Return command "); * foreach (var obj in results.Where(o => o != null)) * { * Console.WriteLine("\t" + obj); * } */ } } catch (Exception ex) { if (ex.Message.Contains("Access is denied")) { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. (Access Denied)", computer.Fqdn)); throw new Exception(); } else if (ex.GetType().ToString().Contains("PSRemotingTransportException")) { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. (Connection Issues)", computer.Fqdn)); throw new Exception(); } else { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. {1}", computer.Fqdn, ex.GetType())); throw new Exception(); } } }
/// <inheritdoc /> protected CassiaCmdlet() { _remoteRunspace = new Lazy <Runspace>(() => { var wsmanConnectionInfo = new WSManConnectionInfo { ComputerName = ComputerName, Credential = Credential }; wsmanConnectionInfo.SetSessionOptions(new PSSessionOption() { IncludePortInSPN = true }); var remoteRunspace = RunspaceFactory.CreateRunspace(wsmanConnectionInfo); remoteRunspace.Open(); return(remoteRunspace); }); var scriptRoot = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new InvalidOperationException("Failed to get assembly directory"); var cassiaAssemblyPath = Path.Combine(scriptRoot, "Lib", "Cassia.dll"); CassiaAssemblyBase64 = Convert.ToBase64String(File.ReadAllBytes(cassiaAssemblyPath)); var scriptPath = Path.Combine(scriptRoot, "Scripts", "CassiaCmdlet.ps1"); CassiaAssemblyImportScript = File.ReadAllText(scriptPath); }
public void Open(string username, string livePass, ref Runspace remoteRunspace) { try { string uri = "https://outlook.office365.com/powershell-liveid/"; string schema = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; SecureString password = new SecureString(); foreach (char c in livePass.ToCharArray()) { password.AppendChar(c); } PSCredential psc = new PSCredential(username, password); WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc); rri.AuthenticationMechanism = AuthenticationMechanism.Basic; remoteRunspace = RunspaceFactory.CreateRunspace(rri); remoteRunspace.Open(); } catch (Exception e) { remoteRunspace.Close(); remoteRunspace.Dispose(); throw e; } }
/// <summary> /// Creates a new instance of ClientRemoteSessionImpl /// </summary> /// <param name="rsPool"> /// The RunspacePool object this session should map to. /// </param> /// <param name="uriRedirectionHandler"> /// </param> internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler) { Dbg.Assert(rsPool != null, "RunspacePool cannot be null"); base.RemoteRunspacePoolInternal = rsPool; Context.RemoteAddress = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(rsPool.ConnectionInfo, "ConnectionUri", null); _cryptoHelper = new PSRemotingCryptoHelperClient(); _cryptoHelper.Session = this; Context.ClientCapability = RemoteSessionCapability.CreateClientCapability(); Context.UserCredential = rsPool.ConnectionInfo.Credential; // shellName validation is not performed on the client side. // This is recommended by the WinRS team: for the reason that the rules may change in the future. Context.ShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(rsPool.ConnectionInfo, "ShellUri", string.Empty); MySelf = RemotingDestination.Client; //Create session data structure handler for this session SessionDataStructureHandler = new ClientRemoteSessionDSHandlerImpl(this, _cryptoHelper, rsPool.ConnectionInfo, uriRedirectionHandler); BaseSessionDataStructureHandler = SessionDataStructureHandler; _waitHandleForConfigurationReceived = new ManualResetEvent(false); //Register handlers for various ClientSessiondata structure handler events SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived; SessionDataStructureHandler.ConnectionStateChanged += HandleConnectionStateChanged; SessionDataStructureHandler.EncryptedSessionKeyReceived += new EventHandler <RemoteDataEventArgs <string> >(HandleEncryptedSessionKeyReceived); SessionDataStructureHandler.PublicKeyRequestReceived += new EventHandler <RemoteDataEventArgs <string> >(HandlePublicKeyRequestReceived); }
public void CreateRemoteSession(string User, string Pass, string Host) { SecureString ssLoginPassword = new SecureString(); foreach (char x in Pass) { ssLoginPassword.AppendChar(x); } PSCredential remoteMachineCredentials = new PSCredential(User, ssLoginPassword); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://" + Host + ":5985/wsman"), this.ShellURI, remoteMachineCredentials); connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Negotiate; Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); runspace.Open(); ps.Runspace = runspace; /* string Command = "$username = \"" + User + "\";"; * Command += "$password = \"" + Pass + "\";"; * Command += "$secpass = New-Object -TypeName System.Security.SecureString;"; * Command += "$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)};"; * Command += "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secpass;"; * Command += "$rsess = New-PSSession -ComputerName " + Host + " -Credential $cred"; * Command += "Enter-PSSession $rsess"; * this.Execute(Command);*/ }
public Runspace GetRunSpace() { this.connectionInfo = new WSManConnectionInfo(new Uri(liveIdconnectionUri), URL, PSCredential.Empty); this.connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default; return(RunspaceFactory.CreateRunspace(connectionInfo)); }
private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectionInfo connectionInfo) { int num; string name = PSSession.GenerateRunspaceName(out num); RemoteRunspace runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, host, this.SessionOption.ApplicationArguments, name, num); runspace.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported); this.stream = new ObjectStream(); try { runspace.Open(); runspace.ShouldCloseOnPop = true; } finally { runspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported); this.stream.ObjectWriter.Close(); if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) { runspace.Dispose(); runspace = null; } } return(runspace); }
public ICustomActivityResult Execute() { string command = "Get-MailboxPermission"; DataTable dt = new DataTable("resultSet"); string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; System.Uri serverUri = new Uri(String.Format("HTTPS://{0}/powershell?serializationLevel=Full", HostName)); System.Security.SecureString securePassword = new System.Security.SecureString(); foreach (char c in Password.ToCharArray()) { securePassword.AppendChar(c); } PSCredential creds = new PSCredential(UserName, securePassword); RunspaceConfiguration rc = RunspaceConfiguration.Create(); WSManConnectionInfo wsManInfo = new WSManConnectionInfo(serverUri, shellUri, creds); wsManInfo.SkipCNCheck = true; wsManInfo.SkipCACheck = true; using (var runspace = RunspaceFactory.CreateRunspace(wsManInfo)) { runspace.Open(); using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = runspace; powershell.AddCommand(command); powershell.Commands.AddParameter("Identity", UserLogonName); powershell.Commands.AddParameter("ErrorAction", "stop"); Collection <PSObject> results = powershell.Invoke(); bool isFirstEntry = true; foreach (PSObject obj in results) { DataRow dr = dt.NewRow(); foreach (PSPropertyInfo psInfo in obj.Properties) { string propertyName = psInfo.Name; if (isFirstEntry) { dt.Columns.Add(propertyName, typeof(String)); } if (psInfo.Value != null) { dr[propertyName] = psInfo.Value; } } isFirstEntry = false; dt.Rows.Add(dr); } } } return(this.GenerateActivityResult(dt)); }
public ActionResult About() { ViewBag.Message = ""; WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ComputerName = ""; Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript("Get-Process"); var results = ps.Invoke(); // Do something with result ... foreach (var result in results) { ViewBag.Message += result.Members["Id"].Value + " "; ViewBag.Message += result.Members["ProcessName"].Value + " "; ViewBag.Message += result.Members["PrivateMemorySize64"].Value + "<br>"; } } runspace.Close(); return(View()); }
/// <summary> /// Create a configured remote runspace from provided name. /// </summary> /// <param name="configurationName"></param> /// <param name="host"></param> /// <returns></returns> internal static RemoteRunspace CreateConfiguredRunspace( string configurationName, PSHost host) { // Create a loop-back remote runspace with network access enabled, and // with the provided endpoint configurationname. TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); var connectInfo = new WSManConnectionInfo(); connectInfo.ShellUri = configurationName.Trim(); connectInfo.EnableNetworkAccess = true; RemoteRunspace remoteRunspace = null; try { remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectInfo, host, typeTable); remoteRunspace.Open(); } catch (Exception e) { throw new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.CannotCreateConfiguredRunspace, configurationName), e); } remoteRunspace.IsConfiguredLoopBack = true; return(remoteRunspace); }
/// <summary> /// CompareConnectionUri compares two connection URIs /// by doing a comparison of elements. /// </summary> /// <param name="connectionInfo1">Connection info 1</param> /// <param name="connectionInfo2">Connection info 2</param> /// <returns>True if they match else false.</returns> internal static bool CompareConnectionUri(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { Debug.Assert(connectionInfo1 != null && connectionInfo2 != null, "Connections should be != null"); Debug.Assert(!string.IsNullOrEmpty(connectionInfo1.Scheme) && !string.IsNullOrEmpty(connectionInfo1.ComputerName) && !string.IsNullOrEmpty(connectionInfo1.AppName), "Connection URI elements should be != null or empty"); Debug.Assert(!string.IsNullOrEmpty(connectionInfo2.Scheme) && !string.IsNullOrEmpty(connectionInfo2.ComputerName) && !string.IsNullOrEmpty(connectionInfo2.AppName), "Connection URI elements should be != null or empty"); if (String.Compare(connectionInfo2.Scheme, connectionInfo1.Scheme, StringComparison.OrdinalIgnoreCase) != 0) { return false; } if (String.Compare(connectionInfo2.ComputerName, connectionInfo1.ComputerName, StringComparison.OrdinalIgnoreCase) != 0) { return false; } if (String.Compare(connectionInfo2.AppName, connectionInfo1.AppName, StringComparison.OrdinalIgnoreCase) != 0) { return false; } if (connectionInfo2.Port != connectionInfo1.Port) { return false; } return true; } // CompareConnectionUri ...
/// <summary> /// CompareConnectionUri compares two connection URIs /// by doing a comparison of elements. /// </summary> /// <param name="connectionInfo1">Connection info 1</param> /// <param name="connectionInfo2">Connection info 2</param> /// <returns>True if they match else false.</returns> internal static bool CompareConnectionUri(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { Debug.Assert(connectionInfo1 != null && connectionInfo2 != null, "Connections should be != null"); Debug.Assert(!string.IsNullOrEmpty(connectionInfo1.Scheme) && !string.IsNullOrEmpty(connectionInfo1.ComputerName) && !string.IsNullOrEmpty(connectionInfo1.AppName), "Connection URI elements should be != null or empty"); Debug.Assert(!string.IsNullOrEmpty(connectionInfo2.Scheme) && !string.IsNullOrEmpty(connectionInfo2.ComputerName) && !string.IsNullOrEmpty(connectionInfo2.AppName), "Connection URI elements should be != null or empty"); if (String.Compare(connectionInfo2.Scheme, connectionInfo1.Scheme, StringComparison.OrdinalIgnoreCase) != 0) { return(false); } if (String.Compare(connectionInfo2.ComputerName, connectionInfo1.ComputerName, StringComparison.OrdinalIgnoreCase) != 0) { return(false); } if (String.Compare(connectionInfo2.AppName, connectionInfo1.AppName, StringComparison.OrdinalIgnoreCase) != 0) { return(false); } if (connectionInfo2.Port != connectionInfo1.Port) { return(false); } return(true); } // CompareConnectionUri ...
} // CompareCertificateThumbprint ... /// <summary> /// CompareProxySettings compares the proxy settings for two wsman connections /// by doing a comparison of elements. /// </summary> /// <param name="connectionInfo1">Connection info 1</param> /// <param name="connectionInfo2">Connection info 2</param> /// <returns>True if they match else false.</returns> internal static bool CompareProxySettings(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { Debug.Assert(connectionInfo1 != null && connectionInfo2 != null, "Connections should be != null"); if (connectionInfo1.ProxyAccessType != connectionInfo2.ProxyAccessType) { return(false); } if (connectionInfo1.ProxyAccessType == ProxyAccessType.None) { return(true); //stop here if no proxy access type } if (connectionInfo1.ProxyAuthentication != connectionInfo2.ProxyAuthentication) { return(false); } // check the proxy credentials password if (!WorkflowUtils.CompareCredential(connectionInfo1.ProxyCredential, connectionInfo2.ProxyCredential)) { return(false); } return(true); } // CompareProxySettings ...
internal static Collection <PSObject> GetRemotePools(WSManConnectionInfo wsmanConnectionInfo) { using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("Get-WSManInstance"); shell.AddParameter("ResourceURI", "Shell"); shell.AddParameter("Enumerate", true); shell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName); shell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism)); if (wsmanConnectionInfo.Credential != null) { shell.AddParameter("Credential", wsmanConnectionInfo.Credential); } if (wsmanConnectionInfo.CertificateThumbprint != null) { shell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } if (wsmanConnectionInfo.PortSetting != -1) { shell.AddParameter("Port", wsmanConnectionInfo.Port); } if (CheckForSSL(wsmanConnectionInfo)) { shell.AddParameter("UseSSL", true); } if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName)) { string str = wsmanConnectionInfo.AppName.TrimStart(new char[] { '/' }); shell.AddParameter("ApplicationName", str); } shell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo)); return(shell.Invoke()); } }
public bool Execute() { var connectionInfo = new WSManConnectionInfo { ComputerName = ComputerName }; using (var runspace = RunspaceFactory.CreateRunspace(connectionInfo)) { try { runspace.Open(); } catch (System.Management.Automation.Remoting.PSRemotingTransportException ex) { MessageBox.Show("Could not connect. Please try run editor as administrator: \n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } using (var ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript("'aaa'"); var results = ps.Invoke(); Result = string.Join("\n", results); } return(true); } }
internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, ClientRemoteSession.URIDirectionReported uriRedirectionHandler) { if (session == null) { throw PSTraceSource.NewArgumentNullException("session"); } this._session = session; this._stateMachine = new ClientRemoteSessionDSHandlerStateMachine(); this._stateMachine.StateChanged += new EventHandler <RemoteSessionStateEventArgs>(this.HandleStateChanged); this._connectionInfo = connectionInfo; this._cryptoHelper = cryptoHelper; if (this._connectionInfo is NewProcessConnectionInfo) { this._transportManager = new OutOfProcessClientSessionTransportManager(this._session.RemoteRunspacePoolInternal.InstanceId, (NewProcessConnectionInfo)this._connectionInfo, cryptoHelper); } else { this._transportManager = new WSManClientSessionTransportManager(this._session.RemoteRunspacePoolInternal.InstanceId, (WSManConnectionInfo)this._connectionInfo, cryptoHelper, this._session.RemoteRunspacePoolInternal.Name); } this._transportManager.DataReceived += new EventHandler <RemoteDataEventArgs>(this.DispatchInputQueueData); this._transportManager.WSManTransportErrorOccured += new EventHandler <TransportErrorOccuredEventArgs>(this.HandleTransportError); this._transportManager.CloseCompleted += new EventHandler <EventArgs>(this.HandleCloseComplete); this._transportManager.DisconnectCompleted += new EventHandler <EventArgs>(this.HandleDisconnectComplete); this._transportManager.ReconnectCompleted += new EventHandler <EventArgs>(this.HandleReconnectComplete); this._transportManager.RobustConnectionNotification += new EventHandler <ConnectionStatusEventArgs>(this.HandleRobustConnectionNotification); WSManConnectionInfo info = connectionInfo as WSManConnectionInfo; if (info != null) { this.uriRedirectionHandler = uriRedirectionHandler; this.maxUriRedirectionCount = info.MaximumConnectionRedirectionCount; } }
private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified() { RemoteRunspace runspace = null; string computerName = base.ResolveComputerName(this.computerName); try { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(this.UseSSL.IsPresent, computerName, this.Port, this.ApplicationName, this.ConfigurationName, this.Credential) { AuthenticationMechanism = this.Authentication }; base.UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = (bool) this.EnableNetworkAccess; runspace = this.CreateTemporaryRemoteRunspace(base.Host, connectionInfo); } catch (InvalidOperationException exception) { this.WriteErrorCreateRemoteRunspaceFailed(exception, computerName); } catch (ArgumentException exception2) { this.WriteErrorCreateRemoteRunspaceFailed(exception2, computerName); } catch (PSRemotingTransportException exception3) { this.WriteErrorCreateRemoteRunspaceFailed(exception3, computerName); } return runspace; }
/// <summary> /// Call windows powershell sdk to get mailbox usage details. /// </summary> /// <param name="credentials">PSCredential object</param> /// <param name="liveIDConnectionUri">Live ID connection uri</param> /// <param name="schemaUri">Schema uri</param> /// <returns>Returns string array with details of ProhibitSendQuota and TotalItemSize</returns> public string[] GetMailBoxSizeDetails(PSCredential credentials, string liveIDConnectionUri, string schemaUri) { Runspace runspace = null; string[] mailBoxDetail = new string[2]; try { // Create basic connection using PSCredential. WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(liveIDConnectionUri), schemaUri, credentials); connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; runspace = RunspaceFactory.CreateRunspace(connectionInfo); // Open runspace once user authorized. runspace.Open(); // Get ProhibitSendQuota value. Collection <PSObject> prohibitSendQuota = GetProhibitSendQuota(runspace); foreach (PSObject resultProhibitSendQuota in prohibitSendQuota) { foreach (PSPropertyInfo psInfo in resultProhibitSendQuota.Properties) { if (psInfo.Name == "ProhibitSendQuota") { mailBoxDetail[0] = psInfo.Value.ToString(); break; } } } // Get TotalItemSize value. Collection <PSObject> usedQuota = GetUsedQuota(runspace); foreach (PSObject resultUsedQuota in usedQuota) { foreach (PSPropertyInfo psInfoUsedQuota in resultUsedQuota.Properties) { if (psInfoUsedQuota.Name == "TotalItemSize") { mailBoxDetail[1] = psInfoUsedQuota.Value.ToString(); break; } } } return(mailBoxDetail); } catch (Exception) { throw; } finally { if (runspace != null) { runspace.Close(); } } }
public ExchPowershell() { string uri = string.Format("https://{0}/powershell", ServiceSettings.ExchangeServer); this._connection = GetConnection(uri, ServiceSettings.Username, ServiceSettings.Password, ServiceSettings.ExchangeConnection == "Kerberos" ? true : false); _runspace = RunspaceFactory.CreateRunspace(_connection); _runspace.Open(); _powershell = PowerShell.Create(); _powershell.Runspace = _runspace; }
internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, IntPtr wsManShellOperationHandle, ClientRemotePowerShell shell, bool noInput, WSManClientSessionTransportManager sessnTM) : base(shell, sessnTM.CryptoHelper, sessnTM) { this.wsManShellOperationHandle = wsManShellOperationHandle; base.ReceivedDataCollection.MaximumReceivedDataSize = connectionInfo.MaximumReceivedDataSizePerCommand; base.ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize; this.cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory(); this.onDataAvailableToSendCallback = new System.Management.Automation.Remoting.PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback); this._sessnTm = sessnTM; sessnTM.RobustConnectionsInitiated += new EventHandler<EventArgs>(this.HandleRobustConnectionsIntiated); sessnTM.RobustConnectionsCompleted += new EventHandler<EventArgs>(this.HandleRobusConnectionsCompleted); }
internal Collection<PSObject> InvokeCommand(PSCommand command, ExchContext context) { if (context == null) { throw new ArgumentNullException("Context", "Parametr not defined. [" + _log.Name + "]"); } PSCredential _credential = GetPSCredential(context); WSManConnectionInfo _connection = new WSManConnectionInfo( new Uri(context.Uri), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", _credential); _connection.AuthenticationMechanism = AuthenticationMechanism.Kerberos; _connection.MaximumConnectionRedirectionCount = 3; _connection.SkipCACheck = true; _connection.SkipCNCheck = true; using (Runspace _runspace = RunspaceFactory.CreateRunspace(_connection)) { _runspace.Open(); //_runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Continue"); using (PowerShell _powershell = PowerShell.Create()) { _powershell.Commands = command; try { //RunspaceInvoke _invoker = new RunspaceInvoke(_runspace); //Collection<PSObject> _commandResults = _invoker.Invoke(command.ToString()); _powershell.Runspace = _runspace; Collection<PSObject> _commandResults = _powershell.Invoke(); CheckErrors(_powershell.Streams.Error); return _commandResults; //foreach (PSObject _result in _commandResults) //{ // Console.WriteLine(_result.ToString()); //} } catch (Exception ex) { throw new Exception(ex.Message + ". [" + _log.Name + "]"); } } } }
internal WSManClientSessionTransportManager(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper, string sessionName) : base(runspacePoolInstanceId, cryptoHelper) { this.startMode = WSManTransportManagerUtils.tmStartModes.None; base.CryptoHelper = cryptoHelper; base.dataToBeSent.Fragmentor = base.Fragmentor; this.sessionName = sessionName; base.ReceivedDataCollection.MaximumReceivedDataSize = null; base.ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize; this.onDataAvailableToSendCallback = new System.Management.Automation.Remoting.PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback); this.Initialize(connectionInfo.ConnectionUri, connectionInfo); }
public IEnumerable<dynamic> ExecuteLocal(ServerConfig localServer, string commandOrScript, Action<PowerShellModulesToLoad> modulesToLoad = null, IEnumerable<CommandParameter> parameters = null, bool logOutput = true) { var connectionInfo = new WSManConnectionInfo(); var modules = new PowerShellModulesToLoad(); if (modulesToLoad != null) { modulesToLoad(modules); } var folders = new RemoteScriptFolders(localServer); return ExecuteCommand(commandOrScript, connectionInfo, modules, folders, parameters, logOutput); }
internal void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) { connectionInfo.SetSessionOptions(this.SessionOption); if (!base.ParameterSetName.Equals("Uri", StringComparison.OrdinalIgnoreCase)) { connectionInfo.MaximumConnectionRedirectionCount = 0; } if (!this.allowRedirection) { connectionInfo.MaximumConnectionRedirectionCount = 0; } }
private Collection<WSManConnectionInfo> GetConnectionObjects() { Collection<WSManConnectionInfo> collection = new Collection<WSManConnectionInfo>(); if ((base.ParameterSetName == "ComputerName") || (base.ParameterSetName == "ComputerInstanceId")) { string str = this.UseSSL.IsPresent ? "https" : "http"; foreach (string str2 in this.ComputerName) { WSManConnectionInfo connectionInfo = new WSManConnectionInfo { Scheme = str, ComputerName = base.ResolveComputerName(str2), AppName = this.ApplicationName, ShellUri = this.ConfigurationName, Port = this.Port }; if (this.CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = this.CertificateThumbprint; } else { connectionInfo.Credential = this.Credential; } connectionInfo.AuthenticationMechanism = this.Authentication; this.UpdateConnectionInfo(connectionInfo); collection.Add(connectionInfo); } return collection; } if ((base.ParameterSetName == "ConnectionUri") || (base.ParameterSetName == "ConnectionUriInstanceId")) { foreach (Uri uri in this.ConnectionUri) { WSManConnectionInfo info2 = new WSManConnectionInfo { ConnectionUri = uri, ShellUri = this.ConfigurationName }; if (this.CertificateThumbprint != null) { info2.CertificateThumbprint = this.CertificateThumbprint; } else { info2.Credential = this.Credential; } info2.AuthenticationMechanism = this.Authentication; this.UpdateConnectionInfo(info2); collection.Add(info2); } } return collection; }
public static WSManConnectionInfo CreateConnectionInfo(Computer computer, int idleTimeout = 60000, int operationTimeout = 1000, int connectionTimeout = 1000) { var wSManConnectionInfo = new WSManConnectionInfo( false, computer.Name, 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", PowerShellSupport.PsCredential) { AuthenticationMechanism = AuthenticationMechanism.Default }; wSManConnectionInfo.IdleTimeout = idleTimeout; wSManConnectionInfo.OperationTimeout = operationTimeout; wSManConnectionInfo.OpenTimeout = connectionTimeout; return wSManConnectionInfo; }
public static void openRunspace(string uri, string schema, string username, string livePass, ref Runspace remoteRunspace) { System.Security.SecureString password = new System.Security.SecureString(); foreach (char c in livePass.ToCharArray()) { password.AppendChar(c); } PSCredential psc = new PSCredential(username, password); WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc); rri.AuthenticationMechanism = AuthenticationMechanism.Kerberos; rri.ProxyAuthentication = AuthenticationMechanism.Negotiate; remoteRunspace = RunspaceFactory.CreateRunspace(rri); remoteRunspace.Open(); }
/// <summary> /// Start new object /// </summary> /// <param name="uri">Uri to Exchange server powershell directory</param> /// <param name="username">Username to connect</param> /// <param name="password">Password to connect</param> /// <param name="kerberos">True to use Kerberos authentication, false to use Basic authentication</param> /// <param name="domainController">Domain controller to communicate with</param> public ExchCmds(string uri, string username, string password, bool kerberos, string domainController) { // DEBUG // this.logger.Debug(string.Format("Opened Exchange powershell class with {0}, {1}, {2}, {3}, {4}", uri, username, password, kerberos.ToString(), domainController)); this.wsConn = GetConnection(uri, username, password, kerberos); this.domainController = domainController; // Create our runspace runspace = RunspaceFactory.CreateRunspace(wsConn); runspace.ThreadOptions = PSThreadOptions.Default; // Open the connection runspace.Open(); }
private Runspace CreateRunspace() { if (_powerShellConfiguration.IsRemote) { var connectionInfo = new WSManConnectionInfo { ComputerName = _powerShellConfiguration.RemoteMachineName, AuthenticationMechanism = AuthenticationMechanism.Negotiate, }; return RunspaceFactory.CreateRunspace(connectionInfo); } return RunspaceFactory.CreateRunspace(); }
public void Conectar() { var securePassword = new SecureString(); foreach (var letra in Password.ToCharArray()) securePassword.AppendChar(letra); var credenciales = new PSCredential(Username, securePassword); var rri = new WSManConnectionInfo(false, Servidor, Puerto, "/wsman", Namespace, credenciales); //rri.AuthenticationMechanism = AuthenticationMechanism.Kerberos; //rri.ProxyAuthentication = AuthenticationMechanism.Negotiate; _runspace = RunspaceFactory.CreateRunspace(rri); _runspace.Open(); }
private List<RemoteRunspace> CreateRunspacesWhenComputerNameParameterSpecified() { string[] strArray; List<RemoteRunspace> list = new List<RemoteRunspace>(); base.ResolveComputerNames(this.ComputerName, out strArray); base.ValidateComputerName(strArray); for (int i = 0; i < strArray.Length; i++) { try { int num2; WSManConnectionInfo connectionInfo = null; connectionInfo = new WSManConnectionInfo(); string str = this.UseSSL.IsPresent ? "https" : "http"; connectionInfo.ComputerName = strArray[i]; connectionInfo.Port = this.Port; connectionInfo.AppName = this.ApplicationName; connectionInfo.ShellUri = this.ConfigurationName; connectionInfo.Scheme = str; if (this.CertificateThumbprint != null) { connectionInfo.CertificateThumbprint = this.CertificateThumbprint; } else { connectionInfo.Credential = this.Credential; } connectionInfo.AuthenticationMechanism = this.Authentication; base.UpdateConnectionInfo(connectionInfo); connectionInfo.EnableNetworkAccess = (bool) this.EnableNetworkAccess; string runspaceName = this.GetRunspaceName(i, out num2); RemoteRunspace item = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, base.Host, this.SessionOption.ApplicationArguments, runspaceName, num2); list.Add(item); } catch (UriFormatException exception) { PipelineWriter objectWriter = this.stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(exception, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, strArray[i]); Action<Cmdlet> action = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; objectWriter.Write(action); } } return list; }
internal IEnumerable<dynamic> ExecuteCommand(string commandOrScript, WSManConnectionInfo connectionInfo, PowerShellModulesToLoad modules, RemoteScriptFolders folders, IEnumerable<CommandParameter> parameters = null, bool logOutput = true) { var host = new ConDepPSHost(); using (var runspace = RunspaceFactory.CreateRunspace(host, connectionInfo)) { runspace.Open(); var ps = PowerShell.Create(); ps.Runspace = runspace; using (var pipeline = ps.Runspace.CreatePipeline("set-executionpolicy remotesigned -force; $VerbosePreference = 'continue'; $DebugPreference = 'continue'")) { ConfigureConDepModule(pipeline, folders, modules); ConfigureConDepNodeModule(pipeline, folders, modules); ConfigureConDepDotNetLibrary(pipeline, folders, modules); ConfigureCommand(commandOrScript, parameters, pipeline); var result = pipeline.Invoke(); if (pipeline.Error.Count > 0) { var errorCollection = new PowerShellErrors(); foreach (var exception in pipeline.Error.NonBlockingRead().OfType<ErrorRecord>()) { errorCollection.Add(exception.Exception); } throw errorCollection; } if (logOutput && result.Count > 0) { Logger.WithLogSection("Script output", () => { foreach (var psObject in result) { Logger.Info(psObject.ToString()); } }); } return result; } } }
/// <summary> /// This sample shows how to use WSManConnectionInfo class to set /// various timeouts and how to establish a remote connection. /// </summary> /// <param name="args">This parameter is not used.</param> public static void Main(string[] args) { // Create a WSManConnactionInfo object using the default constructor // to connect to the "localHost". The WSManConnectionInfo object can // also specify connections to remote computers. WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); // Set the OpertationTimeout property. The OperationTimeout is used to tell // Windows PowerShell how long to wait (in milliseconds) before timing out // for any operation. This includes sending input data to the remote computer, // receiving output data from the remote computer, and more. The user can // change this timeout depending on whether the connection is to a computer // in the data center or across a slow WAN. connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes. // Set the OpenTimeout property. OpenTimeout is used to tell Windows PowerShell // how long to wait (in milliseconds) before timing out while establishing a // remote connection. The user can change this timeout depending on whether the // connection is to a computer in the data center or across a slow WAN. connectionInfo.OpenTimeout = 1 * 60 * 1000; // 1 minute. // Create a remote runspace using the connection information. using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo)) { // Establish the connection by calling the Open() method to open the runspace. // The OpenTimeout value set previously will be applied while establishing // the connection. Establishing a remote connection involves sending and // receiving some data, so the OperationTimeout will also play a role in this process. remoteRunspace.Open(); // Add the code to run commands in the remote runspace here. The // OperationTimeout value set previously will play a role here because // running commands involves sending and receiving data. // Close the connection by calling the Close() method to close the remote // runspace. The Dispose() method (called by using primitive) will call // the Close() method if it is not already called. remoteRunspace.Close(); } }
private WSManConnectionInfo GetConnection(string uri, string username, string password, bool kerberos) { SecureString pwd = new SecureString(); foreach (char x in password) pwd.AppendChar(x); PSCredential ps = new PSCredential(username, pwd); WSManConnectionInfo wsinfo = new WSManConnectionInfo(new Uri(uri), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", ps); wsinfo.SkipCACheck = true; wsinfo.SkipCNCheck = true; wsinfo.SkipRevocationCheck = true; wsinfo.OpenTimeout = 9000; wsinfo.MaximumConnectionRedirectionCount = 1; if (kerberos) wsinfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos; else wsinfo.AuthenticationMechanism = AuthenticationMechanism.Basic; return wsinfo; }
public IEnumerable<dynamic> Execute(ServerConfig server, string commandOrScript, Action<PowerShellModulesToLoad> modulesToLoad = null, IEnumerable<CommandParameter> parameters = null, bool logOutput = true) { var folders = new RemoteScriptFolders(server); var modules = new PowerShellModulesToLoad(); if (modulesToLoad != null) { modulesToLoad(modules); } var remoteCredential = new PSCredential(server.DeploymentUser.UserName, GetPasswordAsSecString(server.DeploymentUser.Password)); var connectionInfo = new WSManConnectionInfo(server.PowerShell.SSL, server.Name, ResolvePort(server), "/wsman", SHELL_URI, remoteCredential); if (UseCredSSP) { using (new CredSSPHandler(connectionInfo, server)) { return ExecuteCommand(commandOrScript, connectionInfo, modules, folders, parameters, logOutput); } } return ExecuteCommand(commandOrScript, connectionInfo, modules, folders, parameters, logOutput); }
internal static Collection<PSObject> GetRemoteCommands(Guid shellId, WSManConnectionInfo wsmanConnectionInfo) { using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("Get-WSManInstance"); string str = string.Format(CultureInfo.InvariantCulture, "ShellId='{0}'", new object[] { shellId.ToString().ToUpper(CultureInfo.InvariantCulture) }); shell.AddParameter("ResourceURI", "Shell/Command"); shell.AddParameter("Enumerate", true); shell.AddParameter("Dialect", "Selector"); shell.AddParameter("Filter", str); shell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName); shell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism)); if (wsmanConnectionInfo.Credential != null) { shell.AddParameter("Credential", wsmanConnectionInfo.Credential); } if (wsmanConnectionInfo.CertificateThumbprint != null) { shell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } if (wsmanConnectionInfo.PortSetting != -1) { shell.AddParameter("Port", wsmanConnectionInfo.Port); } if (CheckForSSL(wsmanConnectionInfo)) { shell.AddParameter("UseSSL", true); } if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName)) { string str2 = wsmanConnectionInfo.AppName.TrimStart(new char[] { '/' }); shell.AddParameter("ApplicationName", str2); } shell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo)); return shell.Invoke(); } }
/// <summary> /// Disposing /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { wsConn = null; if (runspace != null) runspace.Dispose(); } disposed = true; } }
internal static bool CompareProxySettings(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { if (connectionInfo1.ProxyAccessType == connectionInfo2.ProxyAccessType) { if (connectionInfo1.ProxyAccessType != ProxyAccessType.None) { if (connectionInfo1.ProxyAuthentication == connectionInfo2.ProxyAuthentication) { if (WorkflowUtils.CompareCredential(connectionInfo1.ProxyCredential, connectionInfo2.ProxyCredential)) { return true; } else { return false; } } else { return false; } } else { return true; } } else { return false; } }
internal static bool CompareOtherWSManSettings(WSManConnectionInfo connectionInfo1, WSManConnectionInfo connectionInfo2) { bool hasValue; bool flag; if (connectionInfo1.SkipCACheck == connectionInfo2.SkipCACheck) { if (connectionInfo1.SkipCNCheck == connectionInfo2.SkipCNCheck) { if (connectionInfo1.SkipRevocationCheck == connectionInfo2.SkipRevocationCheck) { if (connectionInfo1.UseCompression == connectionInfo2.UseCompression) { if (connectionInfo1.UseUTF16 == connectionInfo2.UseUTF16) { if (connectionInfo1.MaximumConnectionRedirectionCount == connectionInfo2.MaximumConnectionRedirectionCount) { int? maximumReceivedDataSizePerCommand = connectionInfo1.MaximumReceivedDataSizePerCommand; int? nullable = connectionInfo2.MaximumReceivedDataSizePerCommand; if (maximumReceivedDataSizePerCommand.GetValueOrDefault() != nullable.GetValueOrDefault()) { hasValue = true; } else { hasValue = maximumReceivedDataSizePerCommand.HasValue != nullable.HasValue; } if (!hasValue) { int? maximumReceivedObjectSize = connectionInfo1.MaximumReceivedObjectSize; int? maximumReceivedObjectSize1 = connectionInfo2.MaximumReceivedObjectSize; if (maximumReceivedObjectSize.GetValueOrDefault() != maximumReceivedObjectSize1.GetValueOrDefault()) { flag = true; } else { flag = maximumReceivedObjectSize.HasValue != maximumReceivedObjectSize1.HasValue; } if (!flag) { if (connectionInfo1.NoEncryption == connectionInfo2.NoEncryption) { if (connectionInfo1.NoMachineProfile == connectionInfo2.NoMachineProfile) { if (connectionInfo1.OutputBufferingMode == connectionInfo2.OutputBufferingMode) { 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; } } else { return false; } } else { return false; } }
} // ValidateRemoteRunspacesSpecified /// <summary> /// Updates connection info with the data read from cmdlet's parameters and /// sessions variables. /// The following data is updated: /// 1. MaxURIRedirectionCount /// 2. MaxRecvdDataSizePerSession /// 3. MaxRecvdDataSizePerCommand /// 4. MaxRecvdObjectSize /// </summary> /// <param name="connectionInfo"></param> internal void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) { Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null."); connectionInfo.SetSessionOptions(this.SessionOption); if (!ParameterSetName.Equals(PSRemotingBaseCmdlet.UriParameterSet, StringComparison.OrdinalIgnoreCase)) { // uri redirection is supported only with URI parameter set connectionInfo.MaximumConnectionRedirectionCount = 0; } if (!_allowRedirection) { // uri redirection required explicit user consent connectionInfo.MaximumConnectionRedirectionCount = 0; } }