Skip to content

SSH

Terminal window
ssh-keygen -t ed25519 -f ~/.ssh/main_key -a 128 -C "main-key"
  • -t — Тип алгоритма
  • -f — Путь к файлу
  • -a — Раунды KDF
  • -C — Комментарий

Запустить агента

Terminal window
eval "$(ssh-agent -s)"

Добавить ключ

Terminal window
ssh-add

Пример: ssh-add ~/.ssh/main_key

Посмотреть добавленные ключи

Terminal window
ssh-add -l

Удалить ключ из агента

Terminal window
ssh-add -d

Пример: ssh-add -d ~/.ssh/main_key

Очистить агента

Terminal window
ssh-add -D

Пояснение: удалит все ключи из агента

Добавить публичный ключ на сервер

Terminal window
ssh-copy-id -i ~/.ssh/main_key.pub

Пример: ssh-copy-id -i ~/.ssh/main_key.pub root@127.0.0.1 Подсказка: можно подключиться к серверу по ssh и прописать ключ в ~/.ssh/authorized_keys

authorized_keys для проброса портов

no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=localhost:8080

Примечание: для доступа снаружи в sshd включи GatewayPorts yes Пример: no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=localhost:8080 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII6E+CgQ7TYiTUtmZ1wZiz305obShAS96oQQS9yzmXSI tunnel-key

Файл: ~/.ssh/config

# VPS
Host vps
HostName 8.8.8.8
User admin
Port 22022
# Virtual
Host localhost
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
Host vm
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
HostName 127.0.0.1
User admin
Port 22022

Пример: ssh vps; scp file.txt vm:~/ Подсказка: используй флаг -F чтобы указать путь до конфига -> ssh -F ~/my_config vps

Внимание: для scp порт указывается через -P

Копирование файла

Terminal window
scp file.txt user@192.168.1.137:path/to/file

Подсказка: если хост прописан в ~/.ssh/config используй ssh file.txt host:path/to/file

Копирование директории

Terminal window
scp -R myDir user@192.168.1.137:path/to/dir

Подсказка: если хост прописан в ~/.ssh/config используй ssh -R myDir host:path/to/dir

Копирование файла

Terminal window
scp user@192.168.1.137:~/file.txt ~/file.txt

Подсказка: если хост прописан в ~/.ssh/config используй scp host:~/file.txt ~/file.txt

Копирование директории

Terminal window
scp -R user@192.168.1.137:~/var/log/nginx ~/backup/log/

Подсказка: если хост прописан в ~/.ssh/config используй scp -R host:~/var/log/nginx ~/backup/log/

Подключиться к vps1 через vps2

Terminal window
ssh -J vps1 vps2

Важно: на vps1 в sshd_config разрешён AllowAgentForwarding yes Примечание: vps1 и vps2 должны быть прописаны в ~/.ssh/config

Файл: /etc/ssh/sshd_config

# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/bin:/usr/bin:/bin:/usr/games
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.
Include /etc/ssh/sshd_config.d/*.conf
Port 22022
AddressFamily inet
#ListenAddress 0.0.0.0
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
# Ciphers and keying
#RekeyLimit default none
# Logging
#SyslogFacility AUTH
#LogLevel INFO
# Authentication:
LoginGraceTime 1m
PermitRootLogin no
#StrictModes yes
MaxAuthTries 6
MaxSessions 10
PubkeyAuthentication yes
# Expect .ssh/authorized_keys2 to be disregarded by default in future.
AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication no
PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin prohibit-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes
#AllowAgentForwarding yes
#AllowTcpForwarding yes
GatewayPorts yes
X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
ClientAliveInterval 300
ClientAliveCountMax 12
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none
# no default banner path
#Banner none
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
# override default of no subsystems
Subsystem sftp /usr/lib/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server

Простой туннель

Terminal window
ssh -D 127.0.0.1:1080 -N -C vps1

Подсказка: на localhost будет открыть socks5 на порту 1080

  • -D — динамическая переадресация портов
  • -N — без интерактивной оболочки
  • -C — сжатие данных

Простой туннель autossh

Terminal window
autossh -M 20000 -D 127.0.0.1:1080 -N -C vps1

Подсказка: добавь -f чтобы запустить в фоне

  • -M — порт для мониторинга состояния соединения

Туннель с прыжком

Terminal window
ssh -D 127.0.0.1:1080 -N -C -J vps1 vps2

Туннель с прыжком autossh

Terminal window
autossh -M 20000 -D 127.0.0.1:1080 -N -C -J vps1 vps2

Локальный проброс портов

Section titled “Локальный проброс портов”

Подключиться к веб-серверу из локальной сети vps1

Terminal window
ssh -L 8080:192.168.1.50:80 -N -C vps1

Подсказка: можешь заменить ssh на autossh -M 20000 Примечание: порт 8080 - localhost, порт 80 в локальной сети vps1

Несколько портов через autossh

Terminal window
autossh -M 20000 \
-L 22022:remote-host:22 \
-L 8080:remote-host:80 \
-L 8443:remote-host:443 \
-N -C -f vps1

Удалённый проброс портов

Section titled “Удалённый проброс портов”

Пробросить порт веб-сервера с хоста на vps1

Terminal window
ssh -R 0.0.0.0:8080:localhost:80 -N -C vps1

Важно: при 0.0.0.0 в sshd_config включи GatewayPorts yes Примечание: 8080 - порт на vps, 80 - порт на хосте. Подсказка: 0.0.0.0 можно заменить на 127.0.0.1 - порт будет доступен только на vps1

Несколько портов через autossh

Terminal window
autossh -M 20000 \
-R 127.0.0.1:22022:localhost:22 \
-R 0.0.0.0:8080:localhost:80 \
-R 0.0.0.0:8443:localhost:443 \
-N -C -f vps1