ai-chatbot/setup-server.sh
Your Name 73d0d9d8c2
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
feat(security): integrate one-click server hardening into deploy flow
2026-02-12 15:09:16 +08:00

112 lines
2.9 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# 服务器初始化脚本
# 在服务器上运行此脚本来设置环境
set -e
echo "开始设置服务器环境..."
# 更新系统
echo "更新系统..."
apt update && apt upgrade -y
# 安装基础工具
echo "安装基础工具..."
apt install -y curl wget git build-essential
# 安全检查函数:检查 .bashrc 是否被感染
check_bashrc_security() {
local bashrc_file="$HOME/.bashrc"
if [ -f "$bashrc_file" ]; then
# 检查是否包含恶意代码模式
if grep -qE '\.update|/usr/bin/\.update|while.*true.*do.*\.update' "$bashrc_file" 2>/dev/null; then
echo "⚠️ 警告: 检测到 .bashrc 可能包含恶意代码!"
echo " 建议检查并清理 .bashrc 文件"
return 1
fi
fi
return 0
}
# 安装 Node.js (使用 nvm)
echo "安装 Node.js..."
if [ ! -d "$HOME/.nvm" ]; then
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
fi
# 直接加载 nvm,不通过 .bashrc(更安全)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# 执行安全检查
if ! check_bashrc_security; then
echo "⚠️ 继续执行,但请注意安全风险"
fi
# 安装和使用 Node.js
nvm install 20
nvm use 20
nvm alias default 20
# 安装 pnpm
echo "安装 pnpm..."
npm install -g pnpm
# 安装 PM2
echo "安装 PM2..."
npm install -g pm2
# 安装 PostgreSQL
echo "安装 PostgreSQL..."
if ! command -v psql &> /dev/null; then
apt install -y postgresql postgresql-contrib
systemctl start postgresql
systemctl enable postgresql
fi
# 安装 Nginx
echo "安装 Nginx..."
if ! command -v nginx &> /dev/null; then
apt install -y nginx
systemctl start nginx
systemctl enable nginx
fi
# 创建项目目录
echo "创建项目目录..."
mkdir -p /var/www/ai-chatbot
chown -R $USER:$USER /var/www/ai-chatbot
# 创建日志目录
mkdir -p /var/log/pm2
chown -R $USER:$USER /var/log/pm2
# 创建备份目录
mkdir -p /root/backups/ai-chatbot
# 设置防火墙
echo "配置防火墙..."
ufw --force enable
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 5204/tcp
# 安装安全基线(如果脚本存在)
if [ -f "$(dirname "$0")/scripts/security/install-security-stack.sh" ]; then
echo "安装 security-stack..."
bash "$(dirname "$0")/scripts/security/install-security-stack.sh" || echo "security-stack 安装失败,继续执行"
elif [ -f "$(dirname "$0")/scripts/security/install-perf-guard.sh" ]; then
echo "安装 perf-guard..."
bash "$(dirname "$0")/scripts/security/install-perf-guard.sh" || echo "perf-guard 安装失败,继续执行"
fi
echo "服务器环境设置完成!"
echo ""
echo "下一步:"
echo "1. 配置 PostgreSQL 数据库"
echo "2. 上传项目代码到 /var/www/ai-chatbot"
echo "3. 配置环境变量 (.env.local)"
echo "4. 运行 pnpm install && pnpm db:migrate && pnpm build"
echo "5. 使用 PM2 启动应用"