SSH使用及扩展

经常和Linux服务器打交道就离不开SSH.

常用命令

# 连接
ssh user@ip -p port_number

 # 生成key
ssh-keygen -t rsa -C "admin[at]xulizhao.com"
# 删除无效的公钥,通常由于变更IP造成
ssh-keygen -f "~/.ssh/known_hosts" -R 8.8.8.8
# 复制公钥信息到粘贴板
xclip -selection clipboard < ~/.ssh/id_rsa.pub
# 如果服务器没有开启SSH服务, 需要先安装
apt install openssh-server
# 打印DEBUG信息用以调试
ssh -v ...
# 远程运行本地脚本
ssh xulz@moon bash < /path/to/local/script.sh

目录结构

一般ssh相关文件存放在~/.ssh目录, Windows在 %userprofile%/.ssh

  • 公钥: id_rsa.pub
  • 私钥: id_rsa
  • 认证公钥: authorized_keys
  • 配置文件: config
# 样例
ServerAliveInterval 60    # 解决Broken pipe问题
TCPKeepAlive yes

# 配置别名,很有用
Host moon
     HostName moon.xulizhao.com
     user ubuntu
     Port 22
     IdentityFile ~/.ssh/github.key
  • 服务端配置: /etc/ssh/sshd.config
ClientAliveInterval 60    # 解决Broken pipe问题,无需客户端改动

无密码登录

# Mac需要先安装
brew install ssh-copy-id
# 关键命令
ssh-copy-id username@remotehost
# 有时也需要修改权限
chmod 600 ~/.ssh/authorized_keys

timed out waiting for input: auto-logout

echo $TMOUT
vi /etc/profile
export TMOUT=600
source /etc/profile

no matching host key type found. Their offer: ssh-rsa

Ubuntu 22.04为了更好的安全性,现在OpenSSH中默认禁用了ssh-rsa.

Refer here for more.

Host git.example.com
  HostkeyAlgorithms +ssh-rsa
  PubkeyAcceptedAlgorithms +ssh-rsa

Error connecting to agent: No such file or directory

# Check the Windows Service “OpenSSH Authentication Agent” is set to manual and running
# check PublicKey
ssh-add -L
# add PrivateKey
ssh-add ~/.ssh/id_rsa

# try auth
ssh -Tv git@bitbucket.org

调试信息

查看当前使用ssh的用户信息:

ss |grep -i ssh
netstat -tnpa|grep sshd

last -a|grep -i still
who
w

扩展应用

Mosh

更稳定的SSH,适合移动端等网络不可靠环境

sshfs

把远程服务器的路径映射为本地路径

# 安装
sudo apt-get install sshfs
# 映射远程文件系统
mkdir ~/remote_code
sshfs remote.xulizhao.com:/home/$USER/code ~/remote_code

pam_tally2

多次密码失败后锁定账号,参考Use Pam_Tally2 to Lock and Unlock SSH Failed Login Attempts

客户端工具

免费/开源的:

收费中最好用的:

扩展阅读