How do I troubleshoot "Connection refused" or "Connection timed out" errors when I use SSH to connect to my EC2 instance?

7 minute read
2

I receive "Connection refused" or "Connection timed out" errors when I use SSH to connect to my Amazon Elastic Compute Cloud (Amazon EC2) instance.

Short description

If your connection times out, then you receive the following error message from the SSH client:

"ssh: connect to host ec2-X-X-X-X.compute-1.amazonaws.com port 22: Connection timed out"

The Connection timed out error occurs when the server doesn't respond to the client and the client program gives up (times out).

If a host remotely refuses your connection, then you receive the following error message:

"ssh: connect to host ec2-X-X-X-X.compute-1.amazonaws.com port 22: Connection refused"

Resolution

"Connection timed out" error

If you receive the Connection timed out error, then verify the following configurations:

Note: To check for issues with the firewall or TCP Wrappers, you must have operating system (OS) access to the instance.

"Connection refused" error

If you receive the Connection refused error, then verify the following configurations:

  • There isn't a firewall on the instance that blocks the SSH connection.
  • The SSH daemon (sshd) is running and listening on port 22.

Note: To check the preceding configurations, you must have OS-level access to the instance.

Troubleshoot issues with instances that pass both health checks

To troubleshoot issues with instances that pass their health checks, use one of the following troubleshooting methods.

Run the AWSSupport-TroubleshootSSH runbook

It's a best practice to run the AWSSupport-TroubleshootSSH automation runbook. The runbook installs the Amazon EC2Rescue tool on your instance to identify and fix issues that block a remote SSH connection to a Linux host.

Use the EC2 Serial Console for Linux

Use the EC2 Serial Console for Linux to troubleshoot OS-level issues such as boot issues, network configuration issues, and SSH configuration issues on supported instance types.

Prerequisites:

  • Grant access to the console at the AWS account level.
  • Create AWS Identity and Access Management (IAM) policies that grant console access to your IAM users.
    Note: Each instance that uses the EC2 Serial Console must have at least one password-based Linux user with sudo access.

For more information, see Configure access to the EC2 Serial Console.

If there isn't a Linux account with a login password configured, then you must run ssm-user to reset the password for an account with sudo access.

To verify that your configuration isn't blocking SSH access, complete the following steps:

  1. Use the EC2 Serial Console to connect to the EC2 instance as a password-configured Linux user.

  2. If you configured iptables rules, then run the following command to add a rule in iptables that accepts all SSH connections on port 22:

    sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
  3. If you use an OS-based firewall, then deactivate it. It's a best practice to use security groups instead of a firewall. To deactivate your OS-based firewall, run the following commands based on your OS.
    Important: The following commands clear all main iptables rules and delete existing rules. The commands also add a rule that allows inbound SSH connections, and change the default policy of the main chain to ACCEPT. This configuration makes sure that you don't affect the instance network connectivity when you clear the iptables rule.
    Distributions that use UFW such as Ubuntu and Debian:

    sudo iptables -F$ sudo iptables -P INPUT ACCEPT
    sudo ufw disable

    Distributions that use firewalld such as Red Hat Enterprise Linux (RHEL) and CentOS:

    sudo iptables -F $ sudo iptables -P INPUT ACCEPT
    sudo systemctl disable firewalld

    Note: After you regain access to your instance, check your firewall configuration.

  4. To verify that SSH is running and that SSH TCP port 22 is in the listening state, run the following command:

    sudo systemctl restart sshd$ sudo ss -tpln | grep -iE '22|ssh'LISTEN 0 128 *:22 *:* users:(("sshd",pid=1901,fd=3))
    LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=1901,fd=4))

    Note: If your system doesn't have the ss command, then replace ss with the legacy netstat command. Make sure to use the same syntax as the preceding command.

  5. To make sure that the TCP Wrapper doesn't block an SSH connection, run the following command:

    if [[ $( cat /etc/hosts.[ad]* | grep -vE '^#' | awk 'NF' | wc -l) -ne 0 ]];\
    then sudo sed -i '1i sshd2 sshd : ALL: allow' /etc/hosts.allow; fi
  6. Use SSH to connect to the instance.

  7. Disconnect from the EC2 Serial Console session.

Use Systems Manager

Prerequisites: To use Session Manager, a capability of AWS Systems Manager, your instance must be a managed node. The instance's AWS Systems Manager Agent (SSM Agent) ping status must be Online, and the attached IAM role must have AmazonSSMManagedInstanceCore permissions. Make sure that you adhere to all Session Manager prerequisites.

Use Session Manager to start a session to access the instance.

Use a user data script

If you can't use the preceding troubleshooting methods, then use a user data script to deactivate the OS-level firewall and the TCP Wrapper. Then, restart the sshd service.

Important: Before you stop and start your instance, take the following actions:

Note: When you stop and start an instance, the instance's public IP address changes. It's a best practice to use an Elastic IP address to route external traffic to your instance instead of a public IP address.

To configure user data for the instance, complete the following steps:

  1. Open the Amazon EC2 console.
  2. From the navigation pane, choose Instances, and then select your instance.
  3. Stop the instance.
  4. Choose Actions, then choose Instance settings.
  5. Choose Edit user data, and then enter the following user data script:
    Content-Type: multipart/mixed; boundary="//"MIME-Version: 1.0
     
    --//
    Content-Type: text/cloud-config; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename="cloud-config.txt"
     
    #cloud-config
    cloud_final_modules:
    - [scripts-user, always]
     
    --//
    Content-Type:
        text/x-shellscript; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename="userdata.txt"
     
    #!/bin/bash
    iptables -P INPUT ACCEPT
    iptables -F
    systemctl restart sshd.service || service sshd restart
    if [[ $( cat /etc/hosts.[ad]* | grep -vE '^#' | awk 'NF' | wc -l) -ne 0 ]];\
    then sudo sed -i '1i sshd2 sshd : ALL: allow' /etc/hosts.allow; fi
    --//
    Note: The preceding user data script is set to run on each instance reboot. This method removes all main iptables rules.
  6. Choose Save.
  7. Use SSH to connect to the instance.
  8. After you regain access to the instance, remove the user data script, and then verify that your firewall configuration is accurate.

Related information

Error connecting to your instance: Connection timed out

How do I troubleshoot Amazon EC2 instance connection timeout errors from the internet?

How can I troubleshoot connecting to my Amazon EC2 Linux instance using SSH?

Why is my EC2 Linux instance unreachable and failing its status checks?

5 Comments

Check if kes are in SHA-1 or some warrants - if yes then try "update? change keys to RSA . The another advice is if you user PUTTY for SSH connection, followed steps are recommended:

  • backup all keys (and on your decision PUTTY confit)
  • install (update )putty to the latest stable version
  • try to connect, in case of no change disable/enable compression and check connection

Trying to lower key file access privileges may also help mostly if not only you are only user of one stem account.

In my opinion upgrading keys to the latest standard (avoiding MD5 fingerprinting) or changing them to latest version will help. If this is new instance and you can't connect - verify Security Groups for PORT 22 - if port is open limit it to accept only your IP and try to connect. Soft restart of instance may be some solution in scenarios of resources problem.

Not elegant way that helps (USE IT ONLY AT INSTANCES WITHOUT CRITICAL/LIVE SERVICES to avoid data loss, USE OF IT IS JUST EXAMPLE based on own experience where asap action was needed and this fast way helped , in my case it was data breach - it was on ARM IoT device without chance to physical access over the same day) sio "hard reset" allowed our learning emploee diagnoze data breach and secure device with redirect pockets for analyse. On AWS use this only as I advised - DO NOT USE or USE at very last choice ;)

replied 2 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
EXPERT
replied 2 years ago

I was experiencing this same error message "Connection Timed Out", when I tried to SSH using the SSH Client, at that moment my security group was only permitting inbound traffic via SSH from my local IP, but when I reconfigured it to allow SSH traffic from anywhere (0.0.0.0), the error message cleared and I was able to successfully SSH into the Amazon Linux 2 instance.

I had to use this type of security group configuration, because this was a testing environment, so in a production environment, how does one resolve this error message when using a local IP from my computer?

Thanks

replied 2 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
EXPERT
replied 2 years ago

Here is the official resolution video from AWS. Please check it out.

How do I fix Connection refused or Connection timed out errors when connecting to an EC2 instance? https://www.youtube.com/watch?v=b1K0CNYxtC0

profile picture
replied a year ago