- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Как исправить ошибку SSH Connection Refused
- Почему при использовании SSH возникает отказ в подключении?
- Клиент SSH не установлен
- Демон SSH не установлен на сервере
- Учетные данные неверны
- Служба SSH не работает
- Брандмауэр препятствует подключению SSH
- Порт SSH закрыт
- Отладка и ведение журнала SSH
- Socket.Connection refused on linux and osx #923
- Comments
- dv00d00 commented Jul 19, 2018
- Related fact
- davidsh commented Jul 19, 2018
- wfurt commented Jul 19, 2018
- wfurt commented Jul 19, 2018
- dv00d00 commented Jul 20, 2018
- wfurt commented Sep 19, 2018
- Krummelz commented Sep 2, 2019 •
- wfurt commented Sep 2, 2019
- karelz commented Sep 9, 2019
- vindicatorr commented Jun 15, 2020
- tmds commented Jun 25, 2020 •
- Facing an error «System.Net.Sockets.SocketException : Connection refused» on Linux with .Net Core 2.2 #28791
- Comments
- jaydeept commented Feb 26, 2019
- Random «Connection refused» on Linux #2198
- Comments
- paulius-m commented Oct 19, 2018 •
- paulius-m commented Oct 19, 2018 •
- roji commented Oct 20, 2018
- paulius-m commented Oct 20, 2018
- roji commented Oct 21, 2018
- paulius-m commented Oct 22, 2018
- roji commented Nov 17, 2018
- AntonyCook commented Jan 17, 2019
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Как исправить ошибку SSH Connection Refused
В соединении отказано
У вас проблемы с доступом к удаленному серверу через SSH? Если SSH отвечает сообщением «Connection Refused» (Соединение отклонено), возможно, вам придется изменить запрос или проверить настройки.
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
Почему при использовании 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 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Источник
Socket.Connection refused on linux and osx #923
Comments
dv00d00 commented Jul 19, 2018
Not sure if it is a bug but this code works perfectly fine on windows:
but fails on linux
dotnet version: 2.1.302
Related fact
The text was updated successfully, but these errors were encountered:
davidsh commented Jul 19, 2018
wfurt commented Jul 19, 2018
Do you have anything listening on that port @dv00d00 ?
You may run tcpdump -ni lo port 12345 (or strace)
wfurt commented Jul 19, 2018
It seems like the error is coming from OS:
When sending data locally, kernel can probably detect that port is closed and the sendmsg() call fails. That does not looks like problem with the runtime, more difference in how OS handle I/O.
dv00d00 commented Jul 20, 2018
On the other hand
works without throwing exceptions. I don’t believe anything is on that specific port, this was happening on a travis CI machine, but the same happened on my mac.
wfurt commented Sep 19, 2018
I did more testing with C and C# as well as I looked at Linux kernel code.
This seems to be way how Unix works. when sendto() is used, individual chunks of data are submitted independently and the call succeeds as long as there is space in socket buffer.
Since UDP is unreliable, this is has nothing to do with actual delivery.
I did also packet capture for both calls. In both cases I see:
When sendmsg() is trying to send data following happens: first message goes out without error.
When the ICMP error get’s back it is remembered on «connection» (internal socket structure)
Subsequent sendmsg() calls fail.
Since this is OS behavior, I don’t think it make sense to hide underlying error.
It seems that raising exception and allowing caller to deal with it is better approach.
I’m proposing to close this unless somebody objects. cc: @karelz
(note that linked PR does not change this behavior)
Krummelz commented Sep 2, 2019 •
Hi all, please take a look at this same issue over on the NpgSql repo — npgsql/npgsql#2198. I’m experiencing the same thing. And their code is using the same Socket class to make the connections. You can look at the relevant Connect method code here: https://github.com/npgsql/npgsql/blob/91d23f90ef00eadc7c07966833959a5b3f877127/src/Npgsql/NpgsqlConnector.cs#L642.
«System.Net.Sockets.SocketException (111): Connection refused» error,
at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
I’ve run tcpdump -ni lo port 5432 , and I get the following:
wfurt commented Sep 2, 2019
From the dump it is clear that the port you trying to connect to is not listening and sends back RST. It is correct to throw.
Also note that this issue is about UDP.
karelz commented Sep 9, 2019
Triage: We need to understand why Send and SendTo behave differently.
We need either doc change, or product change, or test added.
vindicatorr commented Jun 15, 2020
I’m only just now getting into this as well and it looks like SCM_RIGHTS is going to be key:
Send or receive a set of open file descriptors from another process. The data portion contains an integer array of the file descriptors. (unix.7)
https://stackoverflow.com/questions/28003921/sending-file-descriptor-by-linux-socket/
tmds commented Jun 25, 2020 •
This issue is unrelated to SCM_RIGHTS .
On Linux, Socket.Send throws a SocketException if there is no peer, while on Windows it does not.
Windows WSASend documentation suggests it could do the same thing:
WSAECONNRESET | For a stream socket, the virtual circuit was reset by the remote side. The application should close the socket as it is no longer usable. For a UDP datagram socket, this error would indicate that a previous send operation resulted in an ICMP «Port Unreachable» message.
— | —
Maybe this error is only generated for non-localhost communication on Windows?
You can add an extension method if you always want to ignore the error, and avoid the cost of throwing (and catching) Exceptions for it.
Источник
Facing an error «System.Net.Sockets.SocketException : Connection refused» on Linux with .Net Core 2.2 #28791
Comments
jaydeept commented Feb 26, 2019
I am facing an issue on Linux OS with .Net Core 2.2 , while executing some integration test cases. Here is the stacktrace:
Failed mytest()
Error Message:
System.Net.WebException : Failed after 5 retries
—-> System.Net.WebException : Connection refused Connection refused
—-> System.Net.Http.HttpRequestException : Connection refused
—-> System.Net.Sockets.SocketException : Connection refused
Stack Trace:
WebApiClient.cs:line 56
WebApiClient.cs:line 34
at PdsWebAppTests.ClientForTestPdsWebApp.Call(Method method, String url, String requestContent, WebClientHeaders headers) in ClientForTestPdsWebApp.cs:line 19
at IntegrationTests.IntegrationTests 1.mytest() in IntegrationTests.cs:line 44 —WebException at System.Net.HttpWebRequest.GetResponse() at WebApiClient.GetResponse(WebRequest webRequest) in WebApiClient.cs:line 117 at WebApiClient.ReceiveResponse(WebRequest webRequest) in WebApiClient.cs:line 97 CallWithRetries(Method method, String uriString, String requestContent, WebClientHeaders headers, Int32 retryCount) in WebApiClient.cs:line 46 —HttpRequestException at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask 1.get_Result()
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask 1.get_Result() at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask 1 creationTask)
at System.Threading.Tasks.ValueTask 1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task 1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at System.Net.HttpWebRequest.SendRequest()
at System.Net.HttpWebRequest.GetResponse()
—SocketException
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
Here is my high-level code flow:
P.S.
This test case is working fine in Windows. Also from Linux machine, I am able to launch my web app and able perform all operations so I think it’s just WebRequest.GetResponse() which is throwing an exception.
The text was updated successfully, but these errors were encountered:
Источник
Random «Connection refused» on Linux #2198
Comments
paulius-m commented Oct 19, 2018 •
Hello,
we experience random SocketExceptions on all Linux VMs with pgBouncer:
We use host=localhost , and tracing shows that error is related to [::1], because issue is not encountered then using host=127.0.0.1 .
USUAL TRACE:
TRACE Opening connection.
TRACE Opening connection.
TRACE Attempting to connect to [::1]:6543
TRACE Failed to connect to [::1]:6543
TRACE Attempting to connect to 127.0.0.1:6543
TRACE Socket connected to localhost:6543
TRACE Authenticating.
RANDOM ERROR:
TRACE Opening connection.
TRACE Opening connection.
TRACE Attempting to connect to [::1]:6543
ERROR Breaking connector
TRACE Cleaning up connector
TRACE Closing connector
TRUE CONNECTION REFUSED (port not open):
TRACE Opening connection.
TRACE Opening connection.
TRACE Attempting to connect to [::1]:6543
TRACE Failed to connect to [::1]:6543
TRACE Attempting to connect to 127.0.0.1:6543
TRACE Failed to connect to 127.0.0.1:6543
ERROR Breaking connector
TRACE Cleaning up connector
TRACE Closing connector
Maybe, possible solution would be to move this line into try block below.
var connectTask = Task . Factory . FromAsync ( socket . BeginConnect , socket . EndConnect , endpoint , null ); |
The text was updated successfully, but these errors were encountered:
paulius-m commented Oct 19, 2018 •
roji commented Oct 20, 2018
This is a low-level networking connection error, which likely has nothing to do with Npgsql really. It could be happening because the server (either PostgreSQL or pgBouncer) simply isn’t up and listening yet when the client attempts to connect.
Am going to keep this open for any further details but it really is unlikely that Npgsql is related here — it’s simply trying to establish a TCP connection to the IP and port you give it.
paulius-m commented Oct 20, 2018
Error happens then pgbouncer is running, at random moments. PgBouncer log does not contain any errors.
In normal case, Npgsql tries ::1, then 127.0.0.1.
Secondly, error does not manifest if non async Open is used.
shouldn’t Npgsql try all IPs from dns and fail at the end?
roji commented Oct 21, 2018
shouldn’t Npgsql try all IPs from dns and fail at the end?
The current behavior is to go through all IPs only in the case of timeouts, not other errors (such as connection refused), the relevant code is here. I’m not sure why the error would occur only in async and not in sync though.
Have you tried making pgbouncer listen to the IPv6 address (::1)?
paulius-m commented Oct 22, 2018
It works without issue then pgBouncer listens on localhost.
Strangely, our configuration listens on 127.0.0.1 🙂
We will change our configs for pgBouncer.
roji commented Nov 17, 2018
Am going to close this as there doesn’t seem to be anything actionable in Npgsql, but can reopen if otherwise.
AntonyCook commented Jan 17, 2019
We’ve just hit a similar issue in our environments after upgradring from Net Core 2.0 to Net Core 2.2 using EF core (it possibly started with 2.1 tho)
We’re deploying into GKE using the cloud sql proxy and connecting on localhost to cloud sql. Under the 2.0 docker containers with 2.0 targgeted solution we had no problems.
When we moved to 2.2 containers and targetting 2.2 we instantly began to get Connection Refused errors but only after a period of inactivity. Restarting the pods or keeping the service excerised, no problems at all. leave the service quiet and allow the connection to be closed, then the next request would lead to repeated connection refused.
I saw references to both ::1 and 127.0.0.1 in the logs and figured it was actually the connection to the IPV6 address that was failing as the service did eventually get a connection and this was against 127.0.0.1. Although the service regained its connection the website had timed out by then.
I changed my connection string to use 127.0.0.1 instead of localhost and that seems to work around the problem.
Источник