How to programmatically/remotely execute a program in EC2 Windows instance

后端 未结 5 1880
故里飘歌
故里飘歌 2020-12-08 03:13

I\'d like to launch an EC2 Windows instance, upload an EXEecutable & execute it (all in an automated fashion, this is important)

So far I was ab

5条回答
  •  清歌不尽
    2020-12-08 03:58

    An alternative approach is to use Windows powershell and WinRM - it allows for remote execution, a bit like ssh on Linux.

    Here is a sample of a powershell script you can run on the client to remote execute a script (taken from: https://github.com/CloudifySource/cloudify/blob/master/esc/src/main/resources/clouds/ec2-win/upload/bootstrap-client.ps1):

    param ([string]$target, [string]$username, [string]$password, [string]$command)
    
    $ErrorActionPreference="Stop"
    
    # Set up the password
    $securePassword = ConvertTo-SecureString -AsPlainText -Force $password
    $cred = New-Object System.Management.Automation.PSCredential $username, $securePassword
    
    Write-Host "Connecting to management service of $target"
    Connect-WSMan -Credential $cred $target 
    
    set-item WSMan:\$target\Client\TrustedHosts -Value * -Force
    set-item WSMan:\$target\Shell\MaxMemoryPerShellMB -Value 0 -Force
    
    Write-Host Invoking command on Remote host $target
    Invoke-Command -ComputerName $target -Credential $cred  -ScriptBlock {  
        Invoke-Expression $args[0]
    } -ArgumentList $command
    Write-Host "Command finished"
    

    You can run this command from your own script with the following command:

    powershell.exe -inputformat none -File PATH_TO_SCRIPT -target TARGET_IP -password PASSWORD -username USERNAME -command COMMAND_TO_EXECUTE
    

    You should probably quote your strings, especially the password and command, as these will usually have special characters that powershell can interpret as something else.

    The WinRM service is on by default on the EC2 Amazon Windows AMIs. All you need to do is open port 5985 (the WinRM port) in your security group.

    Finally, if you have never used powershell remoting on your client machine before, there are a couple of commands you should execute to set it up (you only need to do this once):

    set-item WSMan:\localhost\Client\TrustedHosts -Value * -Force
    set-item WSMan:\localhost\Shell\MaxMemoryPerShellMB -Value 0 -Force
    Enable-PSRemoting
    Set-ExecutionPolicy unrestricted
    

    Make sure to run these as an Administrator.

提交回复
热议问题