I am new to AWS and I have created a new Windows EC2 instance. I see ways to SSH to different instances like Amazon Linux, Ubuntu using PuTTY. But not for Windows instance. Can we not connect to Windows instance using PuTTY? Any help would be appreciated. Thanks.
You can SSH to Linux and Mac instance on AWS. You can use Remote Desktop (RDP) to access Windows Instances.
Suppose you wanted to SSH into a Windows instance, then you would have to install OpenSSH. Which would still require access to the Windows instance.
AWS offers a few ways to access your Windows instance, one of them is AWS Systems Manager Session Manager (SSM). You would need to enable RDP through SSM. You can find out how to do this via this workshop. Alternatively configure SSM to run powershell commands against the instance Note the instance must have a role that has IAM access to SSM. If the instance is in a private VPC it would require access to SSM via endpoints.
If your instances is in a public subnet, and has a public IP address then you can easily connect to your Windows instance using RDP. Note just like your EC2 Instances running Linux, the security group must allow access. In this case it must be to RDP (3389) and not SSH (Port 22). You can read more about the prerequisites here.
When you created your Windows EC2 instance, you were asked to create a key. You can use this key to get the Windows password, assuming you used an AWS AMI.
Access your password
Follow these steps (From the documentation here):
Open the Amazon EC2 console, and then choose Instances.
Select the check box for the instance, and then expand the Actions dropdown list. If you're using the old console, then choose Get Windows Password. If you're using the new console, choose Security, and then choose Get Windows Password.
Note: It can take a few minutes for this option to be available after you first launch a new instance.
Choose Browse, select your key pair file, and then choose Open.
-or-
Paste the contents of your key pair into the text box.
Choose Decrypt Password.
Connect to the Instance
On the password screen, Choose Download remote desktop file. Your browser prompts you to either open or save the RDP shortcut file. Select the option to save the file. When you have finished downloading the file, choose Cancel to return to the Instances page.
Navigate to your downloads directory and open the RDP shortcut file.
You might get a warning that the publisher of the remote connection is unknown. Choose Connect to continue to connect to your instance.
The administrator account is chosen by default. Copy and paste the password that you saved previously.
You can also use EC2 Serial Console to access an EC2 instance running Windows, this is great to debug boot issues.
Due to the nature of self-signed certificates, you might get a warning that the security certificate could not be authenticated. Use the following steps to verify the identity of the remote computer, or simply choose Yes (Windows) or Continue (Mac OS X) if you trust the certificate.
For more details on how to connect, visit this site.
Can we SSH to Windows EC2 instance in AWS? - NO.
Windows EC2 you can connect using RDP( Remote Desktop ). You can download .rdp file from AWS console navigating through select instance -> connect -> RDP
SSH connection is for Linux based EC2 machine.
Late here but the answer is Yes you can SSH into a Windows EC2 instance from Windows/Linux and Mac(haven't tried). The upshot is that you need an SSH server in order to receive ssh requests from clients.
Make sure your Windows instance is running
RDP into the instance (one-time only)
Type powershell in command line to toggle out of cmd
Run the following command to determine if you have OpenSSH.Server installed
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
Install the service
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
After a minute or two it installs (be patient)
Set service to start service automatically in case you stop instance
Set-Service -Name sshd -StartupType 'Automatic'
Run the OpenSSH.Server service, called sshd
Start-Service sshd
Exit the instance shell and RDP session
Go back to your shell on your computer
Run your customary ssh command to get into the EC2 instance. You'll be prompted for a password. There are ways to get around that.
Yes, recent releases of Windows (10 build 1809, Server 2019, and later) offer official support for a native OpenSSH daemon. See https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=powershell for details about OpenSSH on Windows.
When wanting to use SSH to connect to an EC2 instance specifically, I have found that the easiest approach is to build a new AMI with the OpenSSH package preinstalled and the relevant services preconfigured. The full process that is currently working for me:
Build a Windows AMI based on Server 2019 or later (e.g. use Windows_Server-2019-English-Full-ECS_Optimized-2022.12.14 as the base AMI). As part of that AMI:
Install OpenSSH and configure the sshd and ssh-agent services as described in the above link:
$ErrorActionPreference = 'Stop'
Write-Host 'Installing and starting sshd'
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Set-Service -Name sshd -StartupType Automatic
Start-Service sshd
Write-Host 'Installing and starting ssh-agent'
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent
Write-Host 'Set PowerShell as the default SSH shell'
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value (Get-Command powershell.exe).Path -PropertyType String -Force
Configure PowerShell as the default SSH shell:
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value (Get-Command powershell.exe).Path -PropertyType String -Force
Launch an EC2 instance using the new AMI:
Provide a valid, existing SSH keypair.
Select IMDSv2.
Provide the following PowerShell script as the userdata script. This script will ensure the SSH keypair specified when launching will be added to the the Administrator user's authorized keys file. Note that the <powershell> and </powershell> tags are part of the userdata; they are parsed and extracted by AWS prior to the script being executed.
<powershell>
# Userdata script to enable SSH access as user Administrator via SSH keypair.
# This assumes that
# 1. the SSH service (sshd) has already been installed, configured, and started during AMI creation;
# 2. a valid SSH key is selected when the EC2 instance is being launched; and
# 3. IMDSv2 is selected when launching the EC2 instance.
# Save the private key from instance metadata.
$ImdsToken = (Invoke-WebRequest -Uri 'http://169.254.169.254/latest/api/token' -Method 'PUT' -Headers #{'X-aws-ec2-metadata-token-ttl-seconds' = 2160} -UseBasicParsing).Content
$ImdsHeaders = #{'X-aws-ec2-metadata-token' = $ImdsToken}
$AuthorizedKey = (Invoke-WebRequest -Uri 'http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key' -Headers $ImdsHeaders -UseBasicParsing).Content
$AuthorizedKeysPath = 'C:\ProgramData\ssh\administrators_authorized_keys'
New-Item -Path $AuthorizedKeysPath -ItemType File -Value $AuthorizedKey -Force
# Set appropriate permissions on administrators_authorized_keys by copying them from an existing key.
Get-ACL C:\ProgramData\ssh\ssh_host_dsa_key | Set-ACL $AuthorizedKeysPath
# Ensure the SSH agent pulls in the new key.
Set-Service -Name ssh-agent -StartupType "Automatic"
Restart-Service -Name ssh-agent
</powershell>
Connect to the instance via SSH like normal. Provide the SSH keypair you specified when launching and user Administrator. For example:
ssh -i ~/.ssh/my-keypair Administrator#my.ec2.instance
PuTTy is not the tool to use typically for Windows machines. While I'm sure it is possible to setup SSH access for Windows machines, the methods below are more typical and easier to setup.
If you have a keypair associated to your EC2 instance, you can use the AWS console to show you the username and password needed to use Windows Remote Desktop to access your machine by giving it your pem file. This will also require you to enable inbound RDP access (a different port than SSH) in your security group.
If you just want PowerShell access and you are using an instance with with the SSM agent installed (e.g. Amazon Linux AMIs) and a role with the required SSM permissions, you can use Session Manager to connect. This does not need a keypair or direct network access to your machine so this is a more secure method but requires a bit more setup.
Both techniques are described is more detail in the reference below.
References:
https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html
You can connect to your Windows EC2 via AWS Session Manager. It let you to manage your instance from browser based shell. Like SSH, you can manage your EC2 from the shell provided by the SSM. You can execute power shell commands from the console.
To use SSM, first you need to install ssm agent in instance and grant EC2 with required SSM policies in IAM role.
I believe SSM agent is by default installed in Windows EC2 instances. Also AWS providing one role named AmazonSSMRoleForInstancesQuickSetup for EC2. You can use the same or utilise the policies inside this role.
To connect: Select the instance and in the Connect option select Session manager
Related
I'm trying to set up remote access (with VSCode) to the GCP VM that's setup with Notebooks AI. However, when I ssh into the VM I don't have write permissions for /home/jupyter so cannot edit any of the notebook files.
I have tried both gcloud compute ssh and setting up local aliases with gcloud compute config-ssh.
My best guess is that the users are different. It looks like the terminal on JupyterLab is logged in as jupyter#[instance...] while when I ssh in its myname#[instance...]. Checking permissions of /home/jupyter/, it's owned by user jupyter of group jupyter. I also tried adding users to the jupyter group with sudo usermod -a -G but that didn't do the trick. When I try to ssh in as jupyter#[instance...] from anywhere else I get permission denied (public key).
I can edit files once logged in if I use sudo vim ..., but that won't help for VS code.
EDIT: a partial solution is to open up permissions using sudo chmod 777 /home/jupyter/*. However, that's probably a hackish, unsafe way to do it. Moreover, it only works on existing files -- new files will still only be writable by whichever user created them.
To SSH into the notebook instance as the “jupyter” user, an SSH key should be generated for that user and be added to the notebook VM instance. Also, please make sure that the notebook instance VM has the appropriate firewall rule to allow the SSH connection. The following are the steps that would create an SSH connection to the “jupyter” user which has the write permissions.
Run the following commands on the local machine to generate the required SSH key:
ssh-keygen -t rsa -f ~/.ssh/jupyter-ssh-key -C jupyter
“jupyter-ssh-key” → Name of the pair of public and private keys (Public key: jupyter-ssh-key.pub, Private key: jupyter-ssh-key)
“jupyter” → User in the VM that we are trying to connect to
chmod 400 ~/.ssh/jupyter-ssh-key
In the Compute Engine console, edit the VM settings to add the contents of the generated SSH public key. Detailed instructions can be found here.
Initiate the SSH connection from the local machine to the notebook VM:
ssh -i ~/.ssh/jupyter-ssh-key jupyter#<external-ip-of-notebook-vm-instance>
If the SSH connection succeeds, the same can be followed in VSCode.
In VSCode, select the “Remote-SSH: Connect to Host” option from the command palette. Enter the above ssh -i command to add the notebook VM instance as a recognized host. A new VSCode window will appear where we have been logged in as the “jupyter” user.
I'm creating a new VM instance. I've clean all the meta data. Then I'm running the following command in the cloud shell:
gcloud beta compute ssh --zone "europe-west2-c" "vmname" --project "myprojectname"
then I've been asking to enter a passphrase (which I don't know). I press enter until I get the following error Permission denied (publickey) error
I've delete and recreated my instance multiple time but I always have the same error. What should I do?
Troubleshooting Steps:
Logon using UI ssh. This creates an ephemeral ssh key, Google Agent also executes the codepath to refresh .ssh/authorized_keys and address any invalid dir/file permissions for both .ssh/ and .ssh/authorized_keys. This approach will address common gcloud compute ssh issues that relates to corrupted keys, missing dir/file or invalid dir/file permission. Try the gcloud again after performing the UI ssh.
Make sure that account has authenticated to gcloud as an IAM user with the compute instance admin role; for example, run gcloud auth revoke --all, gcloud auth login [IAM-USER] then try gcloud compute ssh again.
Verify that persistent SSH Keys metadata for gcloud is set for either the project or instance. Look in Compute Engine > Metadata, then click SSH Keys. Persistent keys do not have the expireOn attribute.
It's possible the account has lost the private key, mismatched a keypair, etc. You can force gcloud to generate a new SSH keypair by doing the following:
Move ~/.ssh/google_compute_engine and ~/.ssh/google_compute_engine.pub if present.
For example:
mv ~/.ssh/google_compute_engine.pub ~/.ssh/google_compute_engine.pub.old
mv ~/.ssh/google_compute_engine ~/.ssh/google_compute_engine.old
Try gcloud compute ssh [INSTANCE-NAME] again. A new keypair will be created and the public key will be added to the SSH keys metadata.
Verify that the Linux Google Agent scripts are installed, up-to-date, and running. See Determining Google Agent Status. If the Linux Google Agent is not installed, re-install it. See guest-environment.
Verify account home owner/permission is correct. Make sure that account home directory has the correct ownership and is not globally writable. If not using os-login (which is default), your's .ssh folder must have mode 0700, .ssh/authorized_keys file must have mode 0600. Review /var/log/auth.log for any errors.
Commands:
sudo chmod 700 /home/[user-id]/.ssh
sudo chmod 600 /home/[user-id]/.ssh/authorized_keys
If os-login is enabled and the Virtual Machine instance is using a service account (default). Add the following roles to the account.
roles/compute.osLogin
roles/iam.serviceAccountUser
For more information troubleshooting SSH.
The possible causes for a Permission denied (publickey) error are:
Your key expired and Compute Engine deleted your
~/.ssh/authorized_keys file.
You used an SSH key stored in metadata to connect to a VM that has
OS Login enabled.
You used an SSH key stored in an OS Login profile to connect to a VM
that doesn't have OS Login enabled.
You connected using a third-party tool and your SSH command is
misconfigured.
The sshd daemon isn't running or isn't configured properly.
You can find more information on how to troubleshoot SSH key errors in this link
I have the same issue sometimes . Cause and solution according to GCP troubleshooting link is:
Your key expired and Compute Engine deleted your
~/.ssh/authorized_keys file. If you manually added SSH keys to your VM
and then connected to your VM using the Google Cloud Console, Compute
Engine created a new key pair for your connection. After the new key
pair expired, Compute Engine deleted your ~/.ssh/authorized_keys file
in the VM, which included your manually added SSH key.
To resolve this issue, try one of the following:
Connect to your VM using the Google Cloud Console or the gcloud
command-line tool. Re-add your SSH key to metadata. For more information, see Add SSH keys to VMs that use metadata-based SSH keys.
I use terraform so in this case I instructed the workflow to destroy the VM and rebuild it.
To fix this issue when you cannot start ssh:
Edit VM and enable Serial port
Start serial console
Edit ~/.ssh/authorized_keys
On your desktop/client,
edit /Users/[yourdesktopuser]/.ssh/id_rsa.pub
copy contents to clipboard
Paste this content to the end of authorized_keys file in the VM serial console
Save and close
This will then recognize the public key from your desktop
I'm having some problems using SSH to get into my running AWS EC2 instance. According to the instructions, I need to create a Key Pair, which downloads a .pem private key file, which I have named QARTH.pem. From the directory where this file has been saved, I'm supposed to execute command:
ssh -i "QARTH.pem" ubuntu#ec2-XX-XX-XX-XXX.us-west-2.compute.amazon.com
However, I get the error:
Permission denied (publickey).
I'm using the auto-generated launch-wizard security group, which allows port 22 incoming access to all IPs.
I've also used the example procedure to convert the .pem file to a PuTTy private key .ppk file, and used the PuTTy client. I get the same error.
This seems like a pretty straightforward procedure, so I don't know what I could be doing wrong. If you have any ideas, I'd love to hear them. However, I'm not strong in network security, so please make responses lay-person friendly.
You are either using the wrong key pair (QARTH.pem), the wrong username, connecting to the wrong system or QARTH.pem is not set to be read-only.
STEP 1: Add debugging options to ssh to help determine what is wrong:
ssh -v -i QARTH.pem ubuntu#ec2-XX-XX-XX-XXX.us-west-2.compute.amazon.com
STEP 2: Make sure that the key pair file is read-only.
LINUX:
To make the key pair file read-only execute this command: chmod 400 QARTH.pem while in the same directory as the file.
WINDOWS:
Commands to run on a Windows system (as administrator) to make a key pair read-only and satisfy ssh:
Note replace %USERNAME% with your user name.
REM Disable inheritance on QARTH.pem
icacls QARTH.pem /inheritance:d
REM Delete "NT AUTHORITY\Authenticated Users" from having any rights
icacls QARTH.pem /remove "NT AUTHORITY\Authenticated Users"
REM Delete "BUILTIN\Users" from having any rights
icacls QARTH.pem /remove "BUILTIN\Users"
REM Grant Read-Only rights to me
icacls QARTH.pem /GRANT:R "%USERNAME%:(R)"
STEP 3: Make sure that you are using the correct username for the EC2 AMI:
Usernames for popular EC2 AMIs:
For Amazon Linux 2 or the Amazon Linux AMI, the user name is ec2-user.
For a Centos AMI, the user name is centos.
For a Debian AMI, the user name is admin or root.
For a Fedora AMI, the user name is ec2-user or fedora.
For a RHEL AMI, the user name is ec2-user or root.
For a SUSE AMI, the user name is ec2-user or root.
For an Ubuntu AMI, the user name is ubuntu.
Otherwise, if ec2-user and root don't work, check with the AMI provider.
TL;DR
Try using the manually generated SSH key pair via AWS Console
Well, colleagues, I have NO IDEA WHY exactly (no idea YET), but when I generate the keys with a CLI command, the SSH connectivity does NOT WORK:
aws --region us-east-1 ec2 create-key-pair --key-name "KeyPair"
BUT, when I am creating the SSH key pai manually using the AWS Console it works perfectly fine:
1. Go to AWS Console
2. EC2 :: Network & Security (in left menu) :: Key Pairs :: Create Key Pair
3. <As soon as I am specifying the name of a key pair Amazon downloads the keys into a default download directory>
4. chmod 400 KeyPair.pem
5. ssh -i ./SSHKeys.pem ec2-user#ec2-54-162-166-40.compute-1.amazonaws.com
6. ENJOY!
P.S. I am pretty sure I have messed up something during the response copy-paste from a CLI ¯\_(ツ)_/¯
I have been using the GCP console to connect to a cloud instance and want to switch to using SSH through powershell as that seems to maintain a longer persistence. Transferring my public key through cloud shell into authorized_key file seems to be temporary since once cloud shell disconnects, the file doesn't persist. I've tried using os-login but that generates a completely different user from what I've been using through cloud shell (Cloud shell creates a user: myname while gcloud creates a user: myname_domain_com. Is there a way to continue using the same profile created by cloud shell when logging in through gcloud. I am using the same email and account in both the console and gcloud myname#domain.com. The alternative is to start all over from gcloud and that would be a pain.
If you want to SSH to different instances of a google cloud project (from a mac or Linux), do the following:
Step 1. Install SSH keys without password
Use the following command to generate the keys on your mac
ssh-keygen -t rsa -f ~/.ssh/ -C
For example private-key-name can be bpa-ssh-key. It will create two files with the following names in the ~/.ssh directory
bpa-ssh-key
bpa-ssh-key.pub
Step 2. Update the public key on your GCP project
Goto Google Cloud Console, choose your project, then
VMInstances->Metadata->SSH Keys->Edit->Add Item
Cut and paste the contents of the bpa-ssh-key.pub (from your mac) here and then save
Reset the VM Instance if it is running
Step 3. Edit config file under ~/.ssh on your mac Edit the ~/.ssh/config to add the following lines if not present already
Host *
PubKeyAuthentication yes
IdentityFile ~/.ssh/bpa-ssh-key
Step 4. SSHing to GCP Instance
ssh username#gcloud-externalip
It should create a SSH shell without asking for the password (since you have created the RSA/SSH keys without a password) on the gcloud instance.
Since Metadata is common across all instances under the same project, you can seam-lessly SSH into any of the instances by choosing the respective External IP of the gcloud instance.
guys.
GCP offers multiple ways of ssh-ing in gcloud, cloud shell, and local machine cloud SDK.
While all these options are great and I have been using them, I normally prefer using .ssh/config to shorten the process of logging in to machines.
For an example, for EC2, you just add:
Host $name
HostName $hostname
User $username
IdentityFile $pathtoFile
Is there any way to replicate this for GCP VMs?
Thanks
According to This Doc
If you have already connected to an instance through the gcloud tool, your keys are already generated and applied to your project or instance. The key files are available in the following locations:
Linux and macOS
Public key: $HOME/.ssh/google_compute_engine.pub
Private key: $HOME/.ssh/google_compute_engine
Windows
Public key: C:\Users[USERNAME].ssh\google_compute_engine.pub
Private key: C:\Users[USERNAME].ssh\google_compute_engine
You can use the key with typical -i or in .ssh/config config file.
Or simply do
ssh-add ~/.ssh/google_compute_engine
to add the identity to your ssh agent.
PS> I've seen people create an alias for the ssh command, something like
alias gce='gcloud compute ssh'
If you want to SSH to different instances of a google cloud project (from a mac or Linux), do the following:
Step 1. Install SSH keys without password
Use the following command to generate the keys on your mac
ssh-keygen -t rsa -f ~/.ssh/<private-key-name> -C <your gcloud username>
For example private-key-name can be bpa-ssh-key. It will create two files with the
following names in the ~/.ssh directory
bpa-ssh-key
bpa-ssh-key.pub
Step 2. Update the public key on your GCP project
Goto Google Cloud Console, choose your project, then
VMInstances->Metadata->SSH Keys->Edit->Add Item
Cut and paste the contents of the bpa-ssh-key.pub (from your mac) here and then save
Reset the VM Instance if it is running
Step 3. Edit config file under ~/.ssh on your mac
Edit the ~/.ssh/config to add the following lines if not present already
Host *
PubKeyAuthentication yes
IdentityFile ~/.ssh/bpa-ssh-key
Step 4. SSHing to GCP Instance
ssh username#gcloud-externalip
It should create a SSH shell without asking for the password (since you have created the RSA/SSH keys without a password) on the gcloud instance.
Since Metadata is common across all instances under the same project, you can seam-lessly SSH into any of the instances by choosing the respective External IP of the gcloud instance.