一、服务器安全的重要性
云服务器暴露在公网上,面临各种安全威胁:暴力破解、漏洞利用、DDoS攻击、恶意软件等。一次安全事件可能导致数据泄露、服务中断、甚至法律责任。本文提供系统化的安全加固方案。
二、账户与访问控制
1. 禁用root远程登录
# 编辑SSH配置
sudo vim /etc/ssh/sshd_config
# 修改以下配置
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
# 重启SSH服务
sudo systemctl restart sshd
2. 创建普通用户并配置sudo
# 创建新用户
sudo useradd -m -s /bin/bash deployer
sudo passwd deployer
# 添加到sudo组
sudo usermod -aG sudo deployer
# 配置免密sudo(可选,用于自动化)
echo 'deployer ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/deployer
3. 配置SSH密钥登录
# 本地生成密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"
# 复制公钥到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub deployer@server_ip
# 测试密钥登录
ssh deployer@server_ip
三、防火墙配置
# 使用UFW简化防火墙管理
sudo apt install ufw
# 默认拒绝所有入站
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 允许SSH(注意:确保密钥登录已配置,否则会被锁在外面)
sudo ufw allow 22/tcp
# 允许HTTP/HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 允许特定IP访问管理端口
sudo ufw allow from 192.168.1.0/24 to any port 3306
# 启用防火墙
sudo ufw enable
sudo ufw status verbose
四、系统更新与漏洞修复
# 自动安全更新
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
# 手动更新
sudo apt update
sudo apt upgrade -y
# 检查安全更新
sudo apt list --upgradable | grep -i security
五、入侵检测与日志监控
# 安装fail2ban防止暴力破解
sudo apt install fail2ban
# 配置fail2ban
sudo tee /etc/fail2ban/jail.local > /dev/null <
服务器安全是持续的过程,需要定期检查日志、更新补丁、审计配置。建议每月进行一次安全扫描,及时发现潜在风险。
