The error message “ssh: connect to host <host> port 22: Connection refused” typically indicates that your SSH client is unable to establish a connection with the SSH server.
It can occur due to various reasons. The SSH server may not be running on the remote host, the host or IP address provided could be incorrect, the SSH server may be using a different port than the default port 22, a firewall might be blocking the SSH connection, or there could be network connectivity issues between the client and server.
In this article, we will dive into this issue.
Get Your Free Linux training!
Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career!
Start Learning Linux today — Free!
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 [email protected]
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.
Verify SSH server status
Ensure that the SSH server is running and accessible on the host you are trying to connect to.
Log in to the host using an alternative method like remote desktop or console access, and check the SSH server’s status with the following systemctl command:
systemctl status sshd
sudo systemctl status sshd.service
ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2022-06-23 17:44:36 UTC; 1 day 3h ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 829 (sshd)
Tasks: 1 (limit: 9535)
Memory: 5.1M
CGroup: /system.slice/ssh.service
└─829 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups
Jun 23 17:44:35 ubu2004 systemd[1]: Starting OpenBSD Secure Shell server...
Jun 23 17:44:36 ubu2004 sshd[829]: Server listening on 0.0.0.0 port 22.
Jun 23 17:44:36 ubu2004 sshd[829]: Server listening on :: port 22.
If the SSH server is not running, start it using the appropriate command for your system. For example:
systemctl start sshd
Confirm SSH server port
By default, SSH servers listen on port 22. However, it’s possible that the SSH server on the host you’re trying to connect to is configured to use a different port.
To check which port the SSH server is using, you can follow these steps:
Log in to the server where the SSH server is running. You can use an alternative method like remote desktop or console access if you cannot establish an SSH connection.
Once you’re logged in to the server, open a terminal or command prompt.
Run the following command to view the SSH server’s configuration file:
sudo nano /etc/ssh/sshd_config
This command opens the SSH server configuration file in the Nano text editor. Look for the line that specifies the port number. It typically looks like this:
Port 22
If the port number is set to the default value of 22, it means the SSH server is using the default port. If a different port number is specified, take note of that number.
After noting the port number, press Ctrl+X to exit the Nano editor. You will be prompted to save the changes made to the file. If you did not make any changes, simply press N to exit without saving.
Remember, if the SSH server is using a non-standard port, you will need to specify that port when connecting to the server using SSH. For example:
ssh -p port_number username@host
If you do not have access to the server’s configuration file, you can also try checking the SSH server’s status and listening ports by running the following command:
sudo netstat -tlnp | grep ssh
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 4012596/sshd
tcp6 0 0 :::22 :::* LISTEN 4012596/sshd
Here -tlnp is the shortened form of the –listen –tcp –process –numeric arguments.
This command will display the active TCP connections and listening ports on the server. Look for the line that includes “ssh” to find the port number being used by the SSH server.
Verify network connectivity
Verifying network connectivity is an important step when troubleshooting the “ssh: connect to host <host> port 22: Connection refused” error.
It helps determine if there are any network-related issues that might be preventing your SSH client from reaching the SSH server.
The ping command is a common tool used to test network connectivity between two devices. When you execute the ping <host> command, your computer sends a small network packet to the specified host, and if the host is reachable and responsive, it sends a reply back.
If the ping command returns a response from the host like below, it indicates that the network connection is working fine.
# ping google.com
PING google.com (142.250.189.174) 56(84) bytes of data.
64 bytes from sfo03s24-in-f14.1e100.net (142.250.189.174): icmp_seq=1 ttl=116 time=1.97 ms
64 bytes from sfo03s24-in-f14.1e100.net (142.250.189.174): icmp_seq=2 ttl=116 time=1.79 ms
64 bytes from sfo03s24-in-f14.1e100.net (142.250.189.174): icmp_seq=3 ttl=116 time=1.93 ms
In this case, the “ssh: connect to host <host> port 22: Connection refused” error is likely due to a different issue, such as the SSH server not running or a firewall blocking the SSH connection.
However, if the ping command fails to receive a response or shows that the host is unreachable, it suggests a network connectivity problem.
# ping howtouselinux.com
PING howtouselinux.com (164.92.86.53) 56(84) bytes of data.
^C
--- howtouselinux.com ping statistics ---
7 packets transmitted, 0 received, 100% packet loss, time 6150ms
Firewall blocking the connection
When encountering the “ssh: connect to host <host> port 22: Connection refused” error, one possible cause is a firewall blocking the SSH connection.
Firewalls are security measures that monitor and control network traffic, and they can be set up at different points within a network, including the SSH server or any intermediate network devices.
Firewalls often enforce rules that determine which network connections are allowed or blocked.
Determine if the firewall is on the SSH server itself or if it is located on an intermediate network device, such as a router or a dedicated firewall appliance.
If the firewall is located on an intermediate network device, such as a router, you need to configure it to permit SSH traffic to reach the SSH server.
There are a few different ways to check the status of the firewall on a Linux machine:
ufw (Uncomplicated Firewall) is a user-friendly firewall that is installed by default on many Linux distributions. To check the status of ufw, use the status command:
sudo ufw status
This will show you whether ufw is active or inactive, as well as the rules that are currently in place.
If ufw is not installed on your machine, you can use the iptables command to check the firewall rules. To see the current firewall rules, use the -L flag:
sudo iptables -L
This will show you the rules that are currently in place for the different chains (INPUT, FORWARD, and OUTPUT).
Alternatively, you can use the firewall-cmd command, which is part of the firewalld service. To check the status of the firewall, use the –state flag:
sudo firewall-cmd --state
This will show you whether the firewall is running or not. To see the current firewall rules, use the –list-all flag:
sudo firewall-cmd --list-all
This will show you the rules that are currently in place for the different zones.
Hence, ensure you have the SSH port allowed in your firewall. If you are using UFW, you can run the command:
sudo ufw allow 22/tcp
sudo ufw reload
This should add port 22 to the firewall settings and allow incoming and outgoing connections. If SSH is running on a different port, replace the port 22 with your target port.
If you are using firewall-cmd on Fedora or REHL family, you can run the command:
sudo firewall-cmd --permanent --add-port=22/tcp
sudo firewall-cmd --reload
Similarly, replace the port 22 with the port of your SSH server.
If you are using iptables, you can run the command:
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
As a troubleshooting step, you can temporarily disable the firewall(s) to determine if they are indeed the cause of the connection issue. This should only be done for testing purposes and should not be a permanent solution. Always exercise caution when making changes to firewall configurations.
After implementing these steps, try connecting to the remote host again using the SSH command.
If the issue persists, carefully review the error message to identify any specific details that might help pinpoint the problem.
Additionally, check the SSH server’s logs (/var/log/auth.log on Ubuntu/Debian or /var/log/secure on CentOS/RHEL) for more information on the connection issue.
- Why SSH do not run on port number 22?
- Does SSH require port 22?
- How do I fix SSH connection refused?
- Can’t connect to localhost connection refused?
- How do I enable SSH on Windows server?
- Is port 22 open windows?
- What is port 22 used for in Windows?
- Why is port 22 important?
Why SSH do not run on port number 22?
Sometimes while connecting to SSH servers, users often encounter “Connection refused” error by port 22. It happens because of several reasons like SSH service is not running, the port is blocked by the firewall, or the server is using a different port. It can also occur because of the IP conflict issue.
Does SSH require port 22?
The default port for SSH client connections is 22; to change this default, enter a port number between 1024 and 32,767. The default port for Telnet client connections is 23; to change this default, enter a port number between 1024 and 32,767.
How do I fix SSH connection refused?
Install an SSH tool such as OpenSSH on the server you want to connect to using the sudo apt install openssh-server command. If your firewall is blocking your SSH connection. Disable the firewall rules blocking your SSH connection by changing the destination port’s settings to ACCEPT.
Can’t connect to localhost connection refused?
When the localhost refused to connect error message appears, it is likely because the port is not correctly configured. However, other reasons, such as insufficient permissions or the Apache web server not running properly might also cause the error “this site can’t be reached localhost refused to connect.”
How do I enable SSH on Windows server?
Install OpenSSH using Windows Settings
Open Settings, select Apps > Apps & Features, then select Optional Features. Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then: Find OpenSSH Client, then click Install.
Is port 22 open windows?
In Windows 10, a message that asks you to press Enter or any key means that port 22 is open while a “Could not open connection” message indicates a closed port. In Windows 7 and Windows Vista, a blank screen indicates that the port is open.
What is port 22 used for in Windows?
Port 22: Remote login protocol secure shell (SSH) Port 23: Telnet, used for accessing system remotely but is not very secure. Port 25: Simple Mail Transfer Protocol (SMTP) used by e-mail servers.
Why is port 22 important?
It provides major improvements in security. and functionality over existing telnet and rlogin protocols and. implementations. In particular, it prevents IP, DNS and routing.
Port 22: Connection Refused is a common SSH error that generally happens because users try to connect to the wrong port.
The default SSH port is 22, but it’s generally changed to something else due to security concerns. As such, when users try to connect to port 22 (by default), they inevitably encounter this error.
In addition to this, reasons like the firewall blocking the SSH port or the SSH service being down also usually lead to this error. We’ve detailed more reasons, as well as steps to deal with each one in the sections below.
How to Fix Port 22: Connection Refused Error
Before you start troubleshooting, we recommend rebooting your router, as that could be all that’s needed to resolve the issue. Additionally, you should perform a ping test to confirm that this is actually an SSH issue rather than a general internet issue. If there’s packet loss, you’d better off fixing that first.
Also, this error is, for the most part, a server-end issue. As such, the first two fixes are applicable on the client end, but there’s not much you can do from the client system. Your best bet will be to try out the server-end fixes.
Verify Login Credentials
It’s easy to miss, but users sometimes enter incorrect credentials on the client end when attempting to connect to the SSH server. Try reconnecting with the correct credentials if this is the case before moving on to the other fixes.
Resolve DNS Issues
The second possible issue on the client end is that the system isn’t resolving the hostname, leading to this error. You can use the Public IP of the SSH server instead of the domain name to confirm this.
If there does indeed seem to be a DNS issue, you could try flushing the DNS cache with the following commands:sudo systemd-resolve --flush-caches
sudo resolvectl flush-caches
If that doesn’t help, you should change your DNS servers. Here are the steps to do so:
- Execute the following command:
sudo nano /etc/systemd/resolved.conf
- Change the DNS and FallbackDNS values to that of a different DNS Server.
- Save the changes and exit, and check if the issue is resolved.
If on a private network, you could also contact your system admin to make sure that the SSH server’s DNS entry is correct.
Ensure SSH is Installed
This might seem like a no-brainer, but users often encounter SSH issues on fresh installations as they forget that SSH doesn’t come preinstalled.
To install the OpenSSH server application and related files on Debian-based distros, use the following command:sudo apt install openssh-server
It’s also worth mentioning that some users were able to resolve the issue by purging the currently installed package with sudo apt purge openssh-server
and reinstalling it.
Check SSH Daemon Status
The SSH Daemon must be running for your connection to be successful. If you’ve made any changes to the SSH configurations, such as Port, for instance, you’ll also need to restart the service to apply the changes. Here’s how you can do so on Debian-based distros:
- To check the service status:
sudo service ssh status
- To start the service:
sudo service ssh start
- To restart the service:
sudo service ssh restart
Check SSH Listening Port
The default SSH port is 22, but for security reasons, it’s generally changed to something else. Use the grep Port /etc/ssh/sshd_config
command to find out which port the server is listening to.
Since you’re encountering this error, it’s likely not port 22. In such cases, you can connect to that specific port with the following command:ssh -p <port_no> <username>@<ip>
Allow SSH in Firewall
Another common reason for this error is that the firewall is blocking the SSH port. In such cases, you can allow the SSH port with the following steps:
- First, enable the firewall with the following command:
sudo ufw enable
- Next, replace port with the port no. and execute the following to allow the connection through the port:
sudo ufw allow port
- Afterward, reload the firewall using the
sudo ufw reload
command to ensure the changes are applied.
Ensure IP Is Whitelisted
There have also been cases where the connection failed because SSH was only configured to listen to certain addresses. In such cases, you can ensure the IP address you’re trying to access is whitelisted with the following steps:
- Execute the
sudo nano /etc/ssh/sshd_config
command. - If the ListenAddress directive is uncommented, make sure the IP you’re trying to access is included here.
- If you added the IP just now, press CTRL+O > Enter to save the changes and CTRL+X to exit the editor.
- Restart the SSH service with
sudo service ssh restart
and try connecting now.
Почему при использовании SSH возникает отказ в подключении?
Существует множество причин, по которым вы можете получить ошибку «Connection Refused» при попытке подключения к серверу по SSH. Чтобы решить эту проблему, вам сначала нужно определить, почему система отказалась от вашего подключения через SSH.
Ниже вы найдете некоторые из наиболее распространенных причин, которые могут вызвать отказ в соединении SSH.
Клиент SSH не установлен
Прежде чем устранять другие проблемы, первым делом необходимо проверить, правильно ли установлен SSH. На машине, с которой вы получаете доступ к серверу, должен быть настроен клиент SSH. Без правильной настройки клиента вы не сможете подключиться к серверу.
Чтобы проверить, есть ли в вашей системе клиент SSH, введите в окне терминала следующее:
ssh
Если терминал предоставляет список параметров команды ssh, клиент SSH установлен в системе. Однако, если он ответит, что команда не найдена (command not found), вам необходимо установить клиент OpenSSH.
Решение: установить клиент SSH
Чтобы установить клиент SSH на свой компьютер, откройте терминал и выполните одну из команд, перечисленных ниже.
Для систем Ubuntu / Debian:
sudo apt установить openssh-client
Для систем CentOS / RHEL:
sudo yum установить openssh-client
Демон SSH не установлен на сервере
Так же, как вам нужна клиентская версия SSH для доступа к удаленному серверу, вам нужна версия сервера для прослушивания и приема соединений. Таким образом, сервер может отклонить входящее соединение, если SSH-сервер отсутствует или настройка неверна.
Чтобы проверить, доступен ли SSH на удаленном сервере, выполните команду:
ssh localhost
Если на выходе отображается «Connection refused», переходите к установке SSH на сервере.
Решение: установите SSH на удаленный сервер
Чтобы решить проблему отсутствия сервера SSH, установите сервер OpenSSH.
Учетные данные неверны
Опечатки или неправильные учетные данные — частые причины отказа в SSH-соединении. Убедитесь, что вы не ошиблись при вводе имени пользователя или пароля.
Затем проверьте, правильно ли вы используете IP-адрес сервера.
Наконец, убедитесь, что у вас открыт правильный порт SSH. Вы можете проверить, запустив:
grep Port /etc/ssh/sshd_config
На выходе отображается номер порта, как на картинке ниже.
Служба SSH не работает
Служба SSH должна быть включена и работать в фоновом режиме. Если служба не работает, демон SSH не может принимать соединения.
Чтобы проверить статус службы, введите эту команду:
sudo service ssh status
Вывод должен ответить, что служба активна. Если терминал отвечает, что служба не работает, включите его, чтобы решить проблему.
Решение: включить службу SSH
Если система показывает, что демон SSH не активен, вы можете запустить службу, выполнив:
systemctl start sshd
Чтобы служба запускалась при загрузке, выполните команду:
sudo systemctl enable sshd
Брандмауэр препятствует подключению SSH
SSH может отклонить соединение из-за ограничений брандмауэра. Брандмауэр защищает сервер от потенциально опасных подключений. Однако, если в системе настроен SSH, необходимо настроить брандмауэр, чтобы разрешить SSH-соединения.
Убедитесь, что брандмауэр не блокирует SSH-соединения, так как это может вызвать ошибку «Connection refused».
Решение: разрешить SSH-подключения через брандмауэр
Чтобы решить проблему, о которой мы упоминали выше, вы можете использовать ufw (Uncomplicated Firewall — несложный брандмауэр), инструмент интерфейса командной строки для управления конфигурацией брандмауэра.
Введите следующую команду в окне терминала, чтобы разрешить SSH-соединения:
sudo ufw allow ssh
Порт SSH закрыт
Когда вы пытаетесь подключиться к удаленному серверу, SSH отправляет запрос на определенный порт. Чтобы принять этот запрос, на сервере должен быть открыт порт SSH.
Если порт закрыт, сервер отказывает в соединении.
По умолчанию SSH использует порт 22. Если вы не вносили никаких изменений в конфигурацию порта, вы можете проверить, прослушивает ли сервер входящие запросы.
Чтобы вывести список всех прослушивающих портов, запустите:
sudo lsof -i -n -P | grep LISTEN
Найдите порт 22 в выходных данных и проверьте, установлено ли для него STATE
значение LISTEN
.
Кроме того, вы можете проверить, открыт ли конкретный порт, в данном случае порт 22:
sudo lsof -i:22
Решение: откройте порт SSH
Чтобы разрешить порту 22 слушать запросы, используйте команду iptables
:
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
Вы также можете открывать порты через графический интерфейс, изменив настройки брандмауэра.
Отладка и ведение журнала SSH
Чтобы проанализировать проблемы SSH в Linux, вы можете включить подробный режим или режим отладки. Когда вы включаете этот режим, SSH выдает отладочные сообщения, которые помогают устранять проблемы с подключением, конфигурацией и аутентификацией.
Существует три уровня детализации:
- уровень 1 (-v)
- уровень 2 (-vv)
- уровень 3 (-vvv)
Поэтому вместо доступа к удаленному серверу с использованием синтаксиса ssh [server_ip]
добавьте параметр -v
и выполните:
ssh -v [server_ip]
В качестве альтернативы вы можете использовать:
ssh -vv [server_ip]
или
ssh -vvv [server_ip]