Connecting to Amazon windows instance using Amazon CLI- powershell - powershell

I'm trying to connect to amazon windows instance using powershell. I'm following the steps from the below link:
Execute powershell script remotely on Amazon EC2 instance from my local computer
http://barakme.tumblr.com/post/89748667258/windows-remote-execution-with-powershell-and-winrm
http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html
I cannot make this to work. I'm new Amazon CLI, I've been struggling for the past few days to connect to my windows instance which is already running.
I keep getting the same error each time. Am I missing out something?
enable-psremoting -force
set-item wsman:\localhost\Client\TrustedHosts -value "*" -force
$password = convertto-securestring -asplaintext -force -string "MY_PASSWORD_GOES_HEREr"
$credential = new-object -typename system.management.automation.pscredential -argumentlist "MY_USERNAME", $pa
ssword
$session = new-pssession x.x.x.x -credential $credential
new-pssession : [x.x.x.x] Connecting to remote server x.x.x.x 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 x.x.x.x -credential $credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed

Related

Test-Path Access denied Error - To check if Directory Exists on Shared Drive/Folder using powershell with credentials

I am trying to check if folder exists on network location using Test-Path powershell script with different credential having access to the Network Server but I am getting access denied error. Below is my script which I am trying to execute on local from where I am trying to connect to Network server:
$username="username"
$pass = "#Passw0rd" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$pass
$pathExists = Invoke-Command -ComputerName . -Credential $cred -ScriptBlock {
Test-Path "\\serverName\Folder"
}
Write-Host $pathExists
I am getting below error:
Access is denied
+ CategoryInfo : PermissionDenied: (\serverName\Folder:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
Note: Admin access for the account is given which is used for accessing Network path and directory
Any help will be much appreciated
The issue most likely is because the credentials stored in $cred don't have Admin privileges on your localhost, hence cannot impersonate your invocation.
Here I'm trying something similar to what you're trying, the user stored in $cred is an Administrator on remote host but does not have any permissions on my laptop (I'm obfuscating for obvious reasons):
PS C:\> icm remoteServer -Credential $cred {test-path \\remoteServer\c$\users}
True
PS C:\> icm remoteServer -Credential $cred {test-path \\localhost\c$\users}
True
PS C:\> icm -computername . -Credential $cred {test-path \\localhost\c$\users}
[localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Edit:
Here is another solution to your problem, Start-Process using the remote credentials and save the results to a file (again obfuscating the name of the remote server):
$argument="-c `"`$path='\\remoteServer\c$\users';'Attempting Test-Path '+`$path;'Result is: '+(Test-Path `$path)`""
$initHash=#{
FilePath='powershell.exe'
Credential=$cred
ArgumentList=$argument
RedirectStandardOutput="$HOME\Documents\testPath.txt"
WindowStyle='Hidden'
}
Start-Process #initHash
PS C:\> gc "$HOME\Documents\testPath.txt"
Attempting Test-Path \\remoteServer\c$\users
Result is: True

Running Powershell script using inline admin credentials to start and stop windows services

I have access as an admin on a machine and I have to Start, Stop and Restart some of the window services using the Powershell script. We don't want to have UAC prompt while running the script because only one user would have access to that machine. Also due to some specific requirements, we have to have run that script file by adding the admin credentials inside it.
Along with other solutions I have tried so far, the one close to what I am looking for is as follows
$username = "Domain\user"
$password = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Set-Service -Name Spooler -Status Running -PassThru -Credential $psCred
But I am getting following error.
Set-Service : A parameter cannot be found that matches parameter name
'Credential'. At line:6 char:53
+ ... t-Service -Name Spooler -Status Running -PassThru -Credential $psCred
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Update 1 (Trying suggestion)
Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername myComputerName
[myComputerName] Connecting to remote server myComputerName failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command on the destination to analyze
and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myComputerName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
Update 2
I had to enabled PSRemoting on machine using command Enable-PSRemoting -Force -SkipNetworkProfileCheck so Invoke-Command can execute but after repeating the command Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername localhost I got following error
[localhost] Connecting to remote server localhost failed with the
following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Running the same set of command in elevated powershell window is working fine.
Can you please guide me in the right direction considering I am newbie in the Powershell world.
As mentioned in the official documentation of Set-Service
Can you try like this?
$Cred = Get-Credential
$hostname = "$env:computername.$env:userdnsdomain"
Write-Host $hostname
Invoke-Command -ComputerName $hostname -Credential $Cred -ScriptBlock{ Start-Service -Name Spooler}
Also if you don't want to prompt for the credentials then you can store the credentials in the Windows credentials manager and get it from their in your PowerShell script. Refer to this answer for using credential manager with PowerShell

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?

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.

Unable to use PowerShell Enter-PSSession to connect to remote server

I am having problems connecting to a remote server using PowerShell where the remote machine uses a non-default port number. The setup is as follows: I have a virtual host server with several virtual machines. All of these virtual machines have the same IP address but are accessed with a different port, for example:
a.b.c.d:3000
a.b.c.d:3001
etc
So, the PowerShell script I have so far is:
$password = ConvertTo-SecureString "<MyPassword>" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("<Domain\UserName>", $password)
Enter-PSSession -ComputerName <IPAddress> -Port <PortNumber> -Credential $cred
The bits inside the "<>" are specific to the individual machines. When running this script I get the following error:
Enter-PSSession : Connecting to remote server failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS- Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command o n the destination to
analyze and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting H elp topic. At
C:\PowerShell\Test7.ps1:25 char:16
+ Enter-PSSession <<<< -ComputerName -Port -Credential $cred
+ CategoryInfo : InvalidArgument: (:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Another variant I tried is as follows:
$password = ConvertTo-SecureString "<MyPassword>" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("<Domain\UserName>", $password)
$powershell_uri = "http://<IPAddress>:<PortNumber>"
Enter-PSSession -ConnectionUri $powershell_uri -Credential $cred
but this gave the following error:
Enter-PSSession : Connecting to remote server failed with the
following error message : The client cannot connect to the destination
specified in the request. Verify that the service on the destination
is running and is accepting requests. Consult the logs and
documentation for the WS- Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command o n the destination to
analyze and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting H elp topic. At
C:\PowerShell\Test7.ps1:21 char:16
+ Enter-PSSession <<<< -ConnectionUri $powershell_uri -Credential $cred # -ComputerName -Port -Credential
$cred
+ CategoryInfo : InvalidArgument: (http://:/:Uri) [Enter-PSSession],
PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I have set the TrustedHosts on my local machine (winrm set winrm/config/client #{TrustedHosts=""}) and on the remote machine I have run the "winrm quickconfig" command. On the remote machine I have also run the "winrm create winrm/config/listener?Address=*+Transport=HTTP #{Port=""}" command.
Any assistance on how I can establish a connection within PowerShell to these machines would be greatly appreciated.
On the remote computer:
In: Control Panel\Network and Internet\Network and Sharing CenterMake sure the remote computer is not in the public location, but set it to work or private
Start PowerShell in administrator mode and enter the command:
Enable-PSRemoting
exit
Goto Control Panel -> System and Security ->Windows Firewall and click advanced Settings
Add the ip-range of your managing computer to windows remote management(http-In) both in the private and in the domain inbound rules.
On the managing computer:
Start PowerShell in administrator mode and enter the command:
Set-Item WSMan:\localhost\Client\TrustedHosts -Concatenate remotecomputer.domain.suffix -Force
using your complete remote computer's network path.
This adds the remote computer network name to your trusted hosts.
That should do the trick.