Ошибка ssh connection timed out

I am trying to connect to remote server via ssh but getting connection timeout.

I ran the following command

ssh testkamer@test.dommainname.com

and getting following result

ssh: connect to host testkamer@test.dommainname.com port 22: Connection timed out

but if try to connect on another remote server then I can login successfully.

So I think there is no problem in ssh and other person try to login with same login and password he can successfully login to server.

Please help me
Thanks.

Manish Shrivastava's user avatar

asked Aug 29, 2012 at 6:41

urjit on rails's user avatar

urjit on railsurjit on rails

1,7534 gold badges18 silver badges36 bronze badges

3

Here are a couple of things that could be preventing you from connecting to your Linode instance:

  1. DNS problem: if the computer that you’re using to connect to your
    remote server isn’t resolving test.kameronderdehamer.nl properly
    then you won’t be able to reach your host. Try to connect using the
    public IP address assigned to your Linode and see if it works (e.g.
    ssh user@123.123.123.123). If you can connect using the public IP
    but not using the hostname that would confirm that you’re having
    some problem with domain name resolution.

  2. Network issues: there
    might be some network issues preventing you from establishing a
    connection to your server. For example, there may be a misconfigured
    router in the path between you and your host, or you may be
    experiencing packet loss. While this is not frequent, it has
    happenned to me several times with Linode and can be very annoying.
    It could be a good idea to check this just in case. You can have a look
    at Diagnosing network issues with MTR (from the Linode
    library).

answered Sep 3, 2012 at 21:46

mfriedman's user avatar

1

That error message means the server to which you are connecting does not reply to SSH connection attempts on port 22. There are three possible reasons for that:

  1. You’re not running an SSH server on the machine. You’ll need to install it to be able to ssh to it.

  2. You are running an SSH server on that machine, but on a different port. You need to figure out on which port it is running; say it’s on port 1234, you then run ssh -p 1234 hostname.

  3. You are running an SSH server on that machine, and it does use the port on which you are trying to connect, but the machine has a firewall that does not allow you to connect to it. You’ll need to figure out how to change the firewall, or maybe you need to ssh from a different host to be allowed in.

EDIT: as (correctly) pointed out in the comments, the third is certainly the case; the other two would result in the server sending a TCP «reset» package back upon the client’s connection attempt, resulting in a «connection refused» error message, rather than the timeout you’re getting. The other two might also be the case, but you need to fix the third first before you can move on.

Ayxan Haqverdili's user avatar

answered Mar 19, 2020 at 20:42

Akash S's user avatar

Akash SAkash S

1861 silver badge4 bronze badges

1

I got this error and found that I don’t have my SSH port (non standard number) whitelisted in config server firewall.

Victor2748's user avatar

Victor2748

4,14913 gold badges52 silver badges89 bronze badges

answered Nov 13, 2014 at 0:08

16851556's user avatar

1685155616851556

2393 silver badges11 bronze badges

Just adding this here because it worked for me. Without changing any settings (to my knowledge), I was no longer able to access my AWS EC2 instance with: ssh -i /path/to/key/key_name.pem admin@ecx-x-x-xxx-xx.eu-west-2.compute.amazonaws.com

It turned out I needed to add a rule for inbound SSH traffic, as explained here by AWS. For Port range 22, I added 0.0.0.0/0, which allows all IPv4 addresses to access the instance using SSH.

Note that making the instance accessible to all IPv4 addresses is a security risk; it is acceptable for a short time in a test environment, but you’ll likely need a longer term solution.

answered Nov 22, 2021 at 7:58

arranjdavis's user avatar

arranjdavisarranjdavis

6498 silver badges16 bronze badges

If you are on Public Network, Firewall will block all incoming connections by default. check your firewall settings or use private network to SSL

answered Oct 22, 2018 at 12:36

Shishay Ghebrehiwet's user avatar

This happens because of firewall connection.
Reset your firewall connection from your hosting website.

It will start working.

After connecting to the server again add this to your (ufw) security

sudo ufw allow 22/tcp

answered Nov 9, 2022 at 18:50

Furqan's user avatar

The possibility could be, the SSH might not be enabled on your server/system.

  1. Check sudo systemctl status ssh is Active or not.
  2. If it’s not active, try installing with the help of these commands

sudo apt update

sudo apt install openssh-server

Now try to access the server/system with following command

ssh username@ip_address

answered Jan 29, 2019 at 7:52

Gani's user avatar

GaniGani

4121 gold badge7 silver badges16 bronze badges

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file.
Try to increase the session timeout and see if it fails again

answered Oct 27, 2016 at 12:58

Biswanath Das's user avatar

My VPN connection was not enabled. I was trying all possible way to open up the Firwall and Ports until I realized, I am working from home and my VPN connection was down.
But yes, Firewall and ssh configurations can be a reason.

answered May 8, 2020 at 7:10

sg28's user avatar

sg28sg28

1,3639 silver badges19 bronze badges

Try connecting to a vpn, if possible. That was the reason I was facing problem.
Tip: if you’re using an ec2 machine, try rebooting it. This worked for me the other day :)

answered Jan 13, 2021 at 5:46

dhruv arora's user avatar

I had this issue while trying to ssh into a local nextcloud server from my Mac.

I had no issues ssh-ing in once, but if I tried to have more than one concurrent connection, it would hang until it timed out.

Note, I was sshing to my user@public-ip-address.

I realized the second connection only didn’t work when I tried to ssh into it when on the same network, ie my home network

Furthermore, when I tried ssh user@server-domain it worked!

The end fix was to use ssh user@server-domain rather than ssh user@public-ip

answered Mar 21, 2021 at 20:01

Jacob Waters's user avatar

Jacob WatersJacob Waters

2971 gold badge2 silver badges10 bronze badges

This may be very case specific and work in some cases only but
check to see if you were previously connecting through some VPN software/application.

Try connecting again to the VPN. Worked in my case.

answered Nov 11, 2021 at 9:49

Abhinav Dobhal's user avatar

I have experienced a couple of nasty issues that lead to these errors, and these are different from everyone else’s answer here:

  1. Wrong folder access rights. You need to have specific directory permissions on you ssh folders and files.
    a. The .ssh directory permissions should be 700 (drwx——).

    b. The public key (.pub file) should be 644 (-rw-r—r—).

    c. The private key (id_rsa) on the client host, and the authorized_keys file on the server, should be 600 (-rw——-).

  2. Nasty docker network configuration. This just happened to me on an AWS EC2 instance. It turned out that I had a docker network with an ip range that interfered with the ssh access granted by the security group and VPC. The docker network’s range was e.g. 192.168.176.0/20 (i.e. a range from 192.168.176.1->192.168.191.254), whereas the security group had a range of 192.168.179.0/24; interfering with the SSH access.

answered Mar 18, 2022 at 12:46

Andreas Forslöw's user avatar

I had this error when trying to SSH into my Raspberry pi from my MBP via bash terminal. My RPI was connected to the network via wifi/wlan0 and this IP had been changed upon restart by my routers DHCP.

Check IP being used to login via SSH is correct. Re-check IP of device being SSH’d into (in my case the RPI), which can be checked using hostname -I

Confirm/amend SSH login credentials on «guest» device (in my case the MBP) and it worked fine in my attempt.

answered Mar 28, 2020 at 20:34

Silicon Star's user avatar

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

answered Jul 3, 2020 at 8:32

Atul Patel's user avatar

Atul PatelAtul Patel

5334 silver badges11 bronze badges

my main machine is windows 10 and I have CEntOS 7 VBox
Search in your main machine for «known_hosts»
usually, known_host location in windows in «user/.ssh/known_host»
open it using notepad and delete the line where your centos vbox ip
then try connect in your terminal

in mac os user you can find known_hosts in «~/.ssh/known_hosts«

answered Jul 17, 2021 at 3:57

Amr Khaled's user avatar

This issue is also caused if the Dynamic Host Configuration Protocol is not set-up properly.

To solve this first check if your IP Address is configured using
ping ipaddress,
If there is no packet loss and the IP Address is working fine try any other solution. If there is no response and you have 100% packet loss, it means that your IP Address is not working and not configured.

Now configure your IP Address using,

sudo dhclient -v devicename

To check your device you can use the ‘ip a’ command
For eg. My device was usb0 since I had connected the device through usb

This will configure an IP Address automatically and you can even see which one is configured. You can again check with the ‘ip a’ command to confirm.

Dharman's user avatar

Dharman

30.5k22 gold badges85 silver badges133 bronze badges

answered Nov 6, 2021 at 21:17

RISHI 's user avatar

RISHI RISHI

13 bronze badges

This happened to me after enabling port 22 with «sudo ufw allow ssh». Before that, I was getting a refusal from my machine when entering with ssh from another one. After enabling it, I thought it would work, but instead it showed the message «connection timed out». As I had just installed Ubuntu with the option of installing basic functions alongside, I checked whether I had the openssh-server with the command sudo apt list —installed | grep openssh-server. It turned out that Ubuntu had installed by defect the openssh-client instead. I uninstalled it and installed the openssh-server following the basic commands:

sudo apt-get purge openssh-client
sudo apt update
sudo apt install openssh-server

After that, a simple «sudo ufw allow ssh» worked perfectly and I was finally able to access the machine with an ssh command.

answered Nov 16, 2021 at 13:42

lufern11's user avatar

What worked for me was that i went to my security group and reset my IP and it worked

answered May 15, 2022 at 22:22

Forbes's user avatar

Here are some considerations which i took to resolve a similar issue that I had:

  • Port 22
  • IGW (Internet Gateway)
  • VPC

Scene 1> This is for port 22 not enabled with right configurations. If the port is set to custom or myip, the probable scene is this won’t work.

Scene 2> When you delete the internet gateway, the network is created and the instance will be functional too, but the routing from the internet will not work. Hence make sure that if there is a VPC, it has an Internet Gateway attached.

Scene 3> Check the VPC for the subnet associations and routing table entries. This might probably tell you the cause. I found one in this kind of troubleshooting. The route used to land up in a «blackhole» (shows up in the route table section of the console). To fix this I had to check and find out my internet gateway and found the issue with the IGW.

Moral of the story: always trace backward in the network!

answered Jul 23, 2022 at 10:18

Sachin's user avatar

In my case I’m on windows, I reset my firewall settings, and it fixed

answered Oct 9, 2022 at 15:18

Shahjahan's user avatar

ShahjahanShahjahan

1612 silver badges3 bronze badges

  1. If you get any error check the basic a version control request with ssh -V and If it is not installed, install it with the sudo apt-get install openssh-server command.

  2. Check your virtual machine ssh connection with sudo service ssh status at console.

  3. Check «Active» rows and if write a inactive(dead) the console write sudo service ssh start

Result: Now you can check your connection with sudo service ssh status command and send ssh connection request.

answered Oct 17, 2022 at 20:35

Adem's user avatar

AdemAdem

211 silver badge4 bronze badges

Reset the firewall and reboot your VPS from your hosting service, it will start working perfectly fine

answered Dec 11, 2022 at 20:37

Furqan's user avatar

check whether accidentally you have deleted the default vpc or default subnets ,while creating your own vpc and subnets.
I have done this mistake while creating vpc, hence got this error while connecting via ssh.

alos check whether u have attched IGW to public subnets.

answered Mar 12, 2021 at 10:53

kavithaperugu's user avatar

2

Its not complicated.
First, go disable your firewall(USE YOUR CONTROL PANEL)after you check if your openssh is active.

Disable firewall, then use putty or any alternative to basically disable using this command sudo ufw disable

try now

answered Dec 12, 2022 at 11:49

Samuel Julius O U's user avatar

1

Update the security group of that instance. Your local IP must have updated. Every time it’s IP flips. You will have to go update the Security group.

answered Oct 17, 2020 at 14:59

chirag garg's user avatar

1

25 мая, 2017 11:40 дп
93 893 views
| Комментариев нет

Linux, SSH

В первой статье этой серии вы узнали о том, как и в каких ситуациях вы можете попробовать исправить ошибки SSH. Остальные статьи расскажут, как определить и устранить ошибки:

  • Ошибки протокола: в этой статье вы узнаете, что делать, если сбрасываются клиентские соединения, клиент жалуется на шифрование или возникают проблемы с неизвестным или измененным удаленным хостом.
  • Ошибки аутентификации: поможет устранить проблемы с парольной аутентификацией или сбросом SSH-ключей.
  • Ошибки оболочки: это руководство поможет исправить ошибки ветвления процессов, валидации оболочки и доступа к домашнему каталогу.

Для взаимодействия SSH-клиента с SSH-сервером необходимо установить базовое сетевое подключение. Это руководство поможет определить некоторые общие ошибки подключения, исправить их и предотвратить их возникновение в будущем.

Требования

  • Убедитесь, что можете подключиться к виртуальному серверу через консоль.
  • Проверьте панель на предмет текущих проблем, влияющих на работу и состояние сервера и гипервизора.

Основные ошибки

Разрешение имени хоста

Большинство ошибок подключения возникает тогда, когда ссылка на хост SSH не может быть сопоставлена с сетевым адресом. Это почти всегда связано с DNS, но первопричина часто бывает не связана с DNS.

На клиенте OpenSSH эта команда:

ssh user@example.com

может выдать ошибку:

ssh: Could not resolve hostname example.com: Name or service not known

В PuTTY может появиться такая ошибка:

Unable to open connection to example.com Host does not exist

Чтобы устранить эту ошибку, можно попробовать следующее:

  • Проверьте правильность написания имени хоста.
  • Убедитесь, что вы можете разрешить имя хоста на клиентской машине с помощью команды ping. Обратитесь к сторонним сайтам (WhatsMyDns.net, например), чтобы подтвердить результаты.

Если у вас возникают проблемы с разрешением DNS на любом уровне, в качестве промежуточного решения можно использовать IP-адрес сервера, например:

ssh user@111.111.111.111
# вместо
ssh user@example.com.

Истечение времени соединения

Эта ошибка значит, что клиент попытался установить соединение с SSH-сервером, но сервер не смог ответить в течение заданного периода ожидания.

На клиенте OpenSSH следующая команда:

ssh user@111.111.111.111

выдаст такую ошибку:

ssh: connect to host 111.111.111.111 port 22: Connection timed out

В PuTTY ошибка выглядит так:

Network error: Connection timed out

Чтобы исправить ошибку:

  • Убедитесь, что IP-адрес хоста указан правильно.
  • Убедитесь, что сеть поддерживает подключение через используемый порт SSH. Некоторые публичные сети могут блокировать порт 22 или пользовательские SSH-порты. Чтобы проверить работу порта, можно, например, попробовать подключиться к другим хостам через этот же порт. Это поможет вам определить, не связана ли проблема с самим сервером.
  • Проверьте правила брандмауэра. Убедитесь, что политика по умолчанию – не DROP.

Отказ в соединении

Эта ошибка означает, что запрос передается на хост SSH, но хост не может успешно принять запрос.

На клиенте OpenSSH следующая команда выдаст ошибку:

ssh user@111.111.111.111
ssh: connect to host 111.111.111.111 port 22: Connection refused

В PuTTY ошибка появится в диалоговом окне:

Network error: Connection refused

Эта ошибка имеет общие с ошибкой Connection Timeout причины. Чтобы исправить её, можно сделать следующее:

  • Убедиться, что IP-адрес хоста указан правильно.
  • Убедиться, что сеть поддерживает подключение через используемый порт SSH. Некоторые публичные сети могут блокировать порт 22 или пользовательские SSH-порты. Чтобы проверить работу порта, можно, например, попробовать подключиться к другим хостам через этот же порт.
  • Проверить правила брандмауэра. Убедитесь, что политика по умолчанию – не DROP, и что брандмауэр не блокирует этот порт.
  • Убедиться, что сервис запущен и привязан к требуемому порту.

Рекомендации по исправлению ошибок подключения

Брандмауэр

Иногда проблемы с подключением возникают из-за брандмауэра. Он может блокировать отдельные порты или сервисы.

Читайте также: Что такое брандмауэр и как он работает?

В разных дистрибутивах используются разные брандмауэры. Вы должны научиться изменять правила и политики своего брандмауэра. В Ubuntu обычно используется UFW, в CentOS – FirewallD. Брандмауэр iptables используется независимо от системы.

Читайте также:

  • Основы UFW: общие правила и команды фаервола
  • Настройка брандмауэра FirewallD в CentOS 7
  • Основы Iptables: общие правила и команды брандмауэра

Чтобы настроить брандмауэр, нужно знать порт сервиса SSH. По умолчанию это порт 22.

Чтобы запросить список правил iptables, введите:

iptables -nL

Такой вывод сообщает, что правил, блокирующих SSH, нет:

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Если в выводе вы видите правило или политику по умолчанию REJECT или DROP, убедитесь, что цепочка INPUT разрешает доступ к порту SSH.

Чтобы запросить список правил FirewallD, введите:

firewall-cmd --list-services

Список, появившийся на экране, содержит все сервисы, которые поддерживаются брандмауэром. В списке должно быть правило:

dhcpv6-client http ssh

Если вы настроили пользовательский порт SSH, используйте опцию –list-ports. Если вы создали пользовательское определение сервиса, добавьте опцию –list-services, чтобы найти SSH.

Чтобы проверить состояние UFW, введите:

ufw status

Команда вернёт доступные порты:

Status: active
To                         Action      From
--                         ------      ----
22                         LIMIT       Anywhere
443                        ALLOW       Anywhere
80                         ALLOW       Anywhere
Anywhere                   ALLOW       192.168.0.0
22 (v6)                    LIMIT       Anywhere (v6)
443 (v6)                   ALLOW       Anywhere (v6)
80 (v6)                    ALLOW       Anywhere (v6)

В списке должен быть порт SSH.

Проверка состояния сервиса SSH

Если вы не можете подключиться к серверу по SSH, убедитесь, что сервис SSH запущен. Способ сделать это зависит от операционной системы сервера. В более старых версиях дистрибутивов (Ubuntu 14.04, CentOS 6, Debian 8) используется команда service. Современные дистрибутивы на основе Systemd используют команду systemctl.

Метод проверки состояния сервиса может варьироваться от системы к системе. В более старых версиях (Ubuntu 14 и ниже, CentOS 6, Debian 6) используется команда service, поддерживаемая системой инициализации Upstart, а в более современных дистрибутивах для управления сервисом используется команда systemctl.

Примечание: В дистрибутивах Red Hat (CentOS и Fedora) сервис называется sshd, а в Debian и Ubuntu – ssh.

В более старых версия используйте команду:

service ssh status

Если процесс работает должным образом, вы увидите вывод, который содержит PID:

ssh start/running, process 1262

Если сервис не работает, вы увидите:

ssh stop/waiting

В системах на основе SystemD используйте:

systemctl status sshd

В выводе должна быть строка active:

sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: active (running) since Mon 2017-03-20 11:00:22 EDT; 1 months 1 days ago
Process: 899 ExecStartPre=/usr/sbin/sshd-keygen (code=exited, status=0/SUCCESS)
Main PID: 906 (sshd)
CGroup: /system.slice/sshd.service
├─  906 /usr/sbin/sshd -D
├─26941 sshd: [accepted]
└─26942 sshd: [net]

Если сервис не работает, вы увидите в выводе inactive:

sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: inactive (dead) since Fri 2017-04-21 08:36:13 EDT; 2s ago
Process: 906 ExecStart=/usr/sbin/sshd -D $OPTIONS (code=exited, status=0/SUCCESS)
Process: 899 ExecStartPre=/usr/sbin/sshd-keygen (code=exited, status=0/SUCCESS)
Main PID: 906 (code=exited, status=0/SUCCESS)

Чтобы перезапустить сервис, введите соответственно:

service ssh start
systemctl start sshd

Проверка порта SSH

Существует два основных способа проверить порт SSH: проверить конфигурационный файл SSH или просмотреть запущенный процесс.

Как правило, конфигурационный файл SSH хранится в /etc/ssh/sshd_config. Стандартный порт 22 может переопределяться любой строкой в этом файле, определяющей директиву Port.

Запустите поиск по файлу с помощью команды:

grep Port /etc/ssh/sshd_config

Читайте также: Использование Grep и регулярных выражений для поиска текстовых шаблонов в Linux

Команда вернёт:

Port 22

Если вы уже убедились, что сервис работает, теперь вы можете узнать, работает ли он на требуемом порте. Для этого используйте команду ss. Команда netstat –plnt выдаст аналогичный результат, но команду ss рекомендуется использовать для запроса информации сокета из ядра.

ss -plnt

В выводе должно быть указано имя программы и порт, который она прослушивает. Например, следующий вывод сообщает, что сервис SSH прослушивает все интерфейсы и порт 22.

State       Recv-Q Send-Q              Local Address:Port                       Peer Address:Port
LISTEN      0      128                 *:22                                     *:*                   users:(("sshd",pid=1493,fd=3))
LISTEN      0      128                 :::22                                    :::*                  users:(("sshd",pid=1493,fd=4))

Символ * и 0.0.0.0 указывает, что все интерфейсы сервера прослушиваются. Строка 127.0.0.1 значит, что сервис не является общедоступным. В sshd_config директива ListenAddress должна быть закомментирована, чтобы прослушивать все интерфейсы, или должна содержать внешний IP-адрес сервера.

Если у вас не получается самостоятельно настроить соединение SSH, вы можете обратиться за помощью к службе поддержки своего хостинг-провайдера.

Tags: firewalld, Iptables, OpenSSH, PuTTY, SSH, UFW

I am trying to connect to remote server via ssh but getting connection timeout.

I ran the following command

ssh testkamer@test.dommainname.com

and getting following result

ssh: connect to host testkamer@test.dommainname.com port 22: Connection timed out

but if try to connect on another remote server then I can login successfully.

So I think there is no problem in ssh and other person try to login with same login and password he can successfully login to server.

Please help me
Thanks.

Manish Shrivastava's user avatar

asked Aug 29, 2012 at 6:41

urjit on rails's user avatar

urjit on railsurjit on rails

1,7534 gold badges18 silver badges36 bronze badges

3

Here are a couple of things that could be preventing you from connecting to your Linode instance:

  1. DNS problem: if the computer that you’re using to connect to your
    remote server isn’t resolving test.kameronderdehamer.nl properly
    then you won’t be able to reach your host. Try to connect using the
    public IP address assigned to your Linode and see if it works (e.g.
    ssh user@123.123.123.123). If you can connect using the public IP
    but not using the hostname that would confirm that you’re having
    some problem with domain name resolution.

  2. Network issues: there
    might be some network issues preventing you from establishing a
    connection to your server. For example, there may be a misconfigured
    router in the path between you and your host, or you may be
    experiencing packet loss. While this is not frequent, it has
    happenned to me several times with Linode and can be very annoying.
    It could be a good idea to check this just in case. You can have a look
    at Diagnosing network issues with MTR (from the Linode
    library).

answered Sep 3, 2012 at 21:46

mfriedman's user avatar

1

That error message means the server to which you are connecting does not reply to SSH connection attempts on port 22. There are three possible reasons for that:

  1. You’re not running an SSH server on the machine. You’ll need to install it to be able to ssh to it.

  2. You are running an SSH server on that machine, but on a different port. You need to figure out on which port it is running; say it’s on port 1234, you then run ssh -p 1234 hostname.

  3. You are running an SSH server on that machine, and it does use the port on which you are trying to connect, but the machine has a firewall that does not allow you to connect to it. You’ll need to figure out how to change the firewall, or maybe you need to ssh from a different host to be allowed in.

EDIT: as (correctly) pointed out in the comments, the third is certainly the case; the other two would result in the server sending a TCP «reset» package back upon the client’s connection attempt, resulting in a «connection refused» error message, rather than the timeout you’re getting. The other two might also be the case, but you need to fix the third first before you can move on.

Ayxan Haqverdili's user avatar

answered Mar 19, 2020 at 20:42

Akash S's user avatar

Akash SAkash S

1861 silver badge4 bronze badges

1

I got this error and found that I don’t have my SSH port (non standard number) whitelisted in config server firewall.

Victor2748's user avatar

Victor2748

4,14913 gold badges52 silver badges89 bronze badges

answered Nov 13, 2014 at 0:08

16851556's user avatar

1685155616851556

2393 silver badges11 bronze badges

Just adding this here because it worked for me. Without changing any settings (to my knowledge), I was no longer able to access my AWS EC2 instance with: ssh -i /path/to/key/key_name.pem admin@ecx-x-x-xxx-xx.eu-west-2.compute.amazonaws.com

It turned out I needed to add a rule for inbound SSH traffic, as explained here by AWS. For Port range 22, I added 0.0.0.0/0, which allows all IPv4 addresses to access the instance using SSH.

Note that making the instance accessible to all IPv4 addresses is a security risk; it is acceptable for a short time in a test environment, but you’ll likely need a longer term solution.

answered Nov 22, 2021 at 7:58

arranjdavis's user avatar

arranjdavisarranjdavis

6498 silver badges16 bronze badges

If you are on Public Network, Firewall will block all incoming connections by default. check your firewall settings or use private network to SSL

answered Oct 22, 2018 at 12:36

Shishay Ghebrehiwet's user avatar

This happens because of firewall connection.
Reset your firewall connection from your hosting website.

It will start working.

After connecting to the server again add this to your (ufw) security

sudo ufw allow 22/tcp

answered Nov 9, 2022 at 18:50

Furqan's user avatar

The possibility could be, the SSH might not be enabled on your server/system.

  1. Check sudo systemctl status ssh is Active or not.
  2. If it’s not active, try installing with the help of these commands

sudo apt update

sudo apt install openssh-server

Now try to access the server/system with following command

ssh username@ip_address

answered Jan 29, 2019 at 7:52

Gani's user avatar

GaniGani

4121 gold badge7 silver badges16 bronze badges

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file.
Try to increase the session timeout and see if it fails again

answered Oct 27, 2016 at 12:58

Biswanath Das's user avatar

My VPN connection was not enabled. I was trying all possible way to open up the Firwall and Ports until I realized, I am working from home and my VPN connection was down.
But yes, Firewall and ssh configurations can be a reason.

answered May 8, 2020 at 7:10

sg28's user avatar

sg28sg28

1,3639 silver badges19 bronze badges

Try connecting to a vpn, if possible. That was the reason I was facing problem.
Tip: if you’re using an ec2 machine, try rebooting it. This worked for me the other day :)

answered Jan 13, 2021 at 5:46

dhruv arora's user avatar

I had this issue while trying to ssh into a local nextcloud server from my Mac.

I had no issues ssh-ing in once, but if I tried to have more than one concurrent connection, it would hang until it timed out.

Note, I was sshing to my user@public-ip-address.

I realized the second connection only didn’t work when I tried to ssh into it when on the same network, ie my home network

Furthermore, when I tried ssh user@server-domain it worked!

The end fix was to use ssh user@server-domain rather than ssh user@public-ip

answered Mar 21, 2021 at 20:01

Jacob Waters's user avatar

Jacob WatersJacob Waters

2971 gold badge2 silver badges10 bronze badges

This may be very case specific and work in some cases only but
check to see if you were previously connecting through some VPN software/application.

Try connecting again to the VPN. Worked in my case.

answered Nov 11, 2021 at 9:49

Abhinav Dobhal's user avatar

I have experienced a couple of nasty issues that lead to these errors, and these are different from everyone else’s answer here:

  1. Wrong folder access rights. You need to have specific directory permissions on you ssh folders and files.
    a. The .ssh directory permissions should be 700 (drwx——).

    b. The public key (.pub file) should be 644 (-rw-r—r—).

    c. The private key (id_rsa) on the client host, and the authorized_keys file on the server, should be 600 (-rw——-).

  2. Nasty docker network configuration. This just happened to me on an AWS EC2 instance. It turned out that I had a docker network with an ip range that interfered with the ssh access granted by the security group and VPC. The docker network’s range was e.g. 192.168.176.0/20 (i.e. a range from 192.168.176.1->192.168.191.254), whereas the security group had a range of 192.168.179.0/24; interfering with the SSH access.

answered Mar 18, 2022 at 12:46

Andreas Forslöw's user avatar

I had this error when trying to SSH into my Raspberry pi from my MBP via bash terminal. My RPI was connected to the network via wifi/wlan0 and this IP had been changed upon restart by my routers DHCP.

Check IP being used to login via SSH is correct. Re-check IP of device being SSH’d into (in my case the RPI), which can be checked using hostname -I

Confirm/amend SSH login credentials on «guest» device (in my case the MBP) and it worked fine in my attempt.

answered Mar 28, 2020 at 20:34

Silicon Star's user avatar

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

answered Jul 3, 2020 at 8:32

Atul Patel's user avatar

Atul PatelAtul Patel

5334 silver badges11 bronze badges

my main machine is windows 10 and I have CEntOS 7 VBox
Search in your main machine for «known_hosts»
usually, known_host location in windows in «user/.ssh/known_host»
open it using notepad and delete the line where your centos vbox ip
then try connect in your terminal

in mac os user you can find known_hosts in «~/.ssh/known_hosts«

answered Jul 17, 2021 at 3:57

Amr Khaled's user avatar

This issue is also caused if the Dynamic Host Configuration Protocol is not set-up properly.

To solve this first check if your IP Address is configured using
ping ipaddress,
If there is no packet loss and the IP Address is working fine try any other solution. If there is no response and you have 100% packet loss, it means that your IP Address is not working and not configured.

Now configure your IP Address using,

sudo dhclient -v devicename

To check your device you can use the ‘ip a’ command
For eg. My device was usb0 since I had connected the device through usb

This will configure an IP Address automatically and you can even see which one is configured. You can again check with the ‘ip a’ command to confirm.

Dharman's user avatar

Dharman

30.5k22 gold badges85 silver badges133 bronze badges

answered Nov 6, 2021 at 21:17

RISHI 's user avatar

RISHI RISHI

13 bronze badges

This happened to me after enabling port 22 with «sudo ufw allow ssh». Before that, I was getting a refusal from my machine when entering with ssh from another one. After enabling it, I thought it would work, but instead it showed the message «connection timed out». As I had just installed Ubuntu with the option of installing basic functions alongside, I checked whether I had the openssh-server with the command sudo apt list —installed | grep openssh-server. It turned out that Ubuntu had installed by defect the openssh-client instead. I uninstalled it and installed the openssh-server following the basic commands:

sudo apt-get purge openssh-client
sudo apt update
sudo apt install openssh-server

After that, a simple «sudo ufw allow ssh» worked perfectly and I was finally able to access the machine with an ssh command.

answered Nov 16, 2021 at 13:42

lufern11's user avatar

What worked for me was that i went to my security group and reset my IP and it worked

answered May 15, 2022 at 22:22

Forbes's user avatar

Here are some considerations which i took to resolve a similar issue that I had:

  • Port 22
  • IGW (Internet Gateway)
  • VPC

Scene 1> This is for port 22 not enabled with right configurations. If the port is set to custom or myip, the probable scene is this won’t work.

Scene 2> When you delete the internet gateway, the network is created and the instance will be functional too, but the routing from the internet will not work. Hence make sure that if there is a VPC, it has an Internet Gateway attached.

Scene 3> Check the VPC for the subnet associations and routing table entries. This might probably tell you the cause. I found one in this kind of troubleshooting. The route used to land up in a «blackhole» (shows up in the route table section of the console). To fix this I had to check and find out my internet gateway and found the issue with the IGW.

Moral of the story: always trace backward in the network!

answered Jul 23, 2022 at 10:18

Sachin's user avatar

In my case I’m on windows, I reset my firewall settings, and it fixed

answered Oct 9, 2022 at 15:18

Shahjahan's user avatar

ShahjahanShahjahan

1612 silver badges3 bronze badges

  1. If you get any error check the basic a version control request with ssh -V and If it is not installed, install it with the sudo apt-get install openssh-server command.

  2. Check your virtual machine ssh connection with sudo service ssh status at console.

  3. Check «Active» rows and if write a inactive(dead) the console write sudo service ssh start

Result: Now you can check your connection with sudo service ssh status command and send ssh connection request.

answered Oct 17, 2022 at 20:35

Adem's user avatar

AdemAdem

211 silver badge4 bronze badges

Reset the firewall and reboot your VPS from your hosting service, it will start working perfectly fine

answered Dec 11, 2022 at 20:37

Furqan's user avatar

check whether accidentally you have deleted the default vpc or default subnets ,while creating your own vpc and subnets.
I have done this mistake while creating vpc, hence got this error while connecting via ssh.

alos check whether u have attched IGW to public subnets.

answered Mar 12, 2021 at 10:53

kavithaperugu's user avatar

2

Its not complicated.
First, go disable your firewall(USE YOUR CONTROL PANEL)after you check if your openssh is active.

Disable firewall, then use putty or any alternative to basically disable using this command sudo ufw disable

try now

answered Dec 12, 2022 at 11:49

Samuel Julius O U's user avatar

1

Update the security group of that instance. Your local IP must have updated. Every time it’s IP flips. You will have to go update the Security group.

answered Oct 17, 2020 at 14:59

chirag garg's user avatar

1

A connection timeout means that the client attempted to establish a network socket to the SSH server, but the server failed to respond within the timeout period.

ssh: connect to host 203.0.113.0 port 22: Connection timed out

In PuTTY, you might see an error window with text like this:

Network error: Connection timed out

In this article, we will dive into this issue and see how to troubleshoot this error:

Check SSH command syntax

The syntax for the SSH command is as follows:

ssh [options] [user@]hostname [command]

Here is a brief explanation of each part of the syntax:

  • ssh – This is the command to initiate the SSH connection.
  • [options] – This is an optional parameter that allows you to specify additional options to configure the SSH connection. For example, you can use the -p option to specify a non-standard SSH port.
  • [user@]hostname – This is the remote host that you want to connect to. You can optionally specify a username to use for the SSH connection. If you omit the username, the default username for your current session will be used.
  • [command] – This is an optional parameter that allows you to specify a command to run on the remote host after the SSH connection is established. If you omit this parameter, you will be dropped into an interactive shell on the remote host.

Here is an example of how to use the SSH command to connect to a remote host:

ssh username@example.com

This will initiate an SSH connection to the host example.com using the username username.

If you have already set up SSH keys, you will be logged in without being prompted for a password. If not, you will be prompted to enter your password.

Enable verbose output in SSH command

The ssh -vvv command is used to establish an SSH connection to a remote server with verbose output enabled. The -v flag stands for “verbose,” and it can be used up to three times in a row (i.e., -v, -vv, -vvv) to increase the level of detail in the output. Here’s what each level of verbosity provides:

  • -v: Verbose mode, displays debug messages about the authentication process and other connection details.
  • -vv: Provides additional debug information and more details about the connection process.
  • -vvv: Provides the most detailed output, including debugging information about the SSH handshake and messages exchanged during the connection process.

Using the -vvv flag is helpful when troubleshooting SSH connection issues, as it provides a wealth of information that can help pinpoint the problem.

However, keep in mind that the output can be quite verbose and overwhelming, so it’s usually best to start with the -v or -vv flags and work your way up to -vvv if needed.

Confirm that the server is correct

To confirm that the server’s IP address is correct, you can follow these steps:

Identify the server that you want to connect to. This could be a domain name, a hostname, or an IP address.

Open a command prompt or terminal window on your local machine.

Type the following command, replacing server_address with the domain name, hostname, or IP address of the server:

ping server_address

This will send a small packet of data to the server and wait for a response. If the hostname is resolvable, you should see a series of responses.

Look at the IP address displayed in the ping results to confirm that it matches the expected IP address for the server.

If the hostname is not resolvable, you will see a message indicating that the hostname could not be resolved.

In this case, you may need to check your DNS settings or use a different hostname or IP address to connect to the server.

Check that the network allows SSH traffic over the port being used. 

Some public networks may block port 22 or custom SSH ports.To check if the network allows SSH traffic over the port being used, you can follow these steps:

Identify the port number being used for SSH on the server. The default port number for SSH is 22, but some servers may use a custom port number.

Open a command prompt or terminal window on your local machine.

Type the following command, replacing port_number with the port number being used for SSH:

telnet server_address port_number

This will attempt to establish a connection to the server using the Telnet protocol on the specified port. If the network allows SSH traffic on this port, you should see a message indicating that the connection was successful.

If the network does not allow SSH traffic on this port, you will see a message indicating that the connection could not be established.

If the network is blocking SSH traffic on the port being used, you may need to use a different port number for SSH, or configure the network to allow SSH traffic on the current port.

For example, to check if the SSH port (port 22) is open on a remote server with the IP address 192.168.1.1, you can use the following command:

telnet 192.168.1.1 22

If the port is open, you will see something like this:

Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is '^]'.
Press CTRL + ] and then type quit to exit.

If the port is not open, you will see an error message like this:

Trying 192.168.1.1...
telnet: Unable to connect to remote host: Connection refused

Verify the firewall rules on both the client and server

Identify the firewall software that is running on both the client and server machines. Common firewall software includes iptables on Linux and Windows Firewall on Windows.

Check the firewall rules on both the client and server to ensure that they are not set to DROP traffic by default. If the default policy is set to DROP, incoming traffic will be blocked by default and will need to be explicitly allowed.

Check that the SSH port is permitted for incoming connections. By default, SSH uses port 22, but some servers may use a custom port number.

On Linux machines with iptables, you can use the following command to list the current firewall rules:

sudo iptables -L

On Windows machines, you can use the Windows Firewall with Advanced Security console to view and manage firewall rules.

Look for a rule that allows incoming traffic on the SSH port. If such a rule exists, the SSH port is permitted for incoming connections. If there is no such rule, you may need to create a new rule to allow incoming traffic on the SSH port.

On Linux machines with iptables, you can use the following command to add a new rule to allow incoming traffic on the SSH port:

sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT

This command adds a new rule to the INPUT chain of the iptables firewall to accept incoming traffic on the SSH port. The -p tcp option specifies that the rule applies to TCP traffic, and the –dport ssh option specifies the destination port as the SSH port (port 22 by default). Finally, the -j ACCEPT option tells iptables to accept incoming traffic that matches the specified rule.

Note that this command only adds the new rule temporarily and will be lost when the system is rebooted. To make the rule persistent, you will need to save the iptables configuration. This can be done using the following command:

sudo iptables-save > /etc/sysconfig/iptables

This command saves the current iptables configuration to the /etc/sysconfig/iptables file, which is read at boot time to restore the firewall rules.

Increase the timeout value for the SSH command

To increase the timeout value for the SSH command, you can use the -o option with the ServerAliveInterval parameter. This option sets the time interval (in seconds) between sending packets to the server to request a response and keep the connection alive.

For example, to set the timeout value to 120 seconds (2 minutes), you can use the following command:

ssh -o ServerAliveInterval=120 username@hostname

This will send a packet every 120 seconds to the server to keep the connection alive. If the server does not respond to any of these packets within the specified interval, the connection will be closed and the SSH command will time out.

I have trouble connecting to a server with ssh from my Lubuntu 14.04 computer, although it can be done from other machines. I can’t get to the address online either (others can).

Am currently using a 3G network from my phone, but this doesn’t seem to be the problem as I can connect to the server using another computer with the same 3G connection.

This is my attempt to connect:

root@Elizabeth:/# ssh USER@HOSTNAME
ssh: connect to host HOSTNAME port 22: Connection timed out

UPDATE: Saw that ping HOSTNAME renders the wrong IP-address, so I guess this could be a clue to what’s wrong. Any way to solve that? I can get around it though by doing ssh USER@IPADDRESS, as suggested to me in a comment.

Some further info below, if it’s useful. I’m new to working with servers and networking, so do say if there is other information needed to say what is wrong.

root@Elizabeth:/# nm-tool | grep "DNS"
DNS: 172.20.10.1
DNS: 172.20.10.1

root@Elizabeth:/# nslookup HOSTNAME
Server:        127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:
Name:    HOSTNAME
Address: IP-address # correct IP-address for HOSTNAME

root@Elizabeth:/# ip route
default via 172.20.10.1 dev eth1  proto static 
172.20.10.0/28 dev eth1  proto kernel  scope link  src 172.20.10.3  metric 1 
172.20.10.0/28 dev wlan0  proto kernel  scope link  src 172.20.10.5  metric 9

  • Ошибка spn 1675 fmi 5 шакман
  • Ошибка spn 1623 fmi 9 камаз
  • Ошибка srs вито 638
  • Ошибка sql сервер 4060
  • Ошибка spn 1623 fmi 9 cummins