Skip to content

ssh

Secure SHell

最初SSH是由芬兰的一家公司开发的。但是因为受版权和加密算法的限制,现在很多人都转而使用OpenSSH

OpenSSH是SSH协议的开源版本(SSH:Secure SHell)

Location

~/.ssh:

  • ./authorized_keys: Others' rsa_pubs

  • ./id_rsa & ./id_rsa.pub: Local rsa pairs

  • ./known_hosts

  • ./config: (记得配在这里哟)

Host dev HostName dev.example.com User john Port 2322

Generate rsa pairs

linux

mac

ssh-keygen

windows

安装 open-ssh

Install public key on server

cat id_rsa.pub >> authorized_keys
# chmod 600 authorized_keys
# chmod 700 ~/.ssh

一个完整的新增用户+配置登录流程

useradd -m 用户名
su 用户名 # 重要 切到新用户!! 我总是用 root 用户去创建!这样用户登录时就会 Permission denied (publickey) 了!
mkdir .ssh; touch .ssh/authorized_keys; # 并写入用户公钥;
chmod 700 .ssh/; chmod 600 .ssh/authorized_keys* # 重要 加读取权限
# 在用户家目录下使用 google-authenticator # 生成新秘钥
# service sshd restart
# systemctl restart sshd

注意 如是 systemd 启动的 ssh,对应 log 也被 systemd 托管:journalctl -t sshd -f

Add MFP (two-pass authentication)

https://wiki.archlinux.org/title/Google_Authenticator

How to Use Two-Factor Authentication with Sudo and SSH on Linux with Google Authenticator - Vultr.com

ssh tunnel

ssh root@120.26.48.180 -N -L localhost:6443:localhost:6443
# -N do not execute remote command
# -f request ssh to go to the background

# more: -NCPf
# -C    使用压缩功能,是可选的,加快速度。 
# -P    用一个非特权端口进行出去的连接。 
# -f    一旦SSH完成认证并建立port forwarding,则转入后台运行

参考:https://developer.aliyun.com/article/641005

Debug

一次 Permission denied

ssh -v 显示 connect to address ... port 22: Operation timed out, 这时要记着去服务端看 ssh 的日志:journalctl -xeu sshd | tail -n 100 ,显示 Authentication refused: bad ownership or modes for file /home/qiwan/.ssh/authorized_keys,才知道用户 authorized_keys 权限给多了也不行…🤣 还只能是 600

SSH doesn’t like it if your home or ~/.ssh directories have group write permissions. Your home directory should be writable only by you, ~/.ssh should be 700, and authorized_keys should be 600