удалённый SSH

Настройка, программирование, распределённые вычисления

Модераторы: Olej, bellic, vikos

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

удалённый SSH

Непрочитанное сообщение Olej » 19 июл 2019, 15:46

Про удалённые сессии SSH, в основном, всё ясно...
Но мне так часто приходится работать над проектами заказчика в SSH терминальной сессии (часто когда хост заказчика находится в Израиле или Великобритании), что накопилось очень много полезных мелочей относительно использования SSH.
И об этом раз за разом, время от времени, спрашивают...
Собираю всё под одну крышу для памятки!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 19 июл 2019, 15:55

Q: К удалённому компьютеру не удаётся подключиться по SSH.
A; Проверить что на этом компьютере вообще запущен сервис (сервер, демон) SSH:

Код: Выделить всё

olej@ACER:~$ ps -A | grep sshd
  799 ?        00:00:00 sshd

Код: Выделить всё

olej@ACER:~$ systemctl status sshd
● ssh.service - OpenBSD Secure Shell server
   Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2019-07-19 15:00:14 EEST; 47min ago
     Docs: man:sshd(8)
           man:sshd_config(5)
  Process: 753 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
 Main PID: 799 (sshd)
    Tasks: 1 (limit: 4915)
   Memory: 2.3M
   CGroup: /system.slice/ssh.service
           └─799 /usr/sbin/sshd -D

июл 19 15:00:14 ACER systemd[1]: Starting OpenBSD Secure Shell server...
июл 19 15:00:14 ACER sshd[799]: Server listening on 0.0.0.0 port 22.
июл 19 15:00:14 ACER sshd[799]: Server listening on :: port 22.
июл 19 15:00:14 ACER systemd[1]: Started OpenBSD Secure Shell server.
Остановить/запустить сервис:

Код: Выделить всё

root@ACER:~# systemctl stop sshd
root@ACER:~# ps -A | grep sshd

Код: Выделить всё

root@ACER:~# systemctl start sshd
root@ACER:~# ps -A | grep sshd
 5873 ?        00:00:00 sshd
Запретить/разрешить автостарт демона SSH при загрузке системы:

Код: Выделить всё

root@ACER:~# systemctl disable sshd
Removed /etc/systemd/system/sshd.service.
Removed /etc/systemd/system/multi-user.target.wants/ssh.service.

Код: Выделить всё

root@ACER:~# systemctl enable ssh
Synchronizing state of ssh.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable ssh
Created symlink /etc/systemd/system/sshd.service → /lib/systemd/system/ssh.service.
Created symlink /etc/systemd/system/multi-user.target.wants/ssh.service → /lib/systemd/system/ssh.service.
Обращаем внимание на запись параметра команды.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 19 июл 2019, 16:21

Q: Соединение начинается, но обрывается при аутентификации (при вводе пароля).
A: Запускать ssh с отладочным выводом (-v или -vv):

Код: Выделить всё

olej@ACER:~$ ssh olej@192.168.1.107 -vv
OpenSSH_7.9p1 Debian-10, OpenSSL 1.1.1c  28 May 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolve_canonicalize: hostname 192.168.1.107 is address
debug2: ssh_connect_direct
debug1: Connecting to 192.168.1.107 [192.168.1.107] port 22.
debug1: Connection established.
debug1: identity file /home/olej/.ssh/id_rsa type -1
debug1: identity file /home/olej/.ssh/id_rsa-cert type -1
debug1: identity file /home/olej/.ssh/id_dsa type -1
debug1: identity file /home/olej/.ssh/id_dsa-cert type -1
debug1: identity file /home/olej/.ssh/id_ecdsa type -1
debug1: identity file /home/olej/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/olej/.ssh/id_ed25519 type -1
debug1: identity file /home/olej/.ssh/id_ed25519-cert type -1
debug1: identity file /home/olej/.ssh/id_xmss type -1
debug1: identity file /home/olej/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9p1 Debian-10
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u6astra6
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u6astra6 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 192.168.1.107:22 as 'olej'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: grasshopper-ctr,chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,grasshopper-cbc,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: grasshopper-ctr,chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,grasshopper-cbc,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: hmac-gost2012-256-etm,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: hmac-gost2012-256-etm,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:xuX038BUNFB8LfjIgw/M4mpxw01FfPmdRJ3TY2KC2kI
The authenticity of host '192.168.1.107 (192.168.1.107)' can't be established.
ECDSA key fingerprint is SHA256:xuX038BUNFB8LfjIgw/M4mpxw01FfPmdRJ3TY2KC2kI.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added '192.168.1.107' (ECDSA) to the list of known hosts.
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Will attempt key: /home/olej/.ssh/id_rsa 
debug1: Will attempt key: /home/olej/.ssh/id_dsa 
debug1: Will attempt key: /home/olej/.ssh/id_ecdsa 
debug1: Will attempt key: /home/olej/.ssh/id_ed25519 
debug1: Will attempt key: /home/olej/.ssh/id_xmss 
debug2: pubkey_prepare: done
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/olej/.ssh/id_rsa
debug1: Trying private key: /home/olej/.ssh/id_dsa
debug1: Trying private key: /home/olej/.ssh/id_ecdsa
debug1: Trying private key: /home/olej/.ssh/id_ed25519
debug1: Trying private key: /home/olej/.ssh/id_xmss
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
olej@192.168.1.107's password: 
debug2: we sent a password packet, wait for reply
debug1: Authentications that can continue: publickey,password
Permission denied, please try again.
olej@192.168.1.107's password: 
debug2: we sent a password packet, wait for reply
debug1: Authentication succeeded (password).
Authenticated to 192.168.1.107 ([192.168.1.107]:22).
debug1: channel 0: new [client-session]
debug2: channel 0: send open
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug2: channel_input_open_confirmation: channel 0: callback start
debug2: fd 3 setting TCP_NODELAY
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug1: Sending environment.
debug1: Sending env LANG = ru_RU.UTF-8
debug2: channel 0: request env confirm 0
debug2: channel 0: request shell confirm 1
debug2: channel_input_open_confirmation: channel 0: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0
You have new mail.
Last login: Fri Jul 19 15:01:57 2019

Проверяем где мы есть:

Код: Выделить всё

olej@astra:~$ uname -a
Linux astra 4.19.0-1-generic #astra1 SMP Wed Mar 20 12:59:21 UTC 2019 x86_64 GNU/Linux
Завершаем сессию SSH:

Код: Выделить всё

olej@astra:~$ exit
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug2: channel 0: rcvd eow
debug2: channel 0: chan_shutdown_read (i0 o0 sock -1 wfd 4 efd 6 [write])
debug2: channel 0: input open -> closed

выход
debug2: channel 0: rcvd eof
debug2: channel 0: output open -> drain
debug2: channel 0: obuf empty
debug2: channel 0: chan_shutdown_write (i3 o1 sock -1 wfd 5 efd 6 [write])
debug2: channel 0: output drain -> closed
debug2: channel 0: rcvd close
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
Connection to 192.168.1.107 closed.
Transferred: sent 3024, received 3976 bytes, in 252.0 seconds
Bytes per second: sent 12.0, received 15.8
debug1: Exit status 127

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 19 июл 2019, 16:28

Q: Хочу в удалённой сессии запускать графические GUI программы, с отображением окон на моём X-сервере.
A: Запуск SSH с опциями:

Код: Выделить всё

olej@ACER:~$ ssh -X olej@192.168.1.107 
olej@192.168.1.107's password: 
...
Менее известный, более поздний, позже добавленный ключ -Y - соединение без шифрования, без затрат процессорного времени на обоимх концах соединения:

Код: Выделить всё

olej@ACER:~$ ssh -Y olej@192.168.1.107 
olej@192.168.1.107's password: 
You have new mail.
Last login: Fri Jul 19 16:17:57 2019 from 192.168.1.103
olej@astra:~$ VirtualBox
...
Вложения
Снимок экрана от 2019-07-19 16-24-17.png

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

удалённый SSH

Непрочитанное сообщение Olej » 19 июл 2019, 17:08

Q: Хочу подключаться по SSH из скрипта, с явным указанием passwd так, чтобы не вводить каждый раз вручную.
A: Об этом описано уже здесь: SSL/SSH.

Используем (устанавливаем) программу sshpass:

Код: Выделить всё

olej@ACER:~/2019_WORK/own.WORK/AplitSoft/FaceDL$ sudo apt install sshpass
[sudo] пароль для olej: 
Чтение списков пакетов… Готово
Построение дерева зависимостей       
Чтение информации о состоянии… Готово
Следующие пакеты устанавливались автоматически и больше не требуются:
  linux-compiler-gcc-7-x86 linux-kbuild-4.18
Для их удаления используйте «sudo apt autoremove».
Следующие НОВЫЕ пакеты будут установлены:
  sshpass
Обновлено 0 пакетов, установлено 1 новых пакетов, для удаления отмечено 0 пакетов, и 6 пакетов не обновлено.
Необходимо скачать 11,3 kB архивов.
После данной операции объём занятого дискового пространства возрастёт на 31,7 kB.
Пол:1 http://deb.debian.org/debian buster/main amd64 sshpass amd64 1.06-1 [11,3 kB]
Получено 11,3 kB за 1с (11,2 kB/s)                                      
Выбор ранее не выбранного пакета sshpass.
(Чтение базы данных … на данный момент установлено 379076 файлов и каталогов.)
Подготовка к распаковке …/sshpass_1.06-1_amd64.deb …
Распаковывается sshpass (1.06-1) …
Настраивается пакет sshpass (1.06-1) …
Обрабатываются триггеры для man-db (2.8.5-1) …

Код: Выделить всё

olej@ACER:~$ sshpass -p 'xxxxxx' ssh -l olej -Y 192.168.1.107
You have new mail.
Last login: Fri Jul 19 16:23:52 2019 from 192.168.1.103

olej@astra:~$ uname -a
Linux astra 4.19.0-1-generic #astra1 SMP Wed Mar 20 12:59:21 UTC 2019 x86_64 GNU/Linux

olej@astra:~$ whoami
olej
Удалённый Firefox:

Код: Выделить всё

olej@astra:~$ which firefox
/usr/bin/firefox
Для вас есть почта в /var/mail/olej

Код: Выделить всё

olej@astra:~$ /usr/bin/firefox &
[1] 6152
olej@astra:~$ defaults/preferences/firefox.js:49: prefs parse error: expected ';' after ')'
/usr/lib/firefox/browser/defaults/preferences/firefox.js:49: prefs parse error: expected ';' after ')'
Вложения
Снимок экрана от 2019-07-19 18-11-49.png

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 21 июл 2019, 00:01

Q: В Raspbian (DEB based) дистрибутиве для Raspberry Pi вход дефаултного юзера pi по SSH запрещён. Как запретить/разрешить конкретному пользователю доступ по SSH?
A: Разрешить или запретить доступ SSH определенному пользователю или группе в Linux
09.07.2018
Перейдите на ваш удаленный сервер и отредактируйте файл sshd_config:
$ sudo vi /etc/ssh/sshd_config
Добавьте или отредактируйте следующую строку:
AllowUsers sk
Замените «sk» на свое имя пользователя.
Вы также можете указать несколько пользователей, как показано ниже.
AllowUsers sk itsecforu
Чтобы разрешить целую группу, скажем, например, root, добавьте / отредактируйте следующую строку:
AllowGroups root
Те, кто входит в группу, могут передавать ssh на удаленный сервер.
Чтобы запретить доступ SSH к определенному пользователю с именем «sk», отредактируйте файл sshd_config:
$ sudo vi /etc/ssh/sshd_config
Добавьте / отредактируйте следующую строку в файле sshd_config.
DenyUsers sk
Аналогично, чтобы запретить доступ SSH нескольким пользователям, укажите имена пользователей как показано ниже.
DenyUsers sk itsecforu
Чтобы запретить доступ SSH ко всей группе, например root, добавьте:
DenyGroups root
И, наверное, это сработает в любом дистрибутиве Linux.

Как разрешить пользователю root заходить по SSH в системах Linux Ubuntu
Обновлено: 23.11.2017
Теперь открываем настройки SSH:
vi /etc/ssh/sshd_config
и редактируем параметр PermitRootLogin — задаем значение yes:
PermitRootLogin yes
* если параметр закомментирован, снимаем комментарий.
** по умолчанию, значение может быть without-password или prohibit-password — оно разрешает вход для root средствами GSSAPI (не парольной аутентификации), например, смарт-карты или отпечатка пальца.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 21 июл 2019, 00:03

Olej писал(а):И, наверное, это сработает в любом дистрибутиве Linux.
Только в Raspbian вот:

Код: Выделить всё

olej@raspberrypi:/etc/ssh $ lsb_release -a
No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 9.9 (stretch)
Release:	9.9
Codename:	stretch

olej@raspberrypi:/etc/ssh $ cat /etc/ssh/sshd_config | grep Deny
olej@raspberrypi:/etc/ssh
Т.е. есть ещё какой-то механизм сверх этого.
И он и используется.

Код: Выделить всё

olej@raspberrypi:/etc/ssh $ cat /etc/ssh/sshd_config | grep Root
#PermitRootLogin prohibit-password
# the setting of "PermitRootLogin without-password".

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 21 июл 2019, 00:23

Olej писал(а): Только в Raspbian вот:
В Raspbian есть дополнительный механизм конфигурации многих параметров:

Код: Выделить всё

olej@raspberrypi:/etc/ssh $ sudo raspi-config
[sudo] пароль для olej: 
...
sfg1.png
cfg2.png
cfg3.png
Но только это не даёт доступа с дефаултным именем паролем pi:pi ... даже в режиме с отладкой:

Код: Выделить всё

olej@ACER:~$ ssh -Y pi@46.172.92.145 -vv
OpenSSH_7.9p1 Debian-10, OpenSSL 1.1.1c  28 May 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolve_canonicalize: hostname 46.172.92.145 is address
debug2: ssh_connect_direct
debug1: Connecting to 46.172.92.145 [46.172.92.145] port 22.
debug1: Connection established.
debug1: identity file /home/olej/.ssh/id_rsa type -1
debug1: identity file /home/olej/.ssh/id_rsa-cert type -1
debug1: identity file /home/olej/.ssh/id_dsa type -1
debug1: identity file /home/olej/.ssh/id_dsa-cert type -1
debug1: identity file /home/olej/.ssh/id_ecdsa type -1
debug1: identity file /home/olej/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/olej/.ssh/id_ed25519 type -1
debug1: identity file /home/olej/.ssh/id_ed25519-cert type -1
debug1: identity file /home/olej/.ssh/id_xmss type -1
debug1: identity file /home/olej/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9p1 Debian-10
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Raspbian-10+deb9u6
debug1: match: OpenSSH_7.4p1 Raspbian-10+deb9u6 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 46.172.92.145:22 as 'pi'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:SurqyV5/ldX8xUMCteh4Tz9GMSm8pOs4lBY71XE7yWg
debug1: Host '46.172.92.145' is known and matches the ECDSA host key.
debug1: Found key in /home/olej/.ssh/known_hosts:4
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Will attempt key: /home/olej/.ssh/id_rsa 
debug1: Will attempt key: /home/olej/.ssh/id_dsa 
debug1: Will attempt key: /home/olej/.ssh/id_ecdsa 
debug1: Will attempt key: /home/olej/.ssh/id_ed25519 
debug1: Will attempt key: /home/olej/.ssh/id_xmss 
debug2: pubkey_prepare: done
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/olej/.ssh/id_rsa
debug1: Trying private key: /home/olej/.ssh/id_dsa
debug1: Trying private key: /home/olej/.ssh/id_ecdsa
debug1: Trying private key: /home/olej/.ssh/id_ed25519
debug1: Trying private key: /home/olej/.ssh/id_xmss
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
pi@46.172.92.145's password: 
debug2: we sent a password packet, wait for reply
debug1: Authentications that can continue: publickey,password
Permission denied, please try again.
pi@46.172.92.145's password: 

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 05 сен 2019, 14:32

Очень противная ситуация, когда при подключении SSH, которое всегда раньше срабатывало, получаете:

Код: Выделить всё

olej@nvidia:~$ ssh olej@192.168.1.101
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:ybkJ5eB+oqonPKk23OyqvtH+1zfv9A+TNtNpiCw4BJQ.
Please contact your system administrator.
Add correct host key in /home/olej/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/olej/.ssh/known_hosts:10
  remove with:
  ssh-keygen -f "/home/olej/.ssh/known_hosts" -R "192.168.1.101"
ECDSA host key for 192.168.1.101 has changed and you have requested strict checking.
Host key verification failed.

Это происходит (часто) при изменении IP хостов, к которым подключаемся, если они получают динамические IP по DHCP + мы достаточно долго не подключались к хосту (период обновления DHCP): IP адрес хоста поменялся и отпечаток (fingerprint) сервера поменялся.
Всё это (отпечатки) для всех серверов записано в файле $HOME/.ssh/known_hosts

До тех пор, пока у вас в клиенте SSH в конфигурации (файл /etc/ssh/ssh_config) не установлен параметр HashKnownHosts, можно просто удалить строку соответствующую интересующему серверу (по IP):

Код: Выделить всё

...
atom,192.168.1.7 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEArNz1w0FKZpSs7i4xVD1uvxYJwghh0H+LGmELsTK0NIDxlfz3NJzArsqchFVJipUTdLB954zFeLxitgZB5iDyxWSZ1AjfzFonz9OXxseTK41bVsI0ad+9wTZXG488AVlq1pYvbTXpqbuYmPRUJD0QMBB5VbHXgR9bXfc8B5Uj+71ZB/1AD6D3/R2SJJ+u5kf1Q70CK/s9Fb+R30k3VV947KhTe91fSwD1FRK9Gc1JZqAlilQyxlZRDqvkEA9iWex/W2MRcsplleATqABMfDFIJW7zGBXoRHtouJINASYjm/W7itCCH7nm6sQ/UJU9LGzTzXaU14Qwo8xNu57UmCYzdQ==
...
notebook,192.168.1.5 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDD+mxcYJwmugC8qMVcRkgUrVbMnvuHU9i1b0EPzodOVwW+AdX7AH5FkXGa5d0weGb0qlsKpNfgKuaMvUh3MXNTRmTKxdtDXOuvsGd2bCE8mX247w37ekhgUX5Z1DyGZu2S52NmB09YA3RSOtTd0LEON/vxUA0fHKbgjhRo/2rPf0+OMLqB0AICJnm6x7ItOALhISxXLbCceW/nzH1ZM1LlRTkWk+seAWTHxhok2xyqTyLUHpEGh1Lyg8qE2nOl+CPfBrEBIOD1kfCdkTtTMWLf5aJTpAZNJXXNnJjls+G/pg4gkRn8W3pLeKejqDkTmex+hyXGtINZC4LXGnoVFCmd
...
192.168.1.20 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDH7wB7zH1AZSoxYoHKOMqBCTxykCfCair1uqEvLLOKhDzGghJ2+k3EJknpaQ+msehPZMTeIJVxJITmdwk5BpJuoe8LsSFlrmACvESy32ej3u7T8wX2sj6c7NDU6/0iBV0KQP5cTGaWWCkrvQ4Gu22uRE2rUYeqLIAxOqYatwhjmVN1DUCa4G+7sevo+vqwK4Y7DGxwC2BGPlC4bjJ3gY5bKCyG5asxIswjayY3klcbYDT9lUqBXFYY+CL6iicUtiE454k8CPaJ6MQeIF+rXZxqnzEiQkOEitJv/KDdmwhYSq2BT2UxPMnbMoPecOkhCNXQmboYJlS93Edpq9TFZyQP
...
Но если установлен параметр HashKnownHosts (что может произойти без нашего ведома при любом обновлении системы, OpenSSH и т.д.):

Код: Выделить всё

olej@nvidia:/etc/ssh$ cat /etc/ssh/ssh_config | grep HashKnownHosts
    HashKnownHosts yes
И тогда строки серверов в $HOME/.ssh/known_hosts принимают вид:

Код: Выделить всё

...
|1|W42Gsr4waE0ufGxNqhYhbO80y4I=|VgSbglHgGKVE1aZqkpTjZ4JkXbY= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBP7KHgCxhttBHeKOYAiPJEDWBdnr9rlrgnGoVL0do5fTAsKvzhHz1jCrl7HgahXb2gdc4LI9FpWVXvVjwFSRBTc=
|1|WOpQ5c1+qsY6eB9HkvL6+5m3yYk=|W+JfKqpIMWVk5bAu0yZZM3gzjU0= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBB1ufxDBbLy4ENE5G5HMDhVwOET0a+OEs0GnqJzGHUcyzS7/LFP/aipRoCW4XZCfFAH20luZMm3gqoiwHVltE2k=
|1|jCzvvjxlViFyPToEK4g3O6P+A8s=|B7g4dONLnbcEOvyg6nCFqk5F8EM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCUBfKHmQe9+19f3xoqkqkVAiRSJweAMQLJYVKew+0sjJVoAeR20rfODn8XbBl1scc3GksvRp+YwffYQkUJ6aKg=
...
И тут IP или имена серверов нам не помощники...

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: удалённый SSH

Непрочитанное сообщение Olej » 05 сен 2019, 14:35

Olej писал(а):И тут IP или имена серверов нам не помощники...
Тогда:

Код: Выделить всё

olej@nvidia:~/.ssh$ ssh-keygen -R 192.168.1.101
# Host 192.168.1.101 found: line 10
/home/olej/.ssh/known_hosts updated.
Original contents retained as /home/olej/.ssh/known_hosts.old
Обращаем внимание: без root, потому что действие выполняется в $HOME!

И в результате:

Код: Выделить всё

olej@nvidia:~$ ssh olej@192.168.1.101
The authenticity of host '192.168.1.101 (192.168.1.101)' can't be established.
ECDSA key fingerprint is SHA256:ybkJ5eB+oqonPKk23OyqvtH+1zfv9A+TNtNpiCw4BJQ.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.101' (ECDSA) to the list of known hosts.
olej@192.168.1.101's password: 

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Mar  7 17:21:12 2019 from 192.168.1.101

model: Raspberry Pi 2 Model B Rev 1.1
compatible: brcm,bcm2709
My IP address is 192.168.1.101 

Xenomai/cobalt v3.0.5
Имеем новую созданную строку для этого хоста... и подключение к удалённому хосту Rapsberry Pi:

Код: Выделить всё

olej@raspberrypi:~ $ lsb_release -a
No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 8.0 (jessie)
Release:	8.0
Codename:	jessie

Ответить

Вернуться в «Сети»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 10 гостей