Remote side unexpectedly closed network connection putty windows

Putty 'Server unexpectedly closed network connection' I have been getting the 'Server unexpectedly closed network connection' (see https://superuser.com/questions/735824/putty-ends-to-an-unexpected...

A PuTTY session left idle will disconnect at a time determined by the host server. Try enabling keep-alives in PuTTY. This causes PuTTY to send null SSH packets to the remote host periodically, preventing the session from timing out.

The PuTTY client can be configured to always establish a connection which will not time out due to inactivity. To create and save a new keep-alive connection, follow these steps:

  1. Open the PuTTY application, and go to the Options panel (labeled «Category») on the left of the window.
  2. Select (click) the «Connection» item.
  3. In the ​​»Sending of null packets to keep the session active» area on the right, change the default value of «Seconds between keepalives» from 0 (turn off) to 1800 (30 minutes).
  4. Select the «Enable TCP keepalives (SO_KEEPALIVE option)» check box.
    Note: This option may not be available in older versions of the PuTTY client.
  5. On the topmost left side of the Options panel, select (click) «Session».
  6. In the «Host Name (or IP Address)» field, enter the destination host name or IP address (e.g., «destination.ipaddress.here.com» or «192.168.1.1»).
  7. In the «Saved Sessions» text-entry box, provide a name for the session (e.g., «savedsession»).
  8. Select «Save».

To use the modified session settings, select it from the «Saved sessions» list, then click the buttons marked «Load» and «Open».

If your connected sessions still time out, enter a lower number of seconds into the «Seconds between keepalives» value.

answered Oct 15, 2014 at 7:20

afrab_null's user avatar

3

The server could have been hardened. The reason could be a) the client ip may be not configured in /etc/allowhosts and/or b) unix/linux firewall rule/selinux is not permitting.

answered Nov 9, 2018 at 7:49

AVA's user avatar

I had the same problem for a long time, I use putty to connect to AWS linux instances (some remote cloud servers)
I read about fixing it with keepAlives in several pages several pages, tried it but to no avail.

And just yesterday, while looking for some color scheme settings I found this:
https://github.com/jblaine/solarized-and-modern-putty

Besides adjusting the colors of the terminal it does apply some sane defaults (Like the forementioned KeepAlives to 59 seconds plus others), and guess what? I havent had any closed connection for two whole days.

answered May 27, 2016 at 2:08

Mario Chapa's user avatar

I tried everything above and nothing worked until this

vi /etc/ssh/sshd_config
ClientAliveInterval 60
restart deamon sshd

also switched to kitty an alternative putty clone which is much better

Ramhound's user avatar

Ramhound

40.3k34 gold badges100 silver badges127 bronze badges

answered Nov 10, 2020 at 21:32

Amarpreet 's user avatar

1

You were idle longer than the session timeout on the remote device, so it closed the session and PuTTy wasn’t expecting it.

answered Oct 15, 2014 at 5:50

cpt_fink's user avatar

cpt_finkcpt_fink

3852 silver badges8 bronze badges

3

To create and save a new keep-alive connection, follow these steps:

  • Open the PuTTY application, and go to the Options panel (labeled «Category») on the left of the window.
  • Select (click) the «Connection» item.
  • In the ​​»Sending of null packets to keep the session active» area on the right, change the default value of «Seconds between keepalives» from 0 (turn off) to 1800 (30 minutes).
  • Select the «Enable TCP keepalives (SO_KEEPALIVE option)» check box. Note: This option may not be available in older versions of the PuTTY client.
  • On the topmost left side of the Options panel, select (click) «Session».
  • In the «Host Name (or IP Address)» field, enter the destination host name or IP address (e.g., «destination.ipaddress.here.com» or «192.168.1.1»).
  • In the «Saved Sessions» text-entry box, provide a name for the session (e.g., «savedsession»).
  • Select «Save».

To use the modified session settings, select it from the «Saved sessions» list, then click the buttons marked «Load» and «Open».

If your connected sessions still time out, enter a lower number of seconds into the «Seconds between keepalives» value.

On searching more I also got a point that:

«Uncheck ‘Attempt GSSAPI authentication (SSH-2 only)’ in Putty: Category — Connection — SSH — Auth — GSSAPI

In my case it seems to be GSSAPI is incompatible to a Ubuntu host that uses Beyond trust (formerly: likewise open).»

Есть docker ubuntu 18.04.3 LTS (GNU/Linux 4.2.8 armv71). Когда подключился через putty к ssh серверу, проходит секунд 10-15 и появляется ошибка «remote side unexpectedly closed network connection».

5e08b92ce94af328515702.png

Смотрю на сервере командой sudo ssh status, ssh не рабочий(:

5e08b94d02dcd030270472.png

Помогает команда sudo /etc/init.d/ssh restart

После этой команды, вроде все норм:

5e08b95fc3d41513624625.png

Если докер перегрузить, сервер работает, но после первого подключения по ssh все повторяется:-(

Вывод команды #journalctl -u ssh, и ее последний результат:

Dec 29 15:32:46 ubuntu-bionic-armhf-1 systemd[1]: Started OpenBSD Secure Shell server.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Main process exited, code=killed, status=9/KILL
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Failed with result ‘signal’.

Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Service hold-off time over, scheduling restart.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Scheduled restart job, restart counter is at 4.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: Stopped OpenBSD Secure Shell server.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: Starting OpenBSD Secure Shell server…
Dec 29 15:33:17 ubuntu-bionic-armhf-1 sshd[454]: Server listening on 0.0.0.0 port 2222.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 sshd[454]: Server listening on :: port 2222.
Dec 29 15:33:17 ubuntu-bionic-armhf-1 systemd[1]: Started OpenBSD Secure Shell server.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Main process exited, code=killed, status=9/KILL
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Failed with result ‘signal’.

Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Service hold-off time over, scheduling restart.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: ssh.service: Scheduled restart job, restart counter is at 5.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: Stopped OpenBSD Secure Shell server.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: Starting OpenBSD Secure Shell server…
Dec 29 15:33:49 ubuntu-bionic-armhf-1 sshd[456]: Server listening on 0.0.0.0 port 2222.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 sshd[456]: Server listening on :: port 2222.
Dec 29 15:33:49 ubuntu-bionic-armhf-1 systemd[1]: Started OpenBSD Secure Shell serv

По совету @pfg21 пробовал в /etc/ssh/sshd_config на сервере следующие параметры
TCPKeepAlive yes
ClientAliveInterval 60
ClientAliveCountMax 360
не помогает….

Как решить эту проблему, чтобы sshd не падал и стабильно работал. Спасибо!

26 мая, 2017 12:02 пп
14 117 views
| Комментариев нет

Linux, SSH, VPS

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

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

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

После успешного подключения протокол SSH согласовывает зашифрованное соединение с клиентом на основе установления доверия. Есть несколько уникальных проблем, которые могут возникнуть на этом этапе. В этом мануале рассматриваются способы их определения, устранения и предотвращения.

Требования

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

Общие ошибки

Ошибка при проверке ключа хоста

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

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
...
В PuTTY предупреждение выглядит так:
WARNING - POTENTIAL SECURITY BREACH!
The server's host key does not match the one PuTTY has
cached in the registry. This means that either the
Server administrator has changed the host key, or you
...

Обычно причиной этой ошибки является:

  • Восстановление сервера с помощью снапшота или резервной копии.
  • Перенос плавающего IP на другой сервер.
  • Переустановка SSH-сервера с помощью менеджера пакетов

Чтобы решить эту проблему, вы можете очистить ключи хоста.

Соединение закрыто или сброшено

Иногда соединения устанавливаются на уровне сокета, но сбрасываются во время проверки ключей хоста. В PuTTY эта ошибка выглядит так:

Server Unexpectedly closed network connection

Клиент OpenSSH выдаёт такую ошибку:

Connection closed by 111.111.111.111 port 22

Эта ошибка, как правило, происходит по следующим причинам:

  • Сбой или ошибки сервиса SSH.
  • Сервис SSH не может инициализировать подключение из-за отсутствия ключей хоста сервера.

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

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

Ошибки переговоров с хостом

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

Couldn't agree a client-to-server cipher (available: aes128-ctr, aes192-ctr, aes256-ctr)

Клиент OpenSSH сообщит:

Unable to negotiate with 111.111.111.111: no matching key exchange method found.
Their offer: diffie-hellman-group1-sha1

Источником этой ошибки может быть:

  • Несовпадение реализаций клиента и хоста (если вы используете современный клиент OpenSSH и устаревший хост, последний может просто не поддерживать шифрования клиента).
  • Изменение списка шифрования клиента SSH (возможно, сервер его не поддерживает).

Чтобы решить эту проблему, вам необходимо правильно настроить шифрование на SSH-клиенте.

Устранение неполадок

Сброс ключей известных хостов

Ключи хоста обычно хранятся в файле ~/.ssh/known_hosts клиента OpenSSH. PuTTY обычно хранит их в реестре Windows (HKEY_CURRENT_USERSoftwareSimonTathamPuTTYSshHostKeys).

В PuTTY можно использовать диалоговое окно, чтобы разрешить подключение и обновить реестр (просто выберите Yes). Кроме того, вы можете удалить запись вручную.

На клиенте OpenSSH вы можете найти записи хоста в файле ~/.ssh/known_hosts и удалить их вручную. Также можно использовать команду ssh-keygen.

ssh-keygen -R your_server_ip

Команда попытается получить доступ и очистить соответствующую запись хоста в файле known_hosts:

# Host 111.111.111.111 found: line 2
/home/user/.ssh/known_hosts updated.
Original contents retained as /home/user/.ssh/known_hosts.old

После этого попробуйте снова подключиться к серверу.

Проверка и генерирование SSH-ключей

Если у хоста SSH нет собственного закрытого ключа и он не может сгенерировать общий секретный ключ, соединение будет сброшено. Откройте каталог /etc/ssh и попробуйте найти в нём группу файлов с именами sshd_host_*_key. Среди них должен быть файлы с расширением .pub.

Если таких файлов нет, сгенерируйте их с помощью команды ssh-keygen.

ssh-keygen -A

Команда выведет сгенерированные ключи:

ssh-keygen: generating new host keys: RSA DSA ECDSA ED25519

Теперь попробуйте снова подключиться к серверу.

Настройка поддерживаемых шифров SSH

Вы можете настроить поддерживаемые SSH-шифры на клиентской машине, если нужна поддержка устаревшего шифрования (например, SHA1). Это не очень распространенная проблема; обычно она случается, если вы используете новый клиент SSH для подключения к устаревшему SSH-серверу, и они поддерживают разные шифры.

В OpenSSH поддержку SHA1 можно настроить с помощью опции KexAlgorithms. Введите в командную строку:

openssh -oKexAlgorithms=+diffie-hellman-group1-sha1 root@your_server_ip

Клиент PuTTY должен поддерживать группу Диффи-Хеллмана (Connection → SSH → Kex).

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

Tags: OpenSSH, PuTTY, SSH

Does this error occur while you are connecting to your instance? If yes, then don’t worry, we will help you resolve it. Read this blog to know how you can resolve this error like a pro!

If you are connecting to your instance with Putty and receive the error “Server unexpectedly closed network connection”, then you can resolve it with two solutions and we are going to discuss these two solutions in this blog.

This is the error –

network error

If this error message appears, there is possibility that

  1. You are not using the correct username when connecting to your instance
  2. You are not using the correct key when connecting to your instance”
  3. PuTTy options –> Connection problem
  4. You have accidentally applied Chmod 777 on the root folder

Since it might be an SSH issue, we have found the following link on troubleshooting problems which will help you in connecting to your instance: https://aws.amazon.com/premiumsupport/knowledge-center/ec2-linux-ssh-troubleshooting/

You can try connecting again by entering your correct username because it is possible that you entered the wrong username before. Try this and see if it works.

Just like this, try connecting again by entering the correct key and see if it works.

If both of these don’t work, then you need to try these two solutions for connecting to your instance. Let’s see what these solutions are and how they work.

SOLUTIONS 1

Here is the first solution for you that can help you resolve this error

Go to PuTTy options –> Connection

  1. Change the default value for “Seconds between keepalives(0 to turn off)”: from 0 to 600 (10 minutes) — in my case taking 30 seconds That means it sends a “ping” every 30 seconds to prevent the connection from timing out
  2. Check the “Enable TCP_keepalives (SO_KEEPALIVE option)” check box.
  3. Finally, save the setting for the session

Youtube Video – https://www.youtube.com/watch?v=cFP4AsxvwNQ&feature=youtu.be

resolve error

SOLUTIONS 2

Here is the 2nd solution to resolve this error

It might be possible that you have put Chmod 777 to remove chmod 777 permission on the root folder.

If you just want to remove the write permission to others, the command is given below and it has to be done from the root folder: chmod o-w /

This will remove others’ permission from / (root folder)

* o means others. * w means write permissions.

So o-w means remove written permission from others. You can also read online to know how this exactly works and how the permissions can be updated for Linux.

Here are some of the references to Forums and documents:

— https://forums.aws.amazon.com/thread.jspa?threadID=60938 — https://forums.aws.amazon.com/thread.jspa?threadID=212950 — https://forums.aws.amazon.com/thread.jspa?threadID=56946

Whenever the such error appears, these two solutions can be helpful for you to resolve the error and you will able to connect to your instance easily. So, if you come across this error, follow these two solutions and say goodbye to the error in a few minutes.

We hope you resolve this error successfully with the help of this blog. (Metizsoft Solutions Private Limited)

Read More:

How to disable TLS 1.0 in the windows server?

AboutManthan Bhavsar

Manthan Bhavsar is one of the most brilliant go-to people when someone thinks to Hire Shopify Certified Experts! A techie by profession and a technologically driven person by passion, Manthan Bhavsar isn’t shy to blog and share the knowledge he has with the world. If you want to follow Manthan, you can do so on Facebook, Twitter, and LinkedIn

Понравилась статья? Поделить с друзьями:
  • Remote server administrator tools windows 7
  • Remote server administration tools rsat for windows 7
  • Remote server administration tools for windows server 2019
  • Remote server administration tools for windows 7 x64 скачать
  • Remote server administration tools for windows 7 sp1