Ubuntu/CentOS 服务器 SSH 安全加固实战:从裸机到抗爆破配置清单
Chapter 1:先做体检,别上来就改配置
兄弟们开机!这里是 eccfy,OK so,今天我们直接进服务器现场,不讲玄学,屏幕左边是终端,右边是攻击日志,接下来我带你做一套Linux服务器安全加固教程。先看基线:我这台 1C1G Ubuntu 22.04,公网 SSH 默认 22 端口,24 小时内 auth.log 里有 1837 次失败登录,延迟 42ms,用 grep "Failed password" /var/log/auth.log | wc -l 数出来的。
先别急着重启 SSH,先开第二个终端保持当前连接,防止把自己锁外面。执行:whoami、ip a、ss -tulpen、last -a | head,看当前用户、监听端口、最近登录 IP。CentOS/RHEL 日志看 /var/log/secure,Ubuntu/Debian 看 /var/log/auth.log。如果你是搜“SSH配置怎么用”来的,记住:先验证现状,再改配置。
Chapter 2:Now watch this,SSH 从密码登录切到密钥登录
接下来镜头拉近,我本机生成密钥:ssh-keygen -t ed25519 -C "admin@server" -f ~/.ssh/eccfy_ed25519。把公钥推上去:ssh-copy-id -i ~/.ssh/eccfy_ed25519.pub user@服务器IP。如果没有 ssh-copy-id,就手动把公钥追加到服务器 ~/.ssh/authorized_keys,权限必须是:chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys。
然后改 SSH 配置,注意是 /etc/ssh/sshd_config,不是 ssh_config。建议这样改:Port 22222、PermitRootLogin no、PasswordAuthentication no、PubkeyAuthentication yes、MaxAuthTries 3、ClientAliveInterval 300、ClientAliveCountMax 2。改完先别重启,用 sshd -t 检查语法;没报错再执行 systemctl reload ssh 或 systemctl reload sshd。
防火墙也要同步,不然你改了端口等于自断网线。Ubuntu 用 ufw allow 22222/tcp && ufw enable && ufw status numbered;CentOS 用 firewall-cmd --permanent --add-port=22222/tcp && firewall-cmd --reload。这也是很多人搜“ufw防火墙怎么用”时踩的坑:SSH 端口先放行,再 reload 服务。
Chapter 3:防爆破、更新补丁,最后现场验收
继续上强度,安装 Fail2ban。Ubuntu:apt update && apt install -y fail2ban unattended-upgrades;CentOS:dnf install -y fail2ban。创建 /etc/fail2ban/jail.d/sshd.local,写入:[sshd] enabled=true port=22222 maxretry=5 findtime=10m bantime=1h。启动:systemctl enable --now fail2ban。这段就是可复制的fail2ban安装教程。
再做系统补丁。Ubuntu 开启自动安全更新:dpkg-reconfigure unattended-upgrades;CentOS/RHEL 可用 dnf-automatic。额外建议:删除不用的用户,检查 sudo:getent passwd、getent group sudo;关闭无用服务:systemctl --type=service --state=running;看开放端口:ss -tulpen。如果你为了查“油管怎么看”“免费VPN”在服务器上装过来路不明脚本或翻墙软件,建议立刻审计 crontab -l、/etc/systemd/system 和 ~/.ssh/authorized_keys,很多后门就藏这里。
如何验证它真的生效?第一,用新端口登录:ssh -i ~/.ssh/eccfy_ed25519 -p 22222 user@服务器IP。第二,测试密码登录应失败:ssh -p 22222 user@服务器IP,不能输入密码成功才对。第三,看 Fail2ban:fail2ban-client status sshd。我实测改完后,24 小时失败登录从 1837 次降到 12 次,SSH 握手延迟从 42ms 到 44ms,几乎无性能损耗。
如果你需要稳定远程访问海外开发资源,官方 SSH、WireGuard、自建跳板机都是优先方案;付费工具只是备选,比如 Roxi(https://wizzegroup.com)这类服务可作为网络连通性补充,但生产服务器安全加固仍然要按上面步骤自己完成。OK,今天就到这,收藏、评论区贴你的 sshd_config,我帮你看坑点!