- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Как исправить ошибку SSH Connection Refused
- Почему при использовании SSH возникает отказ в подключении?
- Клиент SSH не установлен
- Демон SSH не установлен на сервере
- Учетные данные неверны
- Служба SSH не работает
- Брандмауэр препятствует подключению SSH
- Порт SSH закрыт
- Отладка и ведение журнала SSH
- How to resolve “localhost connection refused”?
- Possible error messages on Putty or Linux Terminal
- Reasons and Fixes for localhost connection refused
- 1. SSHD Daemon not running
- SSHD does not start?
- 2. Firewall blocking SSH Port
- If using CyberPanel
- 3. Custom SSH Port
- If using CyberPanel
- 4. Incorrect IP, SSH Port or Key File
- Why use CyberPanel?
- connection refused on localhost
- 1 Answer 1
- ssh connection refused
- 7 Answers 7
ИТ База знаний
Курс по 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 и выполните:
В качестве альтернативы вы можете использовать:
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
Источник
How to resolve “localhost connection refused”?
Table of Contents
When on windows you usually use putty to connect to remote SSH servers or terminal when on Linux. While connecting sometimes you can get error such as localhost connection refused on putty or your Linux terminal. Now, this can be very annoying as you can’t get to SSH of your remote server and perform your tasks.
This problem can be from the server or client-side. In this tutorial, we will see probable causes of this error and how to fix them. If you are using our managed vps, then you just have to contact us via ticket or live chat and we should fix this for you.
Let’s continue and see reasons for this error and how to resolve localhost connection refused.
Possible error messages on Putty or Linux Terminal
We will first see possible error messages that you will see.
In putty
Putty Fatal Error
Network Error: Connection Refused
On Linux Terminal
ssh: connect to host 51.xx.xx.xx port 22: Connection timed out
Now the connection to the server is properly routed, but the server is not accepting your connection for many reasons that we will discuss below.
Reasons and Fixes for localhost connection refused
We will now discuss reasons and fixes for this error one by one.
1. SSHD Daemon not running
It is possible that SSHD daemon on your remote server is not running. For SSH to work there is a daemon that works behind the scene and it is called SSHD. If this daemon is not running your server will not be able to accept SSH incoming connections. Check if this service is running or not:
If it is not running you can turn it on:
SSHD does not start?
Now for some reasons if your SSHD daemon still won’t start make sure you have enough disk space using:
If you have enough space you can see if your server is receiving heavy traffic or if the server is under heavy load. You can hire our managed vps service as well we offer 3 days free trial (no credit card required)
2. Firewall blocking SSH Port
Most of the time there is some firewall blocking the SSH port. First, see if you can telnet to SSH port 22
Then check if you or user IP is blocked on IP Tables firewall
If IP is listed, you need to unblock this IP to restore connectivity to SSH port 22. There is also a possibility that firewall has dropped or reject rule for SSH port 22, you need to remove that rule and add run following command:
iptables -A input -p tcp –dport 22 -j ACCEPT
If using CyberPanel
If you are using CyberPanel it comes with Firewalld by default unless you have installed CSF. You can go to :8090/firewall/ by default port 22 is opened, if not you can add port 22 there.
If you have installed CSF with CyberPanel, you can use csf.allow file to allow this IP. The file is located at
Then turn off and turn on CSF again from CyberPanel interface.
3. Custom SSH Port
If you have defined a custom port for SSH (for security reasons, because standard SSH ports are prone to brute force attacks). Then you need to open that port on the firewall as well. Because firewall doesn’t know you choose a custom port for SSH.
First, confirm if you are using custom port using
cat /etc/sshd_sshd_config | grep Port
If you see something other then port 22, you need to fix it.
iptables -A input -p tcp –dport custom_port_here -j ACCEPT
Replace with custom port here.
If using CyberPanel
Go here :8090/firewall/secureSSH and see if you have set custom ssh port. Normally if you set custom SSH port, CyberPanel will open this port for you on the firewall. But if it still does not work, you can open this port manually by going to :8090/firewall/ or here :8090/firewall/csf if you are using CSF.
4. Incorrect IP, SSH Port or Key File
It is also possible that you did a human error and used incorrect IP or wrong SSH port. Make sure you are using right IP on putty or Linux terminal along with the correct SSH port.
Sometimes people also use key-based authentication, and they get issues while connecting to SSH if the wrong private key is used or there are wrong permissions on your SSH private key. On your local server make sure that your private key has the permission of 600.
Why use CyberPanel?
We’ve discussed many reasons and fixes for localhost connection refused error. But we recommend that you install CyberPanel on your VPS, it will help you solve many issues and if you are hosting sites then you will get super speed as well because CyberPanel is based on OpenLiteSpeed and LiteSpeed Enterprise.
You will get easy access to Firewalld (installed by default) where you can easily open/close any ports at your wish. Or you can also install CSF too.
If you are a very novice user you can also hire our managed vps service, we are super affordable and provide top-notch support to all our customers. You can start with 3 days trial (no credit card required at all).
Источник
connection refused on localhost
On CentOS 7 I am trying to open connections to some services in my localhost using both HTTP and direct TCP/UDP (web server, db, etc) but I keep getting connection refused on ports that are not 8080 or 80 . (ps: ssh to port 22 works fine btw).
Here is what I tried so far:
I checked selinux status.
Then I checked for firewalls
So if it’s not selinux nor firewalls, what should I look for?
Here is what netcat output is (notice that works fine on 8080 and 80) Note: the ^C is just to indicate the interrupt signal because nc has connected
ss -vtnlp | grep :5544 don’t give me anything either (and my service on the other side keeps getting connection refused).
Thanks for any help!
1 Answer 1
It turns out that the service that was supposed to listen for the connections were not listening! After moving the service to a much higher port it’s now working, however I don’t know why that would be the case.. (the below is truncated)
Maybe this helps others:
the major indicator (which I totally missed) was that the ss -tnlp command was not listing the port that I was expecting to be listend to.
Also when doing ss -tnlp | grep :port the result was empty and that actually meant the port wasn’t «open for connections» thus the connection refused error message.
In my case the process was logstash which didn’t throw out a single error about not being able to listen to the port.
Источник
ssh connection refused
Hi I’m having a problem with my ssh, which is magically stopped working and I couldn’t figure out why. The message it give is:
I don’t see any error messages when I write dmesg but I’m getting following from telnet localhost 22
I tried the solutions that I saw in some similar cases [1] and [2] but it still didn’t solve my problem the entries and outputs are as follows:
Note that this was already ACCEPT I didn’t had any problem even before entering the command sudo iptables -A INPUT -p tcp —dport ssh -j ACCEPT . I also tried to reboot ssh but it didn’t change anything
I don’t know what else to try so hope this is enough to solve the problem.
Rest is added after @Ashu’s comment
Eddited after @TheSchwa’s comment
7 Answers 7
I first tried to remove and reinstall ssh but it didn’t work for me then I tried to purge it:
so now its working.
TCP error «Connection refused» means that there is a host active on this IP address but the port you were trying to connect to (22 for ssh) is not open.
First of all double check your host name and/or IP address.
The most likely reason is either somebody stopped the ssh daemon or somebody configured it to use an alternative port instead of the default 22.
If you have physical access to your server logon to that server and type in command sudo netstat -tupan . Ideally you should see a line like:
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1053/sshd
If you don’t try starting sshd and/or checking whether it is configured to listen on port 22.
EDIT
The bits to focus on are:
LISTEN — there is a process running and expecting incoming connections on port 22
sshd — the name of the process.
If you can’t see a line like that then perhaps your ssh server is badly configured and fails to start. Try this page for instructions how to run it in the foreground and troubleshoot it.
Источник