你的浏览器无法正常显示内容,请更换或升级浏览器!

Linux服务器安全加固完整实操流程

tenfei
tenfei
发布于2026-08-15 11:52 阅读11次
Linux服务器安全加固完整实操流程
从零开始给一台新装 Linux 服务器做安全加固的完整实操流程,涵盖系统更新、SSH 密钥登录、防火墙白名单、fail2ban 防暴力破解、日志审计和最小权限配置,每步附可复制命令。
# Linux服务器安全加固完整实操流程 ## 前言 新装的 Linux 服务器直接暴露公网,往往几分钟内就会被扫描器盯上。本文梳理一套标准的安全加固流程,从拿到 root 开始,一步步把服务器武装到"及格线"。 ## 第一步:更新系统 ```bash # Debian/Ubuntu apt update && apt upgrade -y # CentOS/RHEL yum update -y ``` 补丁是安全的第一道防线,很多入侵都是利用已知漏洞,而漏洞往往早就有补丁了。 ## 第二步:创建普通用户 + sudo 永远不要直接以 root 登录,创建一个普通管理用户: ```bash # 创建用户 useradd -m -s /bin/bash deploy passwd deploy # 加入 sudo 组 usermod -aG sudo deploy # Debian/Ubuntu # usermod -aG wheel deploy # CentOS ``` ## 第三步:SSH 密钥登录(禁用密码) ```bash # 本地生成密钥对 ssh-keygen -t ed25519 -C "deploy@server" # 上传公钥 ssh-copy-id deploy@服务器IP # 编辑 /etc/ssh/sshd_config Port 2222 # 改端口 PermitRootLogin no # 禁 root 登录 PasswordAuthentication no # 禁密码登录 PubkeyAuthentication yes # 开密钥登录 MaxAuthTries 3 # 重启 sshd systemctl restart sshd ``` 改完端口后记得防火墙放行新端口,别把自己锁在门外。 ## 第四步:防火墙白名单 ```bash # 启用 ufw (Ubuntu) ufw default deny incoming ufw default allow outgoing ufw allow 2222/tcp ufw allow 80/tcp ufw allow 443/tcp ufw enable # 或用 firewalld (CentOS) systemctl start firewalld firewall-cmd --permanent --add-port=2222/tcp firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload ``` 原则:默认拒绝,按需放行,只开业务需要的端口。 ## 第五步:fail2ban 防暴力破解 ```bash apt install fail2ban -y # 创建 /etc/fail2ban/jail.local [sshd] enabled = true port = 2222 maxretry = 5 bantime = 3600 findtime = 600 systemctl enable fail2ban --now ``` 验证效果: ```bash fail2ban-client status sshd # 查看被 ban 的 IP fail2ban-client status sshd | grep -A 10 Banned ``` ## 第六步:日志审计 ```bash # 开启 auditd apt install auditd -y systemctl enable auditd --now # 监控关键文件变更 auditctl -w /etc/passwd -p wa -k identity auditctl -w /etc/shadow -p wa -k identity auditctl -w /etc/sudoers -p wa -k sudoers auditctl -w /etc/ssh/sshd_config -p wa -k sshd # 查询审计日志 ausearch -k identity ``` ## 第七步:最小权限 ```bash # 检查文件权限 find / -perm -4000 -type f 2>/dev/null # 找 SUID # 锁定关键文件 chattr +i /etc/passwd # 防止被篡改 # 解锁: chattr -i /etc/passwd ``` ## 第八步:定期检查 ```bash # 查看登录日志 last | head -20 grep "Failed password" /var/log/auth.log | tail -20 # 查看当前连接 ss -tunlp # 检查异常进程 ps aux --sort=-%cpu | head -10 ``` ## 加固检查清单 | 项目 | 命令 | |------|------| | 系统已更新 | apt upgrade | | root 禁用 | grep PermitRootLogin /etc/ssh/sshd_config | | 密码登录禁用 | grep PasswordAuth /etc/ssh/sshd_config | | 防火墙启用 | ufw status | | fail2ban 运行 | systemctl status fail2ban | | 审计开启 | systemctl status auditd | ## 小结 按这八步走完,一台服务器的基本安全线就有了。安全不是一次性的,记得定期复查日志和补丁。

2

0

文章点评
Copyright © from 2021 by namoer.com
458815@qq.com QQ:458815
蜀ICP备2022020274号-2