从我的本地计算机在Amazon EC2实例上远程执行powershell脚本

Th4*_*Guy 9 powershell amazon-ec2 amazon-web-services

我有一个Amazon EC2实例.

在我的本地工作站上使用powershell,我希望能够远程访问我的Amazon EC2实例并执行一些命令.

我在网上发现了很多文章,但都没有工作,或者我误解了它们(可能是后者).

我试过的一些是
使用Powershell远程管理Windows EC2实例
管理带有Windows Powershell的EC2实例
启用PSRemoting
如何在远程计算机上运行PowerShell命令

我的理解是我需要:

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  
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误

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
Run Code Online (Sandbox Code Playgroud)

Th4*_*Guy 15

发现的解决方案在这里.

缺少的链接是(在EC2实例上)打开具有高级安全性的Windows防火墙并编辑入站规则.

完整步骤:

EC2实例
1)以管理员身份打开PowerShell
2)输入enable-psremoting -force
3)打开具有高级安全性的Windows防火墙
4)入站规则 - >查找Windows远程管理(Http-In) - 有2个,为两者执行此操作
5)右键单击 - > 属性 - > 高级 - >检查公开

本地
6)以管理员身份打开PowerShell
7)输入enable-psremoting -force
8)输入以下内容:

$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)"
Run Code Online (Sandbox Code Playgroud)


Fro*_*yke 5

我认为不通过SSH暴露PowerShell是MS所犯的最大设计错误之一.即使数年之后,他们仍然过于骄傲/盲目,无法做出糟糕的决定.

我建议你不要与WinRM对抗,而是在Windows机器上使用SSH服务器.您可以从一个简单,标准,安全的方式从任何设备连接到您的服务器(我正在从iPad进行远程PS会话).

有开源cygwin和我最喜欢的专有(免费提供)PowershellServer

当你的Windows服务器与世界其他地方很好地合作时,你会感谢我.