Chapter 5: Amazon EC2 (Elastic Compute Cloud)
5.4 Connecting to your instance
Quick answer: the short, self-contained version of this lesson is the guide How to SSH into EC2 from Windows, Mac and Linux.
In my classes, this is where most students get stuck the first time – wrong username, wrong key permissions, or port 22 blocked. Follow the steps for the connection method your lab supports. Check the actual network path, guest user and credential at each stage.
माझ्या क्लासमध्ये पहिल्या वेळेला सगळ्यात जास्त स्टुडंट्स इथेच अडकतात – चुकीचा यूजरनेम, की च्या चुकीच्या परमिशन्स, किंवा पोर्ट 22 ब्लॉक. तुमच्या लॅबमध्ये मंजूर असलेल्या पद्धतीच्या स्टेप्स वापरा. Network path, guest user आणि key प्रत्येक टप्प्यावर तपासा.
मेरी क्लास में पहली बार सबसे ज़्यादा स्टूडेंट्स यहीं अटकते हैं – गलत यूज़रनेम, की की गलत परमिशन्स, या पोर्ट 22 ब्लॉक. अपनी लैब में स्वीकृत तरीके के चरण अपनाओ। Network path, guest user और key हर चरण में जाँचो।
Default usernames
| AMI | SSH user |
|---|---|
| Amazon Linux 2023 / Amazon Linux 2 | ec2-user |
| Ubuntu | ubuntu |
| CentOS Stream or older CentOS images | Check the selected AMI publisher. Images can document ec2-user or centos. |
| RHEL | ec2-user |
| Debian | admin |
| SUSE | Check the image documentation for the approved default user. |
From Linux or macOS (OpenSSH)
LAB_KEY="$HOME/approved-key-store/REPLACE_WITH_LAB_KEY.pem"
LAB_USER='REPLACE_WITH_APPROVED_GUEST_USER'
LAB_HOST='REPLACE_WITH_APPROVED_LAB_HOST'
ssh -o IdentitiesOnly=yes -o ConnectTimeout=8 -i "$LAB_KEY" "$LAB_USER@$LAB_HOST"
At the first SSH prompt, compare the displayed host key fingerprint with the one from your own instance's trusted EC2 system log. On images that publish their host keys there, open the intended instance’s system log and look for BEGIN SSH HOST KEY FINGERPRINTS. If the image does not report them, obtain the expected fingerprint through another approved trusted source. Compare the same key type. Type yes only if it matches. SSH then remembers the host key in ~/.ssh/known_hosts. AWS connection prerequisites
This fingerprint (a unique mark that identifies the server) is saved on the first connection. On a later connection SSH checks the remembered key. If the key unexpectedly changes, stop and check the instance ID, address and expected fingerprint before accepting anything new.
पहिल्या connection वेळी दाखवलेला fingerprint मंजूर स्रोताशी जुळतो का ते तपासा. जुळल्यावर client server key लक्षात ठेवतो. पुढे ती अनपेक्षितपणे बदलली तर नवीन key स्वीकारण्यापूर्वी instance, address आणि अपेक्षित fingerprint पुन्हा पडताळा.
पहले connection पर दिखा fingerprint विश्वसनीय स्रोत से मिलाओ। मेल होने पर client server key याद रखता है। बाद में key अचानक बदले तो नई key स्वीकार करने से पहले instance, address और अपेक्षित fingerprint जाँचो।
UNPROTECTED PRIVATE KEY FILE!
If you see Permissions 0644 for 'mykey.pem' are too open, SSH refuses to use the key. Fix with chmod 400 mykey.pem. Never share your .pem, never upload it to GitHub, never e-mail it.
From Windows — option 1: built-in OpenSSH (Windows 10/11)
Open PowerShell, check the existing key ACL, and use an approved file and guest account. If the ACL is incorrect, follow the account’s supported Windows key-permission procedure.
$LabKey = Join-Path $env:USERPROFILE 'approved-key-store\REPLACE_WITH_LAB_KEY.pem'
$LabUser = 'REPLACE_WITH_APPROVED_GUEST_USER'
$LabHost = 'REPLACE_WITH_APPROVED_LAB_HOST'
Get-Acl -LiteralPath $LabKey | Format-List Owner, AccessToString
ssh.exe -o IdentitiesOnly=yes -o ConnectTimeout=8 -i $LabKey "$LabUser@$LabHost"
From Windows — option 2: PuTTY
- Install PuTTY (includes PuTTYgen).
- If you downloaded a
.pem: open PuTTYgen → Load → choose All files → selectmykey.pem→ Save private key asmykey.ppk. - Open PuTTY → Session → Host Name:
ec2-user@<PUBLIC_IP>(orubuntu@...), Port 22. - Connection → SSH → Auth → Credentials → Private key file for authentication → browse to
mykey.ppk. - Back to Session, type a name under Saved Sessions → Save → Open → compare the host-key fingerprint with the trusted record for this instance. Accept only after verification.
From Windows — option 3: MobaXterm
- Use MobaXterm if the training workstation and account permit that client.
- Session → SSH → Remote host:
<PUBLIC_IP>, tick Specify username:ec2-user/ubuntu. - Advanced SSH settings → tick Use private key → select
mykey.pem(MobaXterm accepts .pem directly). - Select OK and verify the server host-key fingerprint before trusting the connection. An SFTP pane may be available after login. Upload files only if the lab calls for it.
Other connection options
- EC2 Instance Connect (browser-based): select instance → Connect → EC2 Instance Connect tab → Connect. Requires a supported guest setup, caller IAM permission and the appropriate route to the SSH listener. For a public browser-based path, follow the documented allowed source for the service and Region. For a private endpoint design, follow the endpoint’s network and permission requirements.
- Session Manager (AWS Systems Manager): The ordinary managed shell does not require an inbound SSH rule. Verify SSM Agent support, managed instance permissions, network connectivity to the needed services and operator session permission.
First commands after logging in
hostname
id
cat /etc/os-release
date -u '+%Y-%m-%dT%H:%M:%SZ'
First confirm the guest hostname, logged-in user and operating system. An order at 08:00 IST is 02:30 UTC on the same date. A service can retain UTC logs and display local time separately. Package upgrades and host timezone changes belong to an approved maintenance plan.
लॉगिन झाल्यावर आधी guest चा hostname, user आणि operating system तपासा. सकाळी 08:00 IST म्हणजे त्याच दिवशी 02:30 UTC. Logs UTC मध्ये ठेवून app मध्ये स्थानिक वेळ दाखवता येते. Package update किंवा timezone बदल मंजूर maintenance नुसार करा.
लॉगिन के बाद पहले guest का hostname, user और operating system देखो। सुबह 08:00 IST उसी दिन 02:30 UTC है। Logs UTC में रखकर app में स्थानीय समय दिखा सकते हो। Package update या timezone बदलाव स्वीकृत maintenance के अनुसार करो।
Instance metadata (IMDSv2)
EC2 instance metadata access and IMDSv2 requirements depend on the image, account defaults and launch settings. This login exercise does not need metadata. Read basic guest identity using the commands above and confirm the EC2 record through the approved AWS view.
Ravindra Bagale's Tip
Keep one folder like ~/aws-keys/ for all your .pem files, run chmod 400 on each file and give keys clear names (mumbai-lab-key.pem). If you lose a private key, AWS cannot give it back. And never, ever push a key to GitHub – bots find secrets in public repositories within minutes.
Ravindra Bagale's Tip – मराठी
तुमच्या सगळ्या .pem files साठी ~/aws-keys/ सारखा एकच folder ठेवा, प्रत्येक file वर chmod 400 चालवा आणि keys ना स्पष्ट नावं द्या (mumbai-lab-key.pem). Private key हरवली तर AWS ती परत देऊ शकत नाही. आणि key कधीच, कधीच GitHub वर push करू नका – bots काही मिनिटांतच public repositories मधली secrets शोधतात.
Ravindra Bagale's Tip – हिंदी
अपनी सारी .pem files के लिए ~/aws-keys/ जैसा एक ही folder रखो, हर file पर chmod 400 चलाओ और keys के नाम साफ़ रखो (mumbai-lab-key.pem). Private key खो गई तो AWS उसे वापस नहीं दे सकता. और key को कभी भी, कभी भी GitHub पर push मत करना – bots कुछ ही मिनटों में public repositories में secrets ढूँढ लेते हैं.
Ravindra Bagale's Tip
Read the exact error. If you get Permission denied (publickey), check the guest user, approved key and whether it is still authorized. If you get Connection timed out, verify the actual endpoint, client path, listener and the relevant route and security policy.
Ravindra Bagale's Tip – मराठी
नेमका error वाचा. Permission denied (publickey) आला तर guest user, मंजूर key आणि ती अजून अधिकृत आहे का ते पाहा. Connection timed out आल्यास खरा endpoint, client path, listener, route आणि लागू security policy तपासा.
Ravindra Bagale's Tip – हिंदी
ठीक error पढ़ो। Permission denied (publickey) आए तो guest user, स्वीकृत key और उसकी मौजूदा अनुमति देखो। Connection timed out आए तो सही endpoint, client path, listener, route और लागू security policy जाँचो।
Lab
Use an approved access method for your one training instance. Verify the host, intended guest user and /etc/os-release, then exit the session. If another method is already enabled for the same approved lab, compare its prerequisites. Use the sample errors on this page to practice diagnosis without changing software or trying unrelated identities.
Recognize which computer your command is running on
The training page from the previous lesson is inside Mauli's EC2 Linux instance. You are sitting at a laptop, possibly running Windows, macOS or a local Linux shell. An SSH or managed session lets you run commands on the remote guest through a permissioned connection. Beginning students sometimes read their laptop's file or change a local setting while waiting for the remote command to take effect. Label both sides of the connection before typing the first command.
The client starts the session. It uses a named hostname or address, the actual access path and the intended remote username. The server or managed session system verifies whether you may connect. Once you have a shell, commands such as hostname, id and cat /etc/os-release help identify the environment. A visible prompt or an assigned public address does not prove you are on the right instance. Record its cloud ID and intended region in your training notes before connecting.
There are three separate checks in a basic SSH connection. First, TCP traffic needs to reach the configured listener over the approved route. Second, the client checks the server's host key, which helps verify it reached the expected service. Third, the remote server decides whether the chosen account and client credential are permitted. It is possible to reach the listener, verify the host key and still fail user authentication. The reported error gives you a clue about which check to inspect.
Use only a disposable instance or another instance your training owner authorizes you to access. Pick the connection method the account prepared for it. For a private worker, the approved choice might be Session Manager, an EC2 Instance Connect Endpoint or an existing private network to the instance. An instructor-approved direct SSH exercise may use a public IPv4 path. These methods share a goal of reaching the guest, but they do not all use the same network or identity checks.
Choose the connection method by drawing its actual path
| Method | What the user initiates | Key prerequisites to verify |
|---|---|---|
| Direct OpenSSH or another SSH client | SSH to the intended host and configured port over an approved network. | Route, inbound source permission for that path, listening SSH service, correct guest user and key, and trusted host identity. |
| EC2 Instance Connect | Approved AWS operation supplies a temporary public key for an SSH connection to a supported guest. | Supported software, caller IAM permission, correct guest user and an approved network path to the SSH service. |
| EC2 Instance Connect Endpoint | An approved AWS endpoint provides a connection path to an instance in the VPC. | Endpoint and instance network policy, IAM permissions and supported guest authentication. The target can lack a direct public IP. |
| Systems Manager Session Manager | Open an AWS-managed session to a managed instance. | Supported and functioning SSM Agent, instance permissions, access to required service endpoints and operator session permission. |
Public, private and managed access are choices about the required path. An Amazon Linux guest on a subnet with an internet gateway route still needs a supported public association to be reached directly through that route with IPv4. More importantly, many training and production guests should use another path. An SSH client on a laptop can reach a permitted private address through an approved private network. A browser-to-service-managed session can work through AWS service access without a direct inbound rule for TCP 22.
Verify the identity requirements before changing anything in a security group. A role that allows viewing an EC2 instance is not automatically allowed to start a managed session or supply an Instance Connect key. Authentication to the guest can also require a specific username that matches the selected AMI. Read the connection details and training account controls. If a method is unavailable because the instance is not configured for it, use the authorized method in the plan rather than opening an unrelated path for convenience.
Always distinguish an endpoint from the actual target. The name of a connection endpoint identifies an intermediate resource used to reach the guest. The guest still has its own service and operating system identity. An approved path through an endpoint can often solve the network access requirement without changing the instance's public association. It cannot create an authorized account inside an arbitrary guest. Record the start of the connection and the expected reached instance separately.
Prepare the four inputs for a direct SSH session
In the console locate the exact permitted instance in the approved account and Region. Read its state, intended access route and designated hostname or IP. If the class uses an ordinary auto-assigned public IPv4, check the current value because a stop and start can change it. In a private design use the destination provided for that path. An old saved IP does not prove it still identifies the particular machine you need.
Next identify the guest username. Amazon Linux commonly uses ec2-user. Official Ubuntu cloud images commonly use ubuntu. The correct login depends on the selected publisher, operating system image and configuration. Check its documentation and the Connect details rather than trying every username you know. A guest administrator can configure different users and authorized keys after launch.
Find the exact private key file that belongs to the approved access path. The instance's key-pair name helps identify it, but you can also use the controlled records maintained for the lab. Never paste that file into a chat or web form. Keep it in the approved key store or local directory with appropriate permissions. An exported public key or a PuTTY key in the wrong format cannot always be used where an OpenSSH client expects a supported private key file.
Finally note the listener port. SSH often uses TCP 22. An environment can use a different authorized listener. The route and permissions need to match the configured protocol and port, and the credential needs to match the guest account. If the lab's approved connection requires a VPN, connect that path before running the command. The following OpenSSH example needs values from your own training account, which are intentionally left as placeholders.
LAB_KEY="$HOME/approved-key-store/REPLACE_WITH_LAB_KEY.pem"
LAB_USER='REPLACE_WITH_APPROVED_GUEST_USER'
LAB_HOST='REPLACE_WITH_APPROVED_LAB_HOST'
ssh -o IdentitiesOnly=yes -o ConnectTimeout=8 \
-i "$LAB_KEY" "$LAB_USER@$LAB_HOST"
-i selects an identity file. IdentitiesOnly=yes limits offered identities to the configured set rather than offering every unrelated key from an agent. ConnectTimeout bounds connection establishment and the initial SSH handshake in supported OpenSSH. Quoting preserves paths with spaces. Set the placeholders first, and only connect to a named lab instance that you are allowed to use. If the port is different, use the approved port using -p. The command leaves host key verification enabled.
Verify the server’s host key before sending login credentials
A host key identifies the SSH server. A user key pair lets the client prove it is permitted to use a guest account. These are separate keys. During a first connection the client may display the server key's fingerprint and ask whether you trust that server. A fingerprint is a compact representation of a specific key. Compare the displayed key type and fingerprint to a trusted record for the selected instance before accepting it.
On a supported EC2 Linux image the trusted instance console output or system log may show SSH host key fingerprints generated during setup. Use the entry for the same instance record and key algorithm. If the image does not publish this information, ask the training owner for an authenticated record or use an approved alternative access that lets the owner verify the identity. A fingerprint fetched from the same unverified path does not independently prove which server supplied it.
When the keys match, accept the intended host according to the training procedure. OpenSSH can store it in its known-hosts file for subsequent connections. If a warning later says that the remote host identification changed, pause. A planned replacement may legitimately generate new host keys. An ordinary unchanged machine should normally still present its expected identity. An address or proxy path might also lead to a different host. Verify the instance ID, current address and expected new host key before editing just the relevant trusted record.
The same reasoning applies if you use a different client such as PuTTY or MobaXterm. A visual dialog asking to trust the server represents a security decision, not a billing or network configuration issue. Confirm the approved fingerprint rather than accepting an unexpected key to get past the dialog. Do not erase all saved records, switch off host checks or share key files to work around an identity warning.
Be precise when reporting a failed first login. “The host key matched, but the server rejected the account's public-key authentication” means a different stage than “The DNS address changed and the saved key no longer matches.” Record the type of error and the approved endpoint. If a trusted administrator planned a replacement, compare the keys through the agreed access channel. If there was no change, follow the account's incident handling procedure instead of making assumptions about the new endpoint.
Use the user key file without disclosing or confusing it with the host key
A public-key SSH client uses the private key to prove that it controls the matching public key without sending the private key file to the guest. The guest checks whether a permitted public key is authorized for that user under its configuration. Selecting a correct file is part of the expectation. If you changed the username or the guest's authorized access was rotated, the key from the original launch may no longer be the one accepted now.
Some systems refuse a private key file that is readable by unrelated users. On macOS or Linux the mode 400 grants the file's owner read permission and no ordinary group or other permissions. A warning can also stem from a mismatch between the key file owner and the local account using it. Inspect the exact lab file before making changes. Only adjust your own approved copy. Do not recursively change permissions in a shared directory. A mode change does not turn the wrong file into the correct key for the instance.
On Windows, NTFS ownership and access control lists govern the file instead of POSIX mode bits. Check the owner's approved procedure for protecting the file. In a corporate system a managed key store, client configuration or access broker may provide the credential. If AWS or your instructor gives you a short-lived access flow, it may not require storing a permanent private key on the laptop at all. Avoid creating extra untracked copies just to use another client.
PuTTY's supported key formats and import procedure depend on the client version. Use PuTTYgen where the approved flow needs a PuTTY private key format from your authorized file. Preserve the key's protections and verify the chosen account and host fingerprint in the new client. An SFTP view may show that a client session exists. Uploading is a separate action on the remote guest. The initial connection lesson verifies access without changing files on the server.
If a key was lost, consult the owner's approved recovery mechanism. AWS cannot retrieve the private half of an EC2-generated key after creation. An authorized alternative such as an already configured managed session might let the owner restore access. Coordinate rotation and remove any superseded access according to policy. Never retrieve another person's key or place a long-lived secret in the instance's user data to make a training connection work.
Understand the identity and network behind a managed session
EC2 Instance Connect can supply an SSH public key to a supported guest for a short time. This involves AWS IAM permission to send the key and guest support to retrieve and use it. The managed operation is an authorization step. There still needs to be a usable route to the SSH listener, and the selected operating system username matters. With a browser-based connection over the public path, follow the documented source range for the service and approved Region rather than opening SSH from everywhere.
A private EC2 Instance Connect Endpoint provides an approved connectivity path in the VPC for its supported use cases. Review both the endpoint's own network permissions and the instance's permitted path, including the service's source-IP preservation behavior if used. Endpoint IAM access and guest authentication have separate roles. A target can lack a direct public IPv4 when the endpoint setup is appropriate. Check the actual method selected in the AWS console instead of inferring which endpoint the Connect action uses.
Session Manager uses a managed instance agent and its required network path to Systems Manager services. The operator starts a session with account permissions under the configured controls. An instance can commonly stay without direct inbound SSH for this workflow. If the console says the target is not connected, inspect agent state, instance or management configuration and the applicable routes or service endpoints with the training owner. Opening port 22 cannot fix an agent registration problem.
Temporary AWS credentials, an instance profile and a login username each refer to different identities. The operator role controls whether the named person can start the session. The instance's approved configuration allows the necessary management traffic and its service identity. The Linux account used after connection depends on the session method and settings. Run id in the intended session. Read the result as an observation, and only perform actions that the training account permits for that role.
Transfer the same SSH inputs to a Windows client
Windows installations can provide an OpenSSH client that runs from PowerShell. Check that the client is already available under the workstation's software policy, for example by running ssh.exe -V. The hardware or operating system of the EC2 guest does not change just because the learner's laptop runs Windows. Continue to use the account and endpoint documented for the Linux image. The client-side path syntax and key permissions are the parts you need to adapt locally.
The following PowerShell commands prepare a key path under an approved local storage directory, inspect the existing file ACL and start the authorized connection. The display operations do not grant new permissions or rewrite inherited access. Replace every placeholder and use only the approved key you own. If the key ACL is not suitable, follow the Windows and AWS instructions for your particular machine or ask its administrator.
$LabKey = Join-Path $env:USERPROFILE 'approved-key-store\REPLACE_WITH_LAB_KEY.pem'
$LabUser = 'REPLACE_WITH_APPROVED_GUEST_USER'
$LabHost = 'REPLACE_WITH_APPROVED_LAB_HOST'
Get-Acl -LiteralPath $LabKey | Format-List Owner, AccessToString
ssh.exe -o IdentitiesOnly=yes -o ConnectTimeout=8 -i $LabKey "$LabUser@$LabHost"
Use a different variable name from $Host, which is a built-in PowerShell variable. If the path list says the file is missing, resolve the path before running SSH. One oversight in classroom shells is a filename ending in an extra extension the file browser concealed. Avoid copying a key to an open folder to make it easier to find. Choose the correct approved storage and use the actual path. Verification of the remote host fingerprint is still part of first connection.
With PuTTY, enter the intended hostname, port and remote username. Use a key in the format the selected PuTTY release expects under its credential settings. If converting an OpenSSH private key, use the approved version of PuTTYgen and protect the resulting key file independently. An OpenSSH path and PuTTY path can represent the same credential in different formats. Treat each private file as sensitive. The host key alert still needs out-of-band verification before selecting the appropriate trust option.
If a Windows client can connect while another cannot, compare the exact selected target, username, identity file and first-time host key evidence. Install status and client profile are part of the local environment. Two applications on one laptop can use different saved usernames, IPs or authentication options. Use an approved client that meets the account's rules and record which one produced your training result.
Use the error to locate the failing connection step
| Observation | What it can tell you | Next permitted check |
|---|---|---|
| Could not resolve hostname | The name or resolver result is not usable by the SSH client. | Check the endpoint spelling and private network or DNS context. Verify the intended name in the lab inventory. |
| Connection timed out | The client did not obtain the required response in time for a connection phase. | Confirm instance and destination address, client path, configured port, routing and applicable network controls. |
| Connection refused | A responder rejected the connection attempt instead of accepting it. | Check whether the intended port and address have a functioning SSH listener. Confirm the rejecting responder where possible. |
| Remote host identification has changed | The presented host key conflicts with the trusted entry for the chosen destination. | Stop and verify the intended server and its trusted current key before editing any saved record. |
| Permission denied (publickey) | The reached server did not accept an offered user credential under the selected login conditions. | Verify remote username, intended private key, file protections and currently authorized public keys. |
| Managed session target unavailable | The agent, account authorization or service connectivity may not be ready. | Review the exact service message and approved agent registration, role and endpoint path. |
These observations are clues and can have several causes. A timeout might arise from a missing route, policy, unhealthy host or wrong address. A rejected user credential indicates the client got farther than a connection timeout. An unexpected host key warns about the identity of the server before you decide whether to trust it. Switching keys cannot make a missing route deliver packets, and widening the source policy cannot make an unauthorized username valid.
A useful comparison holds the destination, access method and operating system username steady while inspecting one changed factor. If the learner changed from the office network to a hotspot, record the new client network and current approved path. If the instance was stopped or replaced, record its current IP and host identity separately. When using diagnostic mode such as ssh -v in an authorized lab, review only the relevant connection phase and keep full local usernames, paths and private network information out of a public ticket.
Match two public fingerprints without using a real account or server
This offline lab needs Bash, OpenSSH's ssh-keygen, awk and the ordinary temporary-directory tools. It creates one throwaway local key pair under your current account, derives the same public key from the private file, compares the two public fingerprints and deletes the scratch copies when the script exits. The private key intentionally has no passphrase for this isolated experiment. Do not reuse it for any server or store it as a real credential. The lab does not connect to a host.
#!/bin/bash
set -eu
directory=$(mktemp -d "${TMPDIR:-/tmp}/mauli-key-lab.XXXXXX")
cleanup() {
rm -f "$directory/training_ed25519" "$directory/training_ed25519.pub" \
"$directory/derived.pub"
rmdir "$directory"
}
trap cleanup EXIT
ssh-keygen -q -t ed25519 -N '' -C 'local-worksheet' \
-f "$directory/training_ed25519"
ssh-keygen -y -f "$directory/training_ed25519" > "$directory/derived.pub"
original=$(ssh-keygen -lf "$directory/training_ed25519.pub" | awk '{print $2}')
derived=$(ssh-keygen -lf "$directory/derived.pub" | awk '{print $2}')
test "$original" = "$derived"
printf '%s\n' 'Public fingerprints agree for the same training key pair.'
Run the block in a Bash session or a scratch script you own. You should see the final sentence without any private key data printed. The temporary filename identifies a newly created directory so an existing key is never overwritten by the exercise. In the two commands that inspect fingerprints, only the short public value is compared, and it remains in shell variables. Comparing public values answers whether the two public files describe the same key. It says nothing about which user is authorized on a remote machine.
In the actual login flow the server's host-key fingerprint needs another record, obtained from an approved trusted source. This lab demonstrates the comparison of public fingerprints. It does not identify any EC2 host. If you cannot run it because a workstation disallows key generation or the configured OpenSSH lacks the selected algorithm, complete it on paper. Do not modify workstation security policy. Explain why the public copies should agree and why their match cannot establish a remote host's identity.
A failed comparison would suggest the files did not come from the same key pair or a command did not return the expected value. Check the generated scratch filenames and relevant error. The script removes only its three known scratch files and its own empty directory. If you move the code into a separate practice script, remove or retain that ordinary script according to your training needs. It contains no live key or endpoint.
Prove the session reached the intended Linux guest using read-only commands
Use one permissioned access method supplied by the previous launch lesson. In the local shell, note the prompt, current hostname and operating system as helpful context. Use only the host and login your class owner approved. For direct SSH verify the host key from a trusted record. For a managed session choose the exact approved instance record in the intended account and Region. Either method should reach the same teaching environment when its prerequisites are met.
In the remote session run the following observations. They read basic system information and do not update packages, change the server timezone or ask the instance for AWS credentials. Some CMD shells or PowerShell sessions interpret the local commands differently, so use these lines only after you have an approved Linux guest shell.
hostname
id
cat /etc/os-release
date -u '+%Y-%m-%dT%H:%M:%SZ'
Expect the approved guest hostname or identifying information, the guest user and groups that match the chosen access method, the intended Linux distribution, and the current time formatted in UTC. The date output is a demonstration of reading time in a common reference. Applications can display local time separately. A change to a host timezone is a different operational decision and is outside this simple connection check.
For the student report, write the expected resource alias, actual guest user and distribution, and an authorized timestamp. If the actual username differs from the SSH example, check whether you used a managed session configuration that selects another user. If the image is different, verify the instance ID and access path before running any modifications. Keep whole machine identifiers and any private data in the approved exercise record. Ask the training owner to interpret surprises before proceeding.
Type exit to end the remote shell and confirm you are back at your local prompt. A session ending does not stop or terminate the EC2 instance. If this was a disposable resource you own, follow its existing cleanup plan and identify any separate storage and addresses. If it was a pre-existing shared lab, leave the resource in its intended state. The connection lab itself creates no paid component or guest file.
Handle a logged event without mistaking connection for a maintenance window
Mauli's support ticket says that the test order was placed at 08:00 in India. A remote command prints a UTC time for the corresponding event. India Standard Time is five hours and thirty minutes ahead of UTC, so 08:00 IST corresponds to 02:30 UTC on the same date in this example. The two labels can refer to the same instant. Compare the logged time's stated timezone, record format and event identifier before assuming an application clock is wrong.
Logging in gives you a way to inspect the approved system. It does not authorize a package upgrade or timezone change. An update can restart a service, change a dependency or make later steps differ from the boot image. Use an approved maintenance plan when the course needs one. Start with read-only facts, and keep application and operator identities separate. A better first login record states which host and role you verified and whether the required training service appears where expected.
Instance metadata access also belongs to a separate purpose. AWS supports metadata options that vary by account, AMI and launch configuration, and supports IMDSv2's session-oriented access. Some metadata categories can include sensitive material. This connection exercise needs hostname, OS and the cloud resource record. It has no need to request role credentials or print metadata output. If a future lesson troubleshoots a workload identity, use the lab owner's approved tools and required scope.
Inspect an SSH command’s resolved options before connecting
A classmate has a saved SSH profile that chooses an old port or guest user. They type an alias and the program appears to use the right server name, but the output still seems wrong. OpenSSH can print its selected configuration after it evaluates the applicable options. The command below uses a documentation hostname, overrides the client configuration with an empty system file for the exercise, and prints only a few selected fields. The -G flag prints resolved settings and exits instead of starting an SSH session.
ssh -G -F /dev/null -l ec2-user -p 2222 \
-o "IdentityFile=$HOME/approved-key-store/training-example.pem" \
tracking.example.com | \
awk '$1 == "user" || $1 == "hostname" || $1 == "port" || $1 == "identityfile"'
Use a Unix-like terminal with OpenSSH and awk. Expect lines identifying ec2-user, tracking.example.com, the chosen example port 2222 and the identity file argument. The file path is a demonstration and need not refer to an existing key. Do not run a normal connecting SSH command against that documentation name. In a real approved lab you can inspect the locally selected options for your entitled endpoint and compare them to the connection record.
Try omitting only the -p flag from the offline command. In a standard profile the chosen port becomes 22. This check provides evidence about the client's selected configuration before the connection begins. It cannot tell whether a real server listens there or accepts the corresponding identity. You can use it to separate a wrong saved client choice from a network problem, then verify that real reachability under the authorized workflow.
If you see additional configured fields in another profile, inspect the source of those settings before changing anything. A per-host or system-wide client configuration can change the user, proxy or identity. The demonstration deliberately uses an empty configuration and creates no files. Running it leaves the actual client profile and any known hosts records unchanged.
Distinguish an open shell, a running remote command and the EC2 lifecycle
Mauli's training notes say “connected,” but the next learner sees a local prompt. A successful SSH login creates a remote session that can run commands under a guest identity. Closing the client ends that session. It does not make the EC2 instance stop. A command that runs in the foreground can behave differently when its session ends from a service supervised by the remote operating system. In an introductory lesson, use simple read-only commands that complete and leave the system as it was.
If you see a command apparently waiting, first identify the shell and what it is waiting for. It could be an SSH host key confirmation, a request for an authorized credential, or a program running after login. Treat those differently. A prompt before login belongs to the client or access system. A program running in the guest may be waiting for input or a file. Confirm the exact stage rather than interrupting or restarting the instance to escape a prompt.
At the end of a training check the sequence is straightforward. Confirm the last remote command's result, type exit to close the guest shell, and identify the local prompt again. If a managed session service provides its own close action, use the account's standard session procedure. Then verify whether the lab instance should continue running. A shared instance may belong to the next student. A temporary instance you created may need an approved cleanup action and a check on retained resources. Session evidence and compute billing answer different questions.
Practice selecting the access method and first useful observation
Draw a training laptop, its approved private connection and one EC2 Linux instance. Label where it sends SSH traffic, which policy permits the connection and how it checks the host key. Add the guest username and user credential as separate labels. The diagram should explain why a trusted host can reject an unauthorized user.
One student used the class's old public IP after an EC2 stop and start. Their client timed out. Make a two-column worksheet for current address and intended access path, then state where you confirm each. A successful plan does not assume a different security group until the actual endpoint is known.
A private instance was intended for Session Manager and does not appear as available. List the authorized checks you would ask its owner to perform. Include agent, permissions and service connectivity and describe the expected result for each. Opening public SSH has a different purpose and would not itself satisfy these prerequisites.
A user gets a host key warning after a scheduled replacement. Write the verified information they need before accepting a new key. Include the old target and new instance identity, expected hostname or current address, known change timing and a trusted fingerprint source. The user should not discard a saved key merely to hide the warning.
Interview questions and worked answers
What makes an SSH connection timeout different from a public-key refusal?
A timeout points to a connection or negotiation step that did not receive the needed response. Inspect the selected host and path. A public-key refusal means the reached SSH service reached its authentication decision for the user credentials. Inspect the account and key rather than widening a route.
How does a host key differ from a user key?
The host key helps the SSH client verify the server. The user key lets a client prove it controls an authorized identity. Match the host fingerprint to a trusted record and use the approved private key only for the intended login. One key cannot stand in for the other.
Can an EC2 instance without a public IP accept an authorized connection?
Yes, a properly configured private SSH path, an EC2 Instance Connect Endpoint, or a managed session can provide access under its own prerequisites. Confirm the network and identity needed for the selected method. Absence of a direct public address alone does not determine usability.
Why can Session Manager be unavailable even with a correct instance ID?
The instance needs to register under its supported management setup and reach the applicable Systems Manager services. The operator also needs authority to initiate the session. Check guest agent, instance permissions, network path and actual error for that account.
Why check both hostname and operating system after login?
They help confirm which guest shell received the command and whether the actual image matches expectations. A local command or another instance with the same Name tag can produce different results. Use these observations together with the approved instance ID and access record.
Check which layer you would inspect first
SSH reports
Permission denied (publickey). What should you inspect? A. Guest username and intended key. B. The instance's display-name color. C. Only the default subnet's internet gateway.Show answer
A. The error comes from public-key authentication with a reached SSH service. Check the intended account, offered key and server's permitted keys. A connectivity problem should be inspected separately if evidence shows one.
A saved SSH host key unexpectedly changes. What follows? A. Disable all host checks. B. Pause and verify the host and expected fingerprint through an approved source. C. Share the private key to compare it.
Show answer
B. The changed key might be a legitimate rebuild or a different endpoint. Verify the resource and trusted current fingerprint before altering the saved record. Your user private key is unrelated to this verification.
What can a private managed-session design avoid? A. All permissions. B. Any required network access to the Systems Manager service. C. A public inbound TCP 22 path for Session Manager itself.
Show answer
C. Session Manager uses the configured agent, service communication and approved operator permissions. It does not need public inbound SSH for the ordinary managed session workflow. Those other prerequisites still apply.
The client Key file was correct yesterday and the guest account changed today. What should you verify? A. Whether the current approved user accepts the key. B. Whether a nonrelated account name works. C. Whether a second public port can replace the credential.
Show answer
A. Guest configuration can change after launch. Verify the actual approved user and credential with the owner. A route or open port cannot authorize the user under different account settings.
Which tells you that
cat /etc/os-releaseran remotely? A. The file path begins with slash. B. The command was run in the verified guest session and output matches expected surroundings. C. The command happens to be printed in a tutorial.Show answer
B. The same command can be run locally or on several guests. Confirm your current session and resource identity. The path alone does not tell where the data was read.
Revision cards
- Local and remote
- Identify where the command is running. Verify the approved instance, guest account and operating system.
- Three SSH checks
- Reach the transport listener, verify the host key, then authenticate as the intended guest user.
- Identity protection
- Keep the private key private and protect its local copy. A host fingerprint represents a different key.
- Managed access
- Choose the approved method and verify its own agent, IAM, path and guest prerequisites.
- Error phase
- A timeout, host identity warning and public-key rejection give different evidence about the failing step.
- Finish the session
- Exit the guest shell and record the check. Compute and its associated resources have separate lifecycles.
References
- AWS Linux instance connection prerequisites
- Connect to a Linux EC2 instance using SSH
- EC2 Instance Connect options
- Connect through an EC2 Instance Connect Endpoint
- Troubleshoot EC2 connection errors
- EC2 key pair behavior
- AWS guidance on lost Linux instance keys
- EC2 metadata configuration precedence and settings
- Systems Manager Session Manager prerequisites
- OpenSSH command manual
- OpenSSH client configuration
- OpenSSH key generation and fingerprint commands
- Microsoft OpenSSH client availability and setup
- Microsoft PowerShell Get-Acl reference
- PuTTY and PuTTYgen documentation and release