一键初始化脚本

#!/bin/bash
# server-init.sh — 新服务器初始化配置
# 适用于 Ubuntu 22.04 / 24.04
set -euo pipefail

# === 配置变量 ===
NEW_USER="deploy"
SSH_PORT="22"  # 建议改为非标准端口
TIMEZONE="Asia/Shanghai"

# === 1. 系统更新 ===
echo ">>> Updating system packages..."
apt update && apt upgrade -y
apt autoremove -y

# === 2. 创建部署用户 ===
echo ">>> Creating deploy user..."
if ! id "$NEW_USER" &>/dev/null; then
    useradd -m -s /bin/bash "$NEW_USER"
    usermod -aG sudo "$NEW_USER"
fi

# === 3. 配置 SSH 密钥登录 ===
echo ">>> Configuring SSH keys..."
mkdir -p /home/$NEW_USER/.ssh
cp ~/.ssh/authorized_keys /home/$NEW_USER/.ssh/ 2>/dev/null || true
chown -R $NEW_USER:$NEW_USER /home/$NEW_USER/.ssh
chmod 700 /home/$NEW_USER/.ssh
chmod 600 /home/$NEW_USER/.ssh/authorized_keys

# === 4. 强化 SSH 配置 ===
echo ">>> Hardening SSH configuration..."
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/#Port 22/Port '"$SSH_PORT"'/' /etc/ssh/sshd_config
systemctl restart sshd

# === 5. 配置防火墙 ===
echo ">>> Configuring firewall..."
ufw allow $SSH_PORT/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

# === 6. 配置时区和 NTP ===
echo ">>> Configuring timezone..."
timedatectl set-timezone $TIMEZONE
apt install -y chrony
systemctl enable --now chrony

# === 7. 安装基础软件 ===
echo ">>> Installing essential packages..."
apt install -y curl wget git ufw fail2ban htop     nginx docker.io docker-compose-plugin     certbot python3-certbot-nginx

# === 8. 配置 fail2ban ===
echo ">>> Configuring fail2ban..."
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = $SSH_PORT
maxretry = 3
bantime = 3600
EOF
systemctl enable --now fail2ban

# === 9. 配置 Swap ===
echo ">>> Configuring swap..."
if [ ! -f /swapfile ]; then
    fallocate -l 2G /swapfile
    chmod 600 /swapfile
    mkswap /swapfile
    swapon /swapfile
    echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi

# === 10. 完成 ===
echo ""
echo "=== Server initialization complete! ==="
echo "Created user: $NEW_USER"
echo "SSH port: $SSH_PORT"
echo "Please logout and test SSH with new user before closing this session."

使用方法

# 1. 上传脚本到服务器
scp server-init.sh root@your-server:~/

# 2. 登录服务器执行
ssh root@your-server
chmod +x server-init.sh
sudo ./server-init.sh

脚本说明

步骤 作用 说明
系统更新 apt update & upgrade 确保系统包为最新版本
创建用户 创建 deploy 用户 禁止 root 直接登录
SSH 加固 禁用密码+root登录 仅允许密钥认证
防火墙 UFW 仅开放 SSH/HTTP/HTTPS
Fail2ban 暴力破解防护 SSH 3 次失败封禁 1 小时
Swap 内存交换 2GB Swap 防止 OOM

安全建议

  1. 建议修改 SSH 端口:将 SSH_PORT 改为 2222 或其他非标准端口
  2. 更换 SSH 密钥:不要使用服务器生成的默认密钥
  3. 配置自动更新apt install unattended-upgrades 启用安全更新自动安装
  4. 定期检查日志journalctl -xetail -f /var/log/auth.log