- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Как исправить ошибку SSH Connection Refused
- Почему при использовании SSH возникает отказ в подключении?
- Клиент SSH не установлен
- Демон SSH не установлен на сервере
- Учетные данные неверны
- Служба SSH не работает
- Брандмауэр препятствует подключению SSH
- Порт SSH закрыт
- Отладка и ведение журнала SSH
- How to fix: Connection refused by port 22 Debian/Ubuntu
- Fix Connection refused error
- Make sure OpenSSH is installed
- Check SSH service
- Check SSH server listening port
- Allow SSH in firewall
- Resolve Duplicate IP address conflict
- About the author
- Karim Buzdar
- How to Fix the SSH “Connection Refused” Error
- Prefer to watch the video version?
- What Is SSH and When Should I Use It?
- Why Is My SSH Connection Refused? (5 Reasons for Connectivity Errors)
- 1. Your SSH Service Is Down
- 2. You Have the Wrong Credentials
- Sign Up For the Newsletter
- Want to know how we increased our traffic over 1000%?
- 3. The Port You’re Trying to Use Is Closed
- 4. SSH Isn’t Installed on Your Server
- 5. Firewall Settings Are Preventing an SSH Connection
- Why Does PuTTY Say Connection Refused?
- How Do I Troubleshoot SSH Connectivity Errors?
- Summary
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Как исправить ошибку SSH Connection Refused
В соединении отказано
У вас проблемы с доступом к удаленному серверу через SSH? Если SSH отвечает сообщением «Connection Refused» (Соединение отклонено), возможно, вам придется изменить запрос или проверить настройки.
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Почему при использовании SSH возникает отказ в подключении?
Существует множество причин, по которым вы можете получить ошибку «Connection Refused» при попытке подключения к серверу по SSH. Чтобы решить эту проблему, вам сначала нужно определить, почему система отказалась от вашего подключения через SSH.
Ниже вы найдете некоторые из наиболее распространенных причин, которые могут вызвать отказ в соединении SSH.
Клиент SSH не установлен
Прежде чем устранять другие проблемы, первым делом необходимо проверить, правильно ли установлен SSH. На машине, с которой вы получаете доступ к серверу, должен быть настроен клиент SSH. Без правильной настройки клиента вы не сможете подключиться к серверу.
Чтобы проверить, есть ли в вашей системе клиент SSH, введите в окне терминала следующее:
Если терминал предоставляет список параметров команды ssh, клиент SSH установлен в системе. Однако, если он ответит, что команда не найдена (command not found), вам необходимо установить клиент OpenSSH.
Решение: установить клиент SSH
Чтобы установить клиент SSH на свой компьютер, откройте терминал и выполните одну из команд, перечисленных ниже.
Для систем Ubuntu / Debian:
Для систем CentOS / RHEL:
Демон SSH не установлен на сервере
Так же, как вам нужна клиентская версия SSH для доступа к удаленному серверу, вам нужна версия сервера для прослушивания и приема соединений. Таким образом, сервер может отклонить входящее соединение, если SSH-сервер отсутствует или настройка неверна.
Чтобы проверить, доступен ли SSH на удаленном сервере, выполните команду:
Если на выходе отображается «Connection refused», переходите к установке SSH на сервере.
Решение: установите SSH на удаленный сервер
Чтобы решить проблему отсутствия сервера SSH, установите сервер OpenSSH.
Учетные данные неверны
Опечатки или неправильные учетные данные — частые причины отказа в SSH-соединении. Убедитесь, что вы не ошиблись при вводе имени пользователя или пароля.
Затем проверьте, правильно ли вы используете IP-адрес сервера.
Наконец, убедитесь, что у вас открыт правильный порт SSH. Вы можете проверить, запустив:
На выходе отображается номер порта, как на картинке ниже.
Служба SSH не работает
Служба SSH должна быть включена и работать в фоновом режиме. Если служба не работает, демон SSH не может принимать соединения.
Чтобы проверить статус службы, введите эту команду:
Вывод должен ответить, что служба активна. Если терминал отвечает, что служба не работает, включите его, чтобы решить проблему.
Решение: включить службу SSH
Если система показывает, что демон SSH не активен, вы можете запустить службу, выполнив:
Чтобы служба запускалась при загрузке, выполните команду:
Брандмауэр препятствует подключению SSH
SSH может отклонить соединение из-за ограничений брандмауэра. Брандмауэр защищает сервер от потенциально опасных подключений. Однако, если в системе настроен SSH, необходимо настроить брандмауэр, чтобы разрешить SSH-соединения.
Убедитесь, что брандмауэр не блокирует SSH-соединения, так как это может вызвать ошибку «Connection refused».
Решение: разрешить SSH-подключения через брандмауэр
Чтобы решить проблему, о которой мы упоминали выше, вы можете использовать ufw (Uncomplicated Firewall — несложный брандмауэр), инструмент интерфейса командной строки для управления конфигурацией брандмауэра.
Введите следующую команду в окне терминала, чтобы разрешить SSH-соединения:
Порт SSH закрыт
Когда вы пытаетесь подключиться к удаленному серверу, SSH отправляет запрос на определенный порт. Чтобы принять этот запрос, на сервере должен быть открыт порт SSH.
Если порт закрыт, сервер отказывает в соединении.
По умолчанию SSH использует порт 22. Если вы не вносили никаких изменений в конфигурацию порта, вы можете проверить, прослушивает ли сервер входящие запросы.
Чтобы вывести список всех прослушивающих портов, запустите:
Найдите порт 22 в выходных данных и проверьте, установлено ли для него STATE значение LISTEN .
Кроме того, вы можете проверить, открыт ли конкретный порт, в данном случае порт 22:
Решение: откройте порт SSH
Чтобы разрешить порту 22 слушать запросы, используйте команду iptables :
Вы также можете открывать порты через графический интерфейс, изменив настройки брандмауэра.
Отладка и ведение журнала SSH
Чтобы проанализировать проблемы SSH в Linux, вы можете включить подробный режим или режим отладки. Когда вы включаете этот режим, SSH выдает отладочные сообщения, которые помогают устранять проблемы с подключением, конфигурацией и аутентификацией.
Существует три уровня детализации:
Поэтому вместо доступа к удаленному серверу с использованием синтаксиса ssh [server_ip] добавьте параметр -v и выполните:
В качестве альтернативы вы можете использовать:
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Источник
How to fix: Connection refused by port 22 Debian/Ubuntu
Note: The commands discussed here have been tested on Ubuntu 20.04 LTS. The same commands are also valid for the Debian system.
Fix Connection refused error
This is the “Connection refused” error you might encounter while connecting to a remote system over SSH.
Follow the below solutions step by step in order to solve the “Connection refused” error.
Make sure OpenSSH is installed
One of the reasons you may receive a “Connection refused” error is because the OpenSSH server is not installed on the target server.
First, you will need to make sure that the OpenSSH server is installed on the system which you are trying to access via SSH. In order to check whether OpenSSH is installed or not, issue the following command in the Target server’s Terminal:
This command basically filters the term “openssh-server” from the list of installed packages. If you receive the following similar output, it indicates the OpenSSH server is installed. On the other hand, if you receive no output, it means OpenSSH is missing on the target server.
In case it is not installed on the target server, you can install it using the following command as sudo:
Then type sudo password, and when asked for confirmation, press ‘y’. Once installed, confirm it using the same command
Check SSH service
OpenSSH service runs in the background and listens to incoming connections. The stopped OpenSSH service can be one of the reasons you are receiving a “Connection refused” error.
Therefore, it is necessary to check whether the OpenSSH service is running or not using the following command in Terminal:
If you see the following output, it means the service is active and running in the background.
On the other hand, if you receive inactive (dead), that means the service is not running. You can run the OpenSSH service using the following command as sudo in Terminal:
In order to restart the service, use the following command:
Check SSH server listening port
Another reason for receiving a “Connection refused” error is because you are trying to connect to the wrong port. For instance, if the server is configured to listen on port 2244, and you are trying to connect to its default port 22, then, in this case, you will receive a “Connection refused” error.
Before trying to connect, you need to check the SSH server listening port. If it is the default port (22), then you can connect it using the following command:
If it is some port other than the default port, you will need to connect to the SSH server using this port:
In order to check which on which port the OpenSSH server is listening to; use the following command in Terminal:
You will receive the output similar to the following:
In the third column, you can see the server listening port is 2244. If this is the case, you will need to connect to the SSH server using this port.
Allow SSH in firewall
Firewall blocking the SSH port can be another major reason for the “Connection refused” error. If a firewall is running on the SSH server, you will need to allow the SSH port in it using the following command. Replace the port by the port number the SSH server is listening to:
For instance, if the SSH server is listening to port 2244, then you can allow it in the firewall as:
Reload the firewall using the following command:
In order to confirm if the rules have been added, check the status of the firewall using the following command in Terminal:
The following output shows that the port 2244 is allowed in the firewall.
Resolve Duplicate IP address conflict
The “Connection refused” error can also occur because of duplicate IP address conflict. So, make sure the system does not have a duplicate IP address.
Install the arping utility on your system using the following command:
Then ping the SSH server’s IP address.
In the output, if you see the reply from more than one MAC address, then it shows that there is a duplicate IP running on the system. If this is the case, change the IP address of the SSH server and try connecting again with the new IP address.
This is how to fix the “Connection refused” error by port 22 in Linux systems. In this article, we have described a few ways that will surely help you in solving the “Connection refused” error.
About the author
Karim Buzdar
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.
Источник
How to Fix the SSH “Connection Refused” Error
Secure Shell (SSH) is a key WordPress development tool. It grants advanced users access to key platforms and software that make coding and other tasks easier, faster, and more organized.
So if you attempt to use SSH only to see a “Connection refused” error, you may start to feel concerned. However, this is a common issue, and it’s entirely possible to fix it on your own with just a bit of troubleshooting. You’ll be back to running commands in no time flat.
In this post, we’ll discuss what SSH is and when to use it. Then we’ll explain some common reasons your connection may be refused, including in PuTTY. Finally, we’ll provide some troubleshooting tips.
Prefer to watch the video version?
What Is SSH and When Should I Use It?
Secure Shell (SSH), also sometimes called Secure Socket Shell, is a protocol for securely accessing your site’s server over an unsecured network. In other words, it’s a way to safely log in to your server remotely using your preferred command-line interface:
Using SSH to remotely access a WordPress site hosted on Kinsta
Unlike File Transfer Protocol (FTP), which only enables you to upload, delete, and edit files on your server, SSH can accomplish a wide range of tasks. For instance, if an error locks you out of your WordPress site, you can use SSH to access it remotely.
This protocol also enables you to use several key developer tools, including:
- WP-CLI. The WordPress command line. You can use it for a variety of tasks, including new installations, bulk plugin updates, and media file imports.
- Composer. A PHP package manager. It enables you to implement several frameworks for use in your site’s code by pulling the necessary libraries and dependencies.
- Git. A version control system used to track changes in code. This is especially useful for teams of developers working together on a single project.
- npm. A JavaScript package manager. It includes a command-line and JavaScript software registry. Note: Kinsta customers will need an Enterprise plan in order to access this feature.
It’s important to note that using SSH is an advanced skill. Generally speaking, lay users of WordPress should contact their developers or hosting providers for help, rather than trying to resolve issues with SSH themselves.
A simple mistyped command could ruin your website, so it’s vital that you know what you’re doing.
Why Is My SSH Connection Refused? (5 Reasons for Connectivity Errors)
Unfortunately, there are many scenarios that could occur while you’re trying to connect to your server via SSH, which might result in an error reading “Connection refused”.
Below are some of the most common issues that might be causing problems for you.
1. Your SSH Service Is Down
In order to connect to your server with SSH, it must be running an SSH daemon – a program that runs in the background to listen for and accept connections.
If this service is down, you will not be able to successfully connect to your server and may receive a Connection refused error:
Connection Refused error in Terminal
Your server’s SSH daemon may be down for a wide variety of reasons, including unexpected traffic spikes, resource outages, or even a Distributed Denial of Service (DDoS) attack. In addition to the troubleshooting steps we’ll mention below, you may want to contact your hosting provider to determine the root cause of the issue.
If you suspect that your SSH service might be down, you can run this command to find out:
If the command line returns a status of down, then you’ve likely found the reason behind your connectivity error.
Kinsta is developer-friendly and offers SSH access on all of its hosting plans.
2. You Have the Wrong Credentials
Although it may seem too simple to be true, it’s possible that you’re just entering the wrong credentials when trying to connect to your server. There are four pieces of information needed to run SSH:
- Host name. The IP address of the server you’re trying to connect to or your domain name.
- Username. Your (S)FTP username.
- Password. Your (S)FTP password.
- Port. The default port is 22. However, some hosting providers (including Kinsta) change their SSH port number for security reasons. If this is the case, you should be able to find it by logging in to your MyKinsta dashboard.
You can also check to see which port is being used for SSH by running this command:
The command line should return the correct port.
Check to make sure you’re entering the right credentials and taking into account the possibility of typos or entering the wrong IP address or port.
Sign Up For the Newsletter
Want to know how we increased our traffic over 1000%?
Join 20,000+ others who get our weekly newsletter with insider WordPress tips!
3. The Port You’re Trying to Use Is Closed
A “port” is simply the endpoint to which you’re directed when connecting to your server. In addition to making sure you have the correct one, you’ll also want to check to see if the port you’re trying to use is open.
Any open port is a security vulnerability, as hackers can try to exploit it and gain access to the server. For this reason, unused ports are often closed to prevent attacks.
In the event that port 22, or the custom SSH port for your server, has been closed, you will likely see a Connection refused error. You can see all the ports listening on your server by running this command:
This command should return a list of ports with the LISTEN state. Ideally, you want to see port 22 or your server’s custom SSH port listed here. If it’s not, you’ll need to reopen the port in order to connect to your server.
4. SSH Isn’t Installed on Your Server
As we briefly mentioned earlier, servers use SSH daemons to listen for and accept connections. Therefore, if the server you’re trying to connect to doesn’t have one installed, you won’t be able to access it using SSH.
Generally speaking, almost all hosting providers will have SSH daemons installed on their servers by default. This particular issue is more common on localhost or dedicated servers.
5. Firewall Settings Are Preventing an SSH Connection
Since open ports present a security risk, firewalls installed to protect servers from hackers sometimes block connections to them. Unfortunately, this means that even harmless users who are trying to SSH into their servers may receive a Connection refused error as a result of firewall settings.
If your setup appears to be in order and you still can’t connect, take a look at your firewall’s rules. You can display them in your command-line interface with the following commands:
Need a blazing-fast, secure, and developer-friendly hosting? Kinsta is built with WordPress developers in mind and provides plenty of tools and a powerful dashboard. Check out our plans
Your results will vary, but you’ll want to look for these elements to determine if your firewall is blocking SSH connections:
- dport 22: This refers to the destination port, which for SSH is usually port 22 (reminder: Kinsta doesn’t use this port number).
- REJECT: This would indicate that connections are being refused from the specified destination.
- DROP: Like REJECT, this means that connections to the relevant port are being blocked.
If you search the results of the commands above for dport 22, you should be able to determine if your firewall is preventing an SSH connection. If so, you’ll have to change the rules to accept requests.
Why Does PuTTY Say Connection Refused?
PuTTY is an SSH client. If you’re familiar with FTP, this platform is the FileZilla equivalent to SSH on Windows machines. In other words, PuTTY enables users to input their credentials and launch an SSH connection:
The PuTTY website
If you’re a PuTTY user and see the Connection refused error, the cause is likely one of those listed above.
This is an SSH connectivity error like any other, and the troubleshooting tips below should work whether you’re using PuTTY, Terminal, or any other program for connecting to your server with SSH.
We’ve taken our knowledge of effective website management at scale, and turned it into an ebook and video course. Click here to download the The 2020 Guide to Managing 40+ WordPress Sites!
How Do I Troubleshoot SSH Connectivity Errors?
When you’re experiencing an SSH connectivity error, there are a few steps you can take to troubleshoot it depending on the cause. Here are some tips for troubleshooting the reasons for a Connection refused error that we covered above:
- If your SSH service is down. Contact your hosting provider to see why your SSH service isn’t running. For localhost or dedicated servers, you can use the command sudo service ssh restart to try to get it running again.
- If you entered the wrong credentials. Once you’ve double-checked the SSH port using the grep Port /etc/ssh/sshd_config command, try connecting again with the correct details.
- If your SSH port is closed. This is usually a side effect of one of the two reasons listed below. Either install an SSH daemon on the server you want to connect to or change your firewall rules to accept connections to your SSH port.
- If SSH isn’t installed on your server. 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.
If you’re attempting to connect to your hosting provider’s server, it may be wiser to contact support than to try troubleshooting the problem yourself. Users on localhost or dedicated servers may be able to find further support on more advanced forums if none of the above solutions works.
Summary
Being able to connect to your server with SSH is convenient in a wide range of situations. It can enable you to access your site when you’re locked out of your WordPress dashboard, run commands via WP-CLI, track changes in your site’s code with Git, and more.
Although there are several causes that could be behind your SSH connectivity error, these are a few of the most common:
- Your SSH service is down.
- You have the wrong credentials.
- The port you’re trying to use is closed.
- SSH isn’t installed on your server.
- Firewall settings are preventing an SSH connection.
Save time, costs and maximize site performance with:
- Instant help from WordPress hosting experts, 24/7.
- Cloudflare Enterprise integration.
- Global audience reach with 28 data centers worldwide.
- Optimization with our built-in Application Performance Monitoring.
All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.
Источник