Aller au contenu

Session Manager#

O7 Pro Tip

Avec o7cli : o7 ec2, select instance then... there is a few options.

Connection Shell (Linux) ou Power Shell (Windows)#

Start Standard Terminal
1
2
3
4
read -p "Enter Instance ID : " INSTANCE_ID
aws ssm start-session \
    --region ca-central-1 \
    --target $INSTANCE_ID

Tunnel SSH vers une BD#

  • Ouvrir un tunel SSH vers la base de donnees.
Bash
1
2
3
4
5
6
7
8
read -p "Instance ID : " INSTANCE_ID
read -p "DB Endpoint : " DB_ENDPOINT

aws ssm start-session \
    --region ca-central-1 \
    --target $INSTANCE_ID \
    --document-name AWS-StartPortForwardingSessionToRemoteHost \
    --parameters host="$DB_ENDPOINT",portNumber="5432",localPortNumber="5432"
  • Ensuite avec votre client de BD favori, branchez-vous.With your favorite DB client (ex Heidi SQL)
    • host = 127.0.0.1
    • port = 5432

Connection RDP (Manuel)#

1. Ajouter Utilisateur RDP#

  • Connecter par session PowerShell
    Bash
    1
    2
    3
    4
    read -p "Enter Instance ID : " INSTANCE_ID
    aws ssm start-session \
        --region ca-central-1 \
        --target $INSTANCE_ID
    

Tip

avec o7cli : o7 ec2, choisir l'instance et option shell

  • Dans Powershell, creer un utilisateur pour se brancher en RDP avec un role administrateur.
    PowerShell
    1
    2
    3
    4
    5
    6
    7
    $Password = Read-Host -AsSecureString
    New-LocalUser "RDPUser" -Password $Password
    Add-LocalGroupMember -Group "Remote Desktop Users" -Member "RDPUser"
    Add-LocalGroupMember -Group "Administrators" -Member "RDPUser"
    
    # List User
    Get-LocalUser
    
  • Fermer la session

2. Se brancher avec RDP#

  • Ouvrir un tunelle RDP avec le serveur.
    Bash
    1
    2
    3
    4
    5
    6
    7
    read -p "Instance ID : " INSTANCE_ID
    # RDP Forwward
    aws ssm start-session \
        --region ca-central-1 \
        --target $INSTANCE_ID \
        --document-name AWS-StartPortForwardingSession \
        --parameters "localPortNumber=54321,portNumber=3389"
    
  • Ouvrir la session RDP

    • Computer: 127.0.0.1:54321
    • UserName: RDPUser
    • Password : [de l'etape precedente]

Connection RDP (Scripté)#

Ce script fera tout le travail

  • Présente la liste des instances actives
  • Configure un utilisateur RDP
  • Prépare RDP local
  • Ouvre le tunnel
  • Lance RDP
PowerShell
# Make sure AWS CLI is set in UTF8
$env:PYTHONUTF8="1"

# --------------------------------------
# Function to get all running and stopped EC2 instances
# --------------------------------------
function Get-EC2Instances {
    $instances = aws ec2 describe-instances --filters "Name=instance-state-name,Values=running,stopped" --query "Reservations[*].Instances[*].{InstanceId:InstanceId,Name:Tags[?Key=='Name']|[0].Value,State:State.Name,Platform:Platform}" --output json | ConvertFrom-Json
    return $instances
}

# --------------------------------------
# Function to display a menu and get user selection
# --------------------------------------
function Show-MenuAndGetSelection {
    param (
        [array]$items
    )
    Write-Host "No. | Instance ID         | State   | OS Type | Name                       "
    Write-Host "----|---------------------|---------|---------|----------------------------"
    $i = 1
    foreach ($item in $items) {
        $name = if ($item.Name) { $item.Name } else { "N/A" }
        $platform = if ($item.Platform) { $item.Platform } else { "Linux  " }
        Write-Host ("{0,-3} | {1,-17} | {2,-7} | {3} | {4,-26}" -f $i, $item.InstanceId, $item.State, $platform, $name)
        $i++
    }

    $selection = Read-Host "Please select an instance by entering the corresponding number"
    return $items[$selection - 1].InstanceId
}

# --------------------------------------
# Function to run a PowerShell script on the remote instance
# --------------------------------------
function Run-RemoteScript {
    param (
        [string]$instanceId,
        [string]$script
    )

    Write-Host "Running Remote Script on $instanceId"
    # Write-Host "Script: $script"


    $commandId = aws ssm send-command --instance-ids $instanceId --document-name "AWS-RunPowerShellScript" --parameters "commands=['$script']" --query "Command.CommandId" --output text
    Write-Host ("Running command with ID : $commandId")
    Start-Sleep -Seconds 1
    $status = aws ssm list-command-invocations --command-id $commandId --details --query "CommandInvocations[*].Status" --output text
    while ($status -eq "InProgress") {
        Write-Host (".")
        Start-Sleep -Seconds 5
        $status = aws ssm list-command-invocations --command-id $commandId --details --query "CommandInvocations[*].Status" --output text
    }
    if ($status -ne "Success") {

        Write-Host "FAILED to run the script on the remote instance."
        Write-Host "------------------------------"
        aws ssm get-command-invocation --command-id $commandId --instance-id $instanceId --query "StandardErrorContent" --output text
        Write-Host "------------------------------"
        exit
    }


    Write-Host "ERRORS ------------------------------"
    aws ssm get-command-invocation --command-id $commandId --instance-id $instanceId --query "StandardErrorContent" --output text

    Write-Host "OUTPUT ------------------------------"
    aws ssm get-command-invocation --command-id $commandId --instance-id $instanceId --query "StandardOutputContent" --output text

}

# --------------------------------------
# Function to generate a password
# --------------------------------------
function Get-RandomPassword {
    param(
        [int]$length = 12
    )

    if ($length -lt 4) {
        throw "Password length must be at least 4 characters."
    }

    $LowerCase = 'abcdefghijklmnopqrstuvwxyz'
    $UpperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    $Numbers = '0123456789'
    $SpecialCharacters = '!#$%&*()-_=+[]{}|;:,.<>?'
    $AllCharacters = $LowerCase + $UpperCase + $Numbers + $SpecialCharacters

    $Password = ''
    $Password += $LowerCase | Get-Random -Count 1
    $Password += $UpperCase | Get-Random -Count 1
    $Password += $Numbers | Get-Random -Count 1
    $Password += $SpecialCharacters | Get-Random -Count 1

    for ($i = 4; $i -lt $length; $i++) {
        $Password += $AllCharacters | Get-Random -Count 1
    }

    $Password = ($Password.ToCharArray() | Sort-Object {Get-Random}).ToString()

    return $Password
}



# Get all running and stopped EC2 instances
$instances = Get-EC2Instances

# Check if there are any instances
if ($instances.Count -eq 0) {
    Write-Host "No EC2 instances found."
    exit
}

# Show menu and get the selected instance ID
$instanceId = Show-MenuAndGetSelection -items $instances

# Output selected instance ID
Write-Host "Selected Instance ID: $instanceId"


# Define User and Password
$username = 'RDPUserAuto'
$password = Get-RandomPassword -length 15

Write-Host "$username password: $password"

# Define Script to set up RDP User
$rdpUserScript1 = @"
if (-not (Get-LocalUser -Name $username -ErrorAction SilentlyContinue)) {
    Write-Host \"Create New RDP User\"
    New-LocalUser -Name $username -Password (ConvertTo-SecureString -AsPlainText $password -Force) -FullName \"RDP User\" -Description \"User for RDP access\"
    Add-LocalGroupMember -Group \"Remote Desktop Users\" -Member $username
    Add-LocalGroupMember -Group \"Administrators\" -Member $username

    Add-LocalGroupMember -Group \"Utilisateurs du Bureau à distance\" -Member $username
    Add-LocalGroupMember -Group \"Administrateurs\" -Member $username
} else {
    Write-Host \"Setting New Password on existing RDP User\"
    Set-LocalUser -Name $username -Password (ConvertTo-SecureString -AsPlainText $password -Force)
}
Get-LocalUser
"@

$rdpUserScript2 = @"
Get-Disk
"@

# Run the script on the remote instance
Run-RemoteScript -instanceId $instanceId -script $rdpUserScript1

Write-Host "Press any key to Open Tunnel"
$null = Read-Host


# Start a session using AWS Systems Manager Session Manager
$sessionCommand = "aws ssm start-session --target $instanceId --document-name AWS-StartPortForwardingSession --parameters portNumber=3389,localPortNumber=3390"

# Start the session
Start-Process -NoNewWindow -FilePath "cmd.exe" -ArgumentList "/c $sessionCommand"


# Wait for the session to start
Start-Sleep -Seconds 5

Write-Host "Press any key Start RDP Window"
$null = Read-Host


$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$encryptedPassword = $securePassword | ConvertFrom-SecureString

# Define the RDP connection parameters
$rdpFilePath = "$env:TEMP\rdp_connection.rdp"
$rdpContent = @"
full address:s:localhost:3390
username:s:$username
domain:s:
password 51:b:$encryptedPassword
"@

# Save the RDP connection parameters to a file
$rdpContent | Out-File -FilePath $rdpFilePath -Encoding ASCII

# Start the Remote Desktop Connection application with the RDP file
Start-Process -FilePath "mstsc.exe" -ArgumentList $rdpFilePath