Ubuntu 的 SSH 分两端:服务端(sshd)是让别的机器连进来,客户端是你主动连别人。两侧的配置文件不同,一次把常用配置说全。

服务端配置

  • 安装:sudo apt install openssh-server,装完自动启动并设自启,systemctl status ssh 确认。
  • 配置文件 /etc/ssh/sshd_config:改 Port 换端口、PermitRootLogin no 禁 root、PasswordAuthentication no 换纯密钥(先确认密钥能用再关)。
  • Ubuntu 22.10+ 的配置拆分到 /etc/ssh/sshd_config.d/*.conf,云镜像的自定义通常在这目录,改主文件被覆盖时来这里找。
  • 改动后 sudo sshd -t 校验语法,再 sudo systemctl restart ssh。
  • ufw 启用的机器放行:sudo ufw allow ssh 或指定新端口。

客户端优化

~/.ssh/config 里按主机写别名(Host/HostName/User/Port/IdentityFile),ServerAliveInterval 60 保活防断,ControlMaster 复用连接减少重复认证。常用主机还可以在 ~/.ssh/known_hosts 自动管理下不做多余改动。

免密三板斧:ssh-keygen 生成、ssh-copy-id 推送、chmod 校权限。建议:服务器装完第一件事就是配好密钥免密并禁用密码认证, brutality 的扫描器对 22 端口 24 小时轰炸,密码认证撑不了太久。