Execute powershell script remotely on Amazon EC2 instance from my local computer - powershell

I have an Amazon EC2 instance.
Using powershell on my local workstation, I want to be able to remote into my Amazon EC2 instance and execute some commands.
I have found many articles online but none are working or I misunderstood them (probably the latter).
Some I tried are
Managing Windows EC2 Instances remotely with Powershell
Administering EC2 instance with Windows Powershell
Enabling- PSRemoting
How to Run PowerShell Commands on Remote Computers
My understanding is that I need to:
Amazon EC2 Dashboard > Network & Security > Security Groups > Add port 5985
//Local & EC2 PowerShell(Administrator)
enable-psremoting -force
//Local PowerShell(Administrator)
set-item wsman:\localhost\Client\TrustedHosts -value "*" -force
$password = convertto-securestring -asplaintext -force -string myPassword
$credential = new-object -typename system.management.automation.pscredential -argumentlist "myUsername", $password
$session = new-pssession ec2-00-00-00-000.compute-1.amazonaws.com -credential $credential
enter-pssession $session
But I get this error
new-pssession : [ec2-00-00-00-000.compute-1.amazonaws.com] Connecting to remote server
ec2-00-00-00-000.compute-1.amazonaws.com failed with the following error message : WinRM cannot complete the
operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and
that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM
firewall exception for public profiles limits access to remote computers within the same local subnet. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:12
+ $session = new-pssession ec2-00-00-00-000.compute-1.amazonaws.com -credential $c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed

Solution found here.
The missing link was to (on the EC2 instance) open Windows Firewall with Advanced Security and edit an inbound rule.
Full Steps:
EC2 Instance
1) Open PowerShell as administrator
2) Enter enable-psremoting -force
3) Open Windows Firewall with Advanced Security
4) Inbound Rules -> Find Windows Remote Management (Http-In) - there are 2, do this for both
5) Right click -> Properties -> Advanced -> Check public
Local
6) Open PowerShell as administrator
7) Enter enable-psremoting -force
8) Enter the following:
$password = convertto-securestring -asplaintext -force -string MY_PASSWORD
$credential = new-object -typename system.management.automation.pscredential -argumentlist "MY_USERNAME", $password
$session = new-pssession MY_EC2_PUBLIC_IP -credential $credential
enter-pssession $session
Write-Host "Hello, World (from $env:COMPUTERNAME)"

I think that not exposing PowerShell via SSH was one of the biggest design mistakes MS did. Even years later they are too proud / blind to do revert that poor decision.
I suggest you to not fight with WinRM and instead, use an SSH server on your Windows machine.
You'll benefit from having a simple, standard, secure way to connect to your server from any device (I'm doing remote PS sessions from my iPad).
There is the opensource cygwin and my favorite proprietary (with free offering) PowershellServer
You'll thank me when your Windows server will play nicely with the rest of the world.

UPDATE
I got back to this old thread and would like to add another option - using the new(ish) AWS Systems Manager run-command capability.
This allows you to have no administrative port exposed to the external world so no need to fiddle with host / cloud firewalls.
It also provide other benefits like auditing, permissions etc...

Related

PSRemoting (Using SSL) from Docker Container to HostMachine

Goal: Secure Powershell Remoting to Communicate from Docker Container (Windows Server Core) to Host Machine (Windows 10).
I am trying to communicate from Docker Container to Hostmachine to run Powershell commands. PS Remoting looked promising. I did a little POC and It works simply using HTTP. I just pass in the Credentials and everything seems to work fine. However, I am having hard time securing the PS Remoting using SSL.
I followed this article to secure the PS Remoting.
Like below
$password = ConvertTo-SecureString "passwordstring" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ("username string", $password)
Enter-PSSession -ComputerName "ComputerName" -UseSSL -Credential $Cred
Expected: Powershell Remoting to Work -UsingSSL
Actual:
Enter-PSSession : Connecting to remote server DESKTOP-T773322.mshome.net failed with the following error message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName DESKTOP-T773322.mshome.net -UseSSL -Cre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (DESKTOP-T773322.mshome.net:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I am able to get the -UseSSL working from a VM to my Local Machine. but not Docker Container to Host Machine.
Things I tried:
Turn off all Windows Firewalls.
Ping works both ways (From Container to Host and Vice versa).
Ran Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell to verify if the User has enough permissions to Remote Connect.
Restart Machine.
Added the Container Machine to trusted Hosts.
Changed Trusted Hosts Value to *(all).
Note: The end goal here is to communicate from Docker Container to Local Host Machine. So, It can run Powershell Commands/Batch Files on the Host machine (Securely - Using SSL). I have not found an alternative other than PS Remoting. Please suggest me if there is another better way to do this.

CredSSP - Access is denied. For more information, see the about_Remote_Troubleshooting Help topic

The error:
New-PSSession : [{Public IP of my remote server}] Connecting to remote server
{Public IP of my remote server} failed with the following error message :
Access is denied. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Scripts\Test.ps1:24 char:12
+ $Session = New-PSSession -Computer $target -Authentication Credssp -C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
The "about_Remote_Troubleshooting" seems to be referring to this post which I've tried to follow along, but without luck.
I have a scripting server (Server A) that I'm trying to have manage a remote DC with a different hosting company.
DISCLAIMER: Since I've been failing miserably so far, I'm trying to set my configuration to be as wide-open as possible (AKA: temporarily unsecure), so that I can just see it working and then work backwards, tightening my security - as much as I can given that I'm being tasked with CredSSP in the first place... Also, I'm way over my head in this and very new to Powershell. With that in mind...
Configuration I've done on Server A:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value * -Force
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB -Value 0 -Force
Enable-PSRemoting
Set-ExecutionPolicy Unrestricted
Enable-WSManCredSSP –Role Client –DelegateComputer *
Configuration I've done on Server B:
Enable-PSRemoting
Enable-WSManCredSSP –Role Server
And for kicks, on both machines, I've run gpedit and went under Local Computer Policy → Computer Configuration → Administrative Templates → System → Credentials Delegation... enabled "Allow delegating fresh credentials" and "Allow delegating fresh credentials with NTLM-only server authentication" and added * and wsman/* to the servers list (and a few other possible combinations of IP or computer names for good measure).
So, I can send remote commands to Server B without CredSSP:
This works:
$cred = New-Object System.Management.Automation.PSCredential $username, $securePassword
Invoke-Command -ComputerName $target -Credential $cred -ScriptBlock {
Write-Host $env:computername | Select-Object
}
(Outputs name of Server B)
But if I pass that same $cred into a New-PSSession with CredSSP, that is where the error above occurs.
$Session = New-PSSession -Computer $target -Authentication Credssp -Credential $cred
Server A is able to use CredSSP with a different Domain Controller (in the same network/hosting company). Every article I've gone through seems to lead me to believe that what I've done should work in both cases... What am I missing?

Powershell CREDSSP Problems

I am trying to use CREDSSP on a New Server (Server C)
I have successfully setup credssp on Two Other Servers. (Server A to Server B)
I am now trying to connect from Server A to Server C using CREDSSP, but no matter what I do, I get the following error:
[SERVER_C.domain.edu] Connecting to remote server SERVER_C.domain.edu failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (SERVER_C.domain.edu:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
This is my query that works perfectly from Server A to Server B:
# Setting the Credentials to be used to sign into the Server B.
$pass = ConvertTo-SecureString "Password" -asplaintext -force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\user.service",$pass
#
#
# The Remote Execution Command. Fully Qualified Domain name is critical since we are using Credssp.
# Credssp is being used to resolve an issue with a double hop authentication issue. Other steps setup on each computer had to be completed before Credssp would work
Invoke-Command -ComputerName SERVER_B.domain.edu -command { C:\helloWorld.ps1 } -Authentication Credssp -Credential $mycred
I have double checked everything I can think of between Server C (New Server) and Server B (Old Server) and I cant find any reason why im getting the error.
I know that if I take out the CREDSSP part, The script works, except where a double hop is involved. So the Server is definitely connecting.
I made sure to run the following commands:
Enable-psremoting
Set-ExecutionPolicy -Scope localMachine -ExecutionPolicy RemoteSigned
Enable-WSManCredSSP -Role Client -DelegateComputer '*.reskit.org' –Force
Enable-WSManCredSSP -Role Server –Force
wsman
Also followed these steps: Use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System
-> Credentials Delegation -> Allow Delegating Fresh Credentials. Verify that it is enabled and configured with an SPN appropriate for the target computer. For example,
for a target computer name "myserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. For more information, see the
about_Remote_Troubleshooting Help topic.
And as I mentioned, I know Server A is setup correctly, because I run the script above to Server B without issue.
Any suggestions would really be appreciated.
The only thought I have is that Server A and B are running Powershell 3 and Server C is running Powershell 5
I notice that the Enable-WSManCredSSP -Role Client command uses *.reskit.org instead of *.domain.eu.(?)
To me it's not completely clear which commands were run at the server or at the client, but look OK at first sight. I recently configured credssp also to solve the double hop problem, as follows:
On the server:
Enable-WSManCredSSP -Role Server -Force
Get-WSManCredSSP shows: The machine is not configured to allow delegating fresh credentials. This computer is configured to receive credentials from a remote client computer.
On the client:
winrm quickconfig
Enable-WSManCredSSP -role client *.mydomain.com
Get-WSMancredSSP shows:
The machine is configured to allow delegating fresh credentials to the following target(s): wsman/*.mydomain.com. This computer is not configured to receive credentials from a remote client computer.
My clientside script starts an explicit remote session via:
$session = New-PSSession -Computer $computerName -Credential $credential -Authentication Credssp

Using Powershell to remotely invoke commands in Azure

I'm writing a series of automation scripts that will allow our developers to stand up a simple development environment in Azure. This environment has 3 primary properties:
There is a client machine (Windows 10) where dev tools like their IDE and code will live.
There is a server machine (Windows Server 2016) where that their scripts will target.
Both of these machines live in the same domain, and 1 Domain Admin user is available for use.
I have steps 1 and 2 scripted out, but 3 is currently a mess. Since the script is designed to work from the Developer's local workstation, I need to have the script remote in to the Windows Server and run a few commands to set up the Domain Controller.
Here is my code currently:
Invoke-Command -ComputerName "$RGName-$VMPurpose" -ScriptBlock
{
$ADFeature = Install-WindowsFeature AD-Domain-Services
If ($ADFeature.Success -eq $true)
{
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath
"C:\Windows\NTDS" -DomainMode "Win2016R2" -DomainName "$project.com" -
DomainNetbiosName "$project" -ForestMode "Win2016R2" -InstallDns:$true -
LogPath "C:\Windows\NTDS" -NoRebootOnCompletion $false -sysvolpath
"C:\Windows\SYSVOL" -force $true
$domUserPassword = ConvertTo-SecureString "Th1s is a bad password" -
AsPlainText -Force
New-ADUser -Name "$VMPurpose-DomAdm" -AccountPassword
$domUserPassword
Add-ADGroupMember -Name "Administrators" -Member {Get-ADUser
"$VMPurpose-DomAdm"}
}
} -Credential $Cred
When I attempt to run this I get an error showing that WinRM cannot connect, specifically this error:
[Foo] Connecting to remote server Foo failed with the following error
message : WinRM cannot process the request. The following error with
errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon
servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are
specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port
does not exist.
-The client and remote computers are in different domains and there is no
trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the
WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following
command: winrm help config. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionStateBroken
I added the target machine (Foo) to the TrustedHosts configuration setting in WinRM (I actually added the IP address to make sure that there wasn't any DNS problem happening), and then I get this error:
[Foo's IP] Connecting to remote server <Foo's IP> failed with the following
error message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the
computer is accessible over the network, and that a firewall exception for
the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public
profiles limits access to remote computers within the same local subnet. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo's Ip[:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
Any thoughts here? Am what I trying simply not ever going to work via Powershell?
According to your error message, we can use this PowerShell script to invoke command to Azure:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}
PowerShell result like this:
More information about invoke command, please refer to this answer.

Cannot create remote powershell session after Enable-PSRemoting

I can not remote into any machine to save my life! I have tried everything I can find. If anyone could troubleshoot or guide me, I'd appreciate it as this would be a great tool to add on my domain.
SETUP:
Client machine inside domain
Server machine inside or outside domain - Virtualized and utilized for WSUS Computername: wsustest
CLIENT SERVER MACHINE physical- computername: epizzi-pc
STEPS:
enable-pssremoting done! on all machines
trustedhosts configured with * or client machine added
Firewalls with public profile off just in case
Enter-PSSession -ComputerName wsustest -Credential wsustest\administrator
Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
Enter-PSSession : Connecting to remote server epizzi-pc failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName epizzi-pc -Credential epizzi-pc\administrador
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (epizzi-pc:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrator
*Enter-PSSession : Connecting to remote server wsustest failed with the following error message : WinRM cannot complete the operation. Verify that the specified computer name is
valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM
firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName wsustest -UseSSL -Credential wsustest\administrato ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (wsustest:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed*
ERRORs:
I was receiving the same problem when remoting to a server and found this blog post very helpful - http://jeffgraves.me/2013/10/14/powershell-remoting/
For my specific case I did the following:
On the Local machine
winrm quickconfig (although this was already configured)
winrm s winrm/config/client '#{TrustedHosts="myservername.domain"}'
On the Remote machine
enable-psremoting -force
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell -Force
I got around this problem by using a fully qualified logon. Instead of "netbiosdomain\accountname", I used fqdn\accountname, as in Microsoft.com\myaccount in the get-credential prompt. May not work for everyone, but it's worth a shot.
This is how I do it. I use this on my scripts.
# This is only done once
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File
c:\Windows\temp\securepass.txt
# Setup credentials
$SecureString = Get-Content c:\Windows\temp\securepass.txt | ConvertTo-SecureString
$mycredentials = New-Object -TypeName System.Management.Automation.PSCredential
-ArgumentList "yourDomain\userID",$SecureString
# Open remote session:
$MyRSession = New-PSSession -ComputerName Computer1 -Credential $mycredentials
-Authentication default
# Use remote session:
Enter-PSSession $MyRSession
Get rid of -UseSSL. I enabled PSRemoting and had problems with using that. I guess I could look at it later but for now it doesn't matter.
If there is no trust between the client and server computers, you have to enable basic authentication on the server side. Do this by toggling the correct properties on the WSMAN: drive on the server. You'll obviously have to do this interactively on the console or via remote desktop, due to the chicken and egg problem :) Also, this may come into play too:
http://www.nivot.org/blog/post/2009/10/30/PowerShell20EnablingRemotingWithVirtualXPModeOnWindows7
I was getting that same error currently no logon servers available.
The issue was resolved by using instead of Domain\Username as credentials the user UPN or Username#Domain.
I have achieved a remote session with Enter-pssession command, had to follow these exact parameters
$creds = get-credential (the -credential parameter in enter-pssession does not work properly, thus u must previously enter the object at another variable)
Enter-pssession -computername wsustest -authentication Default -credentials $creds
i Also had to set both client and remote server in the trusted hosts wsman: space
another solution which surely wouldve worked but i havent tried, wouldve been setting https: which is harder to do.
thx to all, your comments certainly led to the solution!