diff --git a/README.md b/README.md new file mode 100644 index 0000000..c59ef77 --- /dev/null +++ b/README.md @@ -0,0 +1,334 @@ +# EM Script Library + +🚀 **EM Script Library** - Debian 12 系统部署优化脚本库 + +专为解决国内 Debian 12 系统部署时的各种配置问题而设计,提供一站式自动化配置解决方案。 + +## 📋 特性 + +- 🎯 **专注 Debian 12** - 专门针对 Debian 12 优化 +- 🌏 **国内源支持** - 支持阿里云、清华、网易、中科大、华为云等多源 +- 🔧 **模块化设计** - 独立脚本,便于调试和维护 +- ⚡ **自动化配置** - 一键执行完整配置流程 +- 🔒 **安全加固** - 内置安全配置和入侵检测 +- 📊 **状态监控** - 提供详细的配置状态检查 + +## 📁 目录结构 + +``` +em-script/ +├── em-setup.sh # 主入口脚本 +├── scripts/ +│ ├── sources/ # 国内源配置 +│ │ └── configure_sources.sh +│ ├── packages/ # 包管理配置 +│ │ └── configure_packages.sh +│ ├── system/ # 系统配置 +│ │ └── configure_system.sh +│ ├── network/ # 网络优化 +│ │ └── configure_network.sh +│ └── security/ # 安全配置 +│ └── configure_security.sh +├── config/ # 配置文件目录 +├── lib/ # 公共函数库 +├── docs/ # 文档 +└── tests/ # 测试脚本 +``` + +## 🚀 快速开始 + +### 1. 下载脚本库 + +```bash +git clone https://github.com/your-repo/em-script.git +cd em-script +``` + +### 2. 给脚本执行权限 + +```bash +chmod +x em-setup.sh +chmod +x scripts/*/*.sh +``` + +### 3. 执行完整配置 + +```bash +sudo ./em-setup.sh all +``` + +## 📖 使用方法 + +### 主入口脚本 + +```bash +# 显示帮助信息 +./em-setup.sh -h + +# 执行完整配置 +sudo ./em-setup.sh all + +# 配置国内源 +sudo ./em-setup.sh sources aliyun + +# 配置系统 +sudo ./em-setup.sh system + +# 配置网络 +sudo ./em-setup.sh network + +# 配置安全 +sudo ./em-setup.sh security +``` + +### 单独执行脚本 + +```bash +# 配置阿里云源 +sudo ./scripts/sources/configure_sources.sh aliyun + +# 安装基础工具 +sudo ./scripts/packages/configure_packages.sh basic + +# 配置时区 +sudo ./scripts/system/configure_system.sh timezone + +# 测试网络 +sudo ./scripts/network/configure_network.sh network-test + +# 配置防火墙 +sudo ./scripts/security/configure_security.sh fail2ban +``` + +## 🔧 功能模块 + +### 📡 国内源配置 (sources) + +- ✅ 阿里云镜像源 +- ✅ 清华大学镜像源 +- ✅ 网易镜像源 +- ✅ 中科大镜像源 +- ✅ 华为云镜像源 +- ✅ 自动选择最快源 +- ✅ 源配置备份恢复 + +```bash +# 配置阿里云源 +sudo ./scripts/sources/configure_sources.sh aliyun + +# 自动选择最快源 +sudo ./scripts/sources/configure_sources.sh test + +# 备份当前配置 +sudo ./scripts/sources/configure_sources.sh backup +``` + +### 📦 包管理配置 (packages) + +- ✅ apt 配置优化 +- ✅ 基础工具安装 +- ✅ 开发工具安装 +- ✅ **Docker CE 安装 (国内源)** +- ✅ **Docker 镜像加速器配置** +- ✅ 网络工具安装 +- ✅ 监控工具安装 +- ✅ 包缓存清理 + +```bash +# 优化 apt 配置 +sudo ./scripts/packages/configure_packages.sh optimize + +# 从国内源安装 Docker CE +sudo ./scripts/packages/configure_packages.sh docker +# 或单独运行 +sudo ./scripts/packages/install_docker.sh + +# Docker 镜像加速器设置 +sudo ./scripts/packages/setup_docker_mirrors.sh add aliyun # 添加阿里云镜像 +sudo ./scripts/packages/setup_docker_mirrors.sh recommend # 设置推荐组合 +sudo ./scripts/packages/setup_docker_mirrors.sh test # 测试镜像源速度 + +# 安装开发环境 (不含 Docker) +sudo ./scripts/packages/configure_packages.sh dev + +# 查看包信息 +sudo ./scripts/packages/configure_packages.sh info +``` + +### ⚙️ 系统配置 (system) + +- ✅ 时区配置 (Asia/Shanghai) +- ✅ NTP 时间同步 +- ✅ 语言环境配置 +- ✅ 系统限制优化 +- ✅ SSH 服务配置 +- ✅ UFW 防火墙配置 +- ✅ 日志轮转配置 + +```bash +# 配置时区和 NTP +sudo ./scripts/system/configure_system.sh timezone + +# 配置防火墙 +sudo ./scripts/system/configure_system.sh firewall + +# 执行所有系统配置 +sudo ./scripts/system/configure_system.sh all +``` + +### 🌐 网络优化 (network) + +- ✅ DNS 配置 (国内 DNS) +- ✅ DNS 解析速度测试 +- ✅ 网络接口配置 +- ✅ 代理配置 +- ✅ 网络连接测试 +- ✅ IPv6 支持配置 + +```bash +# 配置国内 DNS +sudo ./scripts/network/configure_network.sh dns + +# 测试网络连接 +sudo ./scripts/network/configure_network.sh network-test + +# 配置 HTTP 代理 +sudo ./scripts/network/configure_network.sh proxy http 127.0.0.1 8080 + +# 查看网络信息 +sudo ./scripts/network/configure_network.sh info +``` + +### 🔒 安全配置 (security) + +- ✅ Fail2Ban 入侵检测 +- ✅ 自动安全更新 +- ✅ SSH 配置强化 +- ✅ AppArmor 配置 +- ✅ 内核安全参数 +- ✅ ClamAV 杀毒软件 +- ✅ sudo 安全策略 + +```bash +# 配置入侵检测 +sudo ./scripts/security/configure_security.sh fail2ban + +# 强化 SSH 配置 +sudo ./scripts/security/configure_security.sh ssh-harden + +# 查看安全状态 +sudo ./scripts/security/configure_security.sh status +``` + +## 🔍 测试和验证 + +### 运行测试脚本 + +```bash +# 执行所有测试 +bash tests/run_all_tests.sh + +# 测试源配置 +bash tests/test_sources.sh + +# 测试网络连接 +bash tests/test_network.sh +``` + +### 验证配置结果 + +```bash +# 检查源配置 +cat /etc/apt/sources.list + +# 检查 DNS 配置 +cat /etc/resolv.conf + +# 检查防火墙状态 +ufw status + +# 检查 SSH 配置 +sshd -T | grep -E "(permitrootlogin|passwordauthentication)" + +# 检查安全状态 +sudo ./scripts/security/configure_security.sh status +``` + +## 📝 日志和调试 + +### 日志位置 + +- 系统日志: `/var/log/syslog` +- 认证日志: `/var/log/auth.log` +- apt 日志: `/var/log/apt/` +- Fail2Ban 日志: `/var/log/fail2ban.log` +- 自定义日志: `/var/log/em-script/` + +### 调试模式 + +```bash +# 启用调试模式运行 +sudo DEBUG=1 ./em-setup.sh sources + +# 查看详细日志 +tail -f /var/log/syslog + +# 检查脚本执行状态 +echo $? +``` + +## 🤝 贡献指南 + +1. Fork 本项目 +2. 创建特性分支 (`git checkout -b feature/AmazingFeature`) +3. 提交更改 (`git commit -m 'Add some AmazingFeature'`) +4. 推送到分支 (`git push origin feature/AmazingFeature`) +5. 创建 Pull Request + +## 📄 许可证 + +本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情 + +## ⚠️ 注意事项 + +- 🔴 **生产环境使用前请务必测试** +- 🔴 **建议在测试环境先验证配置** +- 🔴 **重要操作前请备份数据** +- 🔴 **定期更新系统和安全补丁** + +## 🆘 常见问题 + +### Q: 配置失败怎么办? + +A: 检查日志文件,常见问题: +- 网络连接问题 +- 权限不足 +- 依赖包缺失 + +### Q: 如何回滚配置? + +A: 大部分脚本都支持备份恢复: +```bash +# 恢复源配置 +sudo ./scripts/sources/configure_sources.sh restore /path/to/backup + +# 重新配置网络 +sudo ./scripts/network/configure_network.sh interfaces +``` + +### Q: 如何自定义配置? + +A: 编辑对应的配置文件: +- `/etc/apt/sources.list` - 源配置 +- `/etc/resolv.conf` - DNS 配置 +- `/etc/ssh/sshd_config` - SSH 配置 + +## 📞 联系我们 + +- 项目主页: [GitHub](https://github.com/your-repo/em-script) +- 问题反馈: [Issues](https://github.com/your-repo/em-script/issues) +- 邮箱: your-email@example.com + +--- + +⭐ 如果这个项目对你有帮助,请给它一个 Star! \ No newline at end of file diff --git a/em-setup.sh b/em-setup.sh new file mode 100644 index 0000000..a758af3 --- /dev/null +++ b/em-setup.sh @@ -0,0 +1,195 @@ +#!/bin/bash + +# EM Script Library - Debian 12 系统部署脚本库 +# 用于解决国内源配置和系统优化问题 + +set -e # 遇到错误立即退出 + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 检查是否为 root 用户 +check_root() { + if [[ $EUID -ne 0 ]]; then + log_error "此脚本需要 root 权限运行" + log_info "请使用 sudo bash $0 或切换到 root 用户" + exit 1 + fi +} + +# 检查操作系统 +check_os() { + if [[ ! -f /etc/debian_version ]]; then + log_error "此脚本仅支持 Debian 系统" + exit 1 + fi + + local version=$(cat /etc/debian_version | cut -d. -f1) + if [[ $version -ne 12 ]]; then + log_warning "此脚本针对 Debian 12 优化,当前版本: $version" + fi + + log_success "检测到 Debian $version 系统" +} + +# 显示帮助信息 +show_help() { + cat << EOF +EM Script Library - Debian 12 系统部署工具 + +用法: $0 [选项] [模块] + +选项: + -h, --help 显示此帮助信息 + -l, --list 列出所有可用模块 + -v, --version 显示版本信息 + -d, --debug 启用调试模式 + +模块: + sources 配置国内软件源 + packages 包管理相关操作 + system 系统基础配置 + network 网络优化配置 + security 安全配置 + all 执行所有模块 + +示例: + $0 sources # 配置国内源 + $0 sources aliyun # 使用阿里云源 + $0 all # 执行所有配置 + +EOF +} + +# 显示版本信息 +show_version() { + echo "EM Script Library v1.0.0" + echo "针对 Debian 12 优化的系统部署工具" +} + +# 列出可用模块 +list_modules() { + echo "可用模块:" + echo " sources - 国内软件源配置" + echo " packages - 包管理工具配置" + echo " system - 系统基础配置" + echo " network - 网络优化配置" + echo " security - 安全配置" + echo "" + echo "使用方法: $0 <模块名>" +} + +# 主函数 +main() { + local debug=false + local module="" + + # 参数解析 + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + show_help + exit 0 + ;; + -v|--version) + show_version + exit 0 + ;; + -l|--list) + list_modules + exit 0 + ;; + -d|--debug) + debug=true + shift + ;; + -*) + log_error "未知选项: $1" + show_help + exit 1 + ;; + *) + module="$1" + shift + break + ;; + esac + done + + # 调试模式 + if [[ "$debug" == "true" ]]; then + set -x + log_info "调试模式已启用" + fi + + # 检查环境 + check_root + check_os + + # 执行模块 + case $module in + sources) + log_info "开始配置国内软件源..." + bash scripts/sources/configure_sources.sh "$@" + ;; + packages) + log_info "开始配置包管理工具..." + bash scripts/packages/configure_packages.sh "$@" + ;; + system) + log_info "开始系统基础配置..." + bash scripts/system/configure_system.sh "$@" + ;; + network) + log_info "开始网络优化配置..." + bash scripts/network/configure_network.sh "$@" + ;; + security) + log_info "开始安全配置..." + bash scripts/security/configure_security.sh "$@" + ;; + all) + log_info "开始执行完整配置流程..." + bash scripts/sources/configure_sources.sh + bash scripts/packages/configure_packages.sh + bash scripts/system/configure_system.sh + bash scripts/network/configure_network.sh + bash scripts/security/configure_security.sh + log_success "所有配置完成!" + ;; + "") + log_error "未指定模块" + list_modules + exit 1 + ;; + *) + log_error "未知模块: $module" + list_modules + exit 1 + ;; + esac +} + +# 执行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/network/configure_network.sh b/scripts/network/configure_network.sh new file mode 100644 index 0000000..dcb06c9 --- /dev/null +++ b/scripts/network/configure_network.sh @@ -0,0 +1,364 @@ +#!/bin/bash + +# Debian 12 网络配置脚本 +# 网络优化和配置 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 配置 DNS +configure_dns() { + log_info "配置 DNS 服务器..." + + # 备份原始 resolv.conf + cp /etc/resolv.conf /etc/resolv.conf.backup + + # 配置国内 DNS 服务器 + cat > /etc/resolv.conf << 'EOF' +# EM Script Library - DNS Configuration +nameserver 223.5.5.5 # AliDNS +nameserver 223.6.6.6 # AliDNS +nameserver 119.29.29.29 # DNSPod +nameserver 182.254.116.116 # DNSPod +nameserver 114.114.114.114 # 114DNS +nameserver 8.8.8.8 # Google DNS (fallback) +nameserver 1.1.1.1 # Cloudflare DNS (fallback) +EOF + + # 防止网络管理器覆盖 DNS 配置 + if [[ -f /etc/NetworkManager/NetworkManager.conf ]]; then + sed -i '/\[main\]/a dns=none' /etc/NetworkManager/NetworkManager.conf + systemctl restart NetworkManager + fi + + log_success "DNS 配置完成" +} + +# 测试 DNS 解析速度 +test_dns_speed() { + log_info "测试 DNS 解析速度..." + + local domains=("www.baidu.com" "www.qq.com" "www.taobao.com" "www.github.com") + local dns_servers=( + "223.5.5.5|AliDNS" + "119.29.29.29|DNSPod" + "114.114.114.114|114DNS" + "8.8.8.8|Google" + "1.1.1.1|Cloudflare" + ) + + echo "DNS 服务器性能测试:" + echo "==========================================" + + for dns_server in "${dns_servers[@]}"; do + local server=$(echo "$dns_server" | cut -d'|' -f1) + local name=$(echo "$dns_server" | cut -d'|' -f2) + + local total_time=0 + local success_count=0 + + for domain in "${domains[@]}"; do + local start_time=$(date +%s%N) + if nslookup "$domain" "$server" >/dev/null 2>&1; then + local end_time=$(date +%s%N) + local time_diff=$(( (end_time - start_time) / 1000000 )) + total_time=$((total_time + time_diff)) + success_count=$((success_count + 1)) + fi + done + + if [[ $success_count -gt 0 ]]; then + local avg_time=$((total_time / success_count)) + printf "%-12s %-10s %dms (成功: %d/%d)\n" "$server" "$name" "$avg_time" "$success_count" "${#domains[@]}" + else + printf "%-12s %-10s 失败\n" "$server" "$name" + fi + done + + log_success "DNS 测试完成" +} + +# 配置网络接口 +configure_interfaces() { + log_info "配置网络接口..." + + # 获取网络接口信息 + local interfaces=$(ip -o link show | awk -F': ' '{print $2}' | grep -v lo) + + for interface in $interfaces; do + log_info "配置接口: $interface" + + # 创建网络接口配置 + cat > "/etc/network/interfaces.d/$interface" << EOF +# EM Script Library - Network Interface Configuration +auto $interface +iface $interface inet dhcp + +# DNS 配置 +dns-nameservers 223.5.5.5 223.6.6.6 119.29.29.29 +dns-search local + +# MTU 设置 (可选) +# mtu 1500 +EOF + done + + log_success "网络接口配置完成" +} + +# 配置网络代理 +configure_proxy() { + local proxy_type="$1" + local proxy_host="$2" + local proxy_port="$3" + + if [[ -z "$proxy_host" || -z "$proxy_port" ]]; then + log_error "请提供代理主机和端口" + echo "用法: $0 proxy <类型> <主机> <端口>" + echo "类型: http, https, socks5" + return 1 + fi + + log_info "配置 $proxy_type 代理: $proxy_host:$proxy_port" + + case $proxy_type in + http) + export http_proxy="http://$proxy_host:$proxy_port" + export https_proxy="http://$proxy_host:$proxy_port" + ;; + https) + export http_proxy="https://$proxy_host:$proxy_port" + export https_proxy="https://$proxy_host:$proxy_port" + ;; + socks5) + export http_proxy="socks5://$proxy_host:$proxy_port" + export https_proxy="socks5://$proxy_host:$proxy_port" + ;; + *) + log_error "不支持的代理类型: $proxy_type" + return 1 + ;; + esac + + # 配置系统代理 + cat > /etc/environment << EOF +# EM Script Library - System Proxy Configuration +http_proxy=$http_proxy +https_proxy=$https_proxy +ftp_proxy=$http_proxy +no_proxy=localhost,127.0.0.1,::1,.local +EOF + + # 配置 apt 代理 + cat > /etc/apt/apt.conf.d/99proxy << EOF +# EM Script Library - APT Proxy Configuration +Acquire::http::Proxy "$http_proxy"; +Acquire::https::Proxy "$https_proxy"; +EOF + + # 配置 wget 代理 + cat > /root/.wgetrc << EOF +# EM Script Library - Wget Proxy Configuration +http_proxy=$http_proxy +https_proxy=$https_proxy +EOF + + # 配置 curl 代理 + cat > /root/.curlrc << EOF +# EM Script Library - Curl Proxy Configuration +proxy=$http_proxy +EOF + + log_success "代理配置完成" +} + +# 移除代理配置 +remove_proxy() { + log_info "移除代理配置..." + + unset http_proxy https_proxy ftp_proxy no_proxy + + rm -f /etc/environment + rm -f /etc/apt/apt.conf.d/99proxy + rm -f /root/.wgetrc + rm -f /root/.curlrc + + log_success "代理配置已移除" +} + +# 测试网络连接 +test_network() { + log_info "测试网络连接..." + + local test_hosts=( + "223.5.5.5|阿里DNS" + "www.baidu.com|百度" + "www.qq.com|腾讯" + "www.github.com|GitHub" + "registry.npmmirror.com|NPM镜像" + "pypi.tuna.tsinghua.edu.cn|PyPI镜像" + ) + + echo "网络连接测试:" + echo "==========================================" + + for host_info in "${test_hosts[@]}"; do + local host=$(echo "$host_info" | cut -d'|' -f1) + local name=$(echo "$host_info" | cut -d'|' -f2) + + if ping -c 3 -W 3 "$host" >/dev/null 2>&1; then + local ping_time=$(ping -c 3 "$host" | tail -1 | awk '{print $4}' | cut -d'/' -f2) + printf "%-30s ✓ %s ms\n" "$name ($host)" "$ping_time" + else + printf "%-30s ✗ 连接失败\n" "$name ($host)" + fi + done + + log_success "网络测试完成" +} + +# 配置 IPv6 +configure_ipv6() { + log_info "配置 IPv6 支持..." + + # 启用 IPv6 + sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="[^"]*/& ipv6.disable=0/' /etc/default/grub + sed -i 's/GRUB_CMDLINE_LINUX="[^"]*/& ipv6.disable=0/' /etc/default/grub + + update-grub + + # 配置 sysctl IPv6 参数 + cat >> /etc/sysctl.d/99-custom.conf << 'EOF' + +# IPv6 configuration +net.ipv6.conf.all.disable_ipv6 = 0 +net.ipv6.conf.default.disable_ipv6 = 0 +net.ipv6.conf.lo.disable_ipv6 = 0 +EOF + + sysctl -p + + log_success "IPv6 配置完成,重启后生效" +} + +# 显示网络信息 +show_network_info() { + log_info "网络配置信息:" + + echo "=== 网络接口 ===" + ip addr show + + echo "" + echo "=== 路由表 ===" + ip route show + + echo "" + echo "=== DNS 配置 ===" + cat /etc/resolv.conf + + echo "" + echo "=== 网络连接 ===" + ss -tuln + + echo "" + echo "=== 网络统计 ===" + ip -s link +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 网络配置工具 + +用法: $0 [选项] [操作] + +操作: + dns 配置 DNS 服务器 + dns-test 测试 DNS 解析速度 + interfaces 配置网络接口 + proxy 配置网络代理 + remove-proxy 移除代理配置 + network-test 测试网络连接 + ipv6 配置 IPv6 支持 + info 显示网络信息 + +选项: + -h, --help 显示此帮助信息 + +示例: + $0 dns # 配置 DNS + $0 proxy http 127.0.0.1 8080 # 配置 HTTP 代理 + $0 network-test # 测试网络连接 + $0 info # 显示网络信息 + +EOF +} + +# 主函数 +main() { + local action="$1" + + case $action in + dns) + configure_dns + ;; + dns-test) + test_dns_speed + ;; + interfaces) + configure_interfaces + ;; + proxy) + shift + configure_proxy "$@" + ;; + remove-proxy) + remove_proxy + ;; + network-test) + test_network + ;; + ipv6) + configure_ipv6 + ;; + info) + show_network_info + ;; + ""|-h|--help) + show_help + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + log_success "网络配置完成!" +} + +# 执行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/packages/configure_packages.sh b/scripts/packages/configure_packages.sh new file mode 100755 index 0000000..03dec22 --- /dev/null +++ b/scripts/packages/configure_packages.sh @@ -0,0 +1,368 @@ +#!/bin/bash + +# Debian 12 包管理配置脚本 +# 优化 apt 配置和安装基础软件 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 优化 apt 配置 +optimize_apt() { + log_info "优化 apt 配置..." + + # 创建 apt 配置目录 + mkdir -p /etc/apt/apt.conf.d + + # 配置 apt 并发连接数 + cat > /etc/apt/apt.conf.d/99custom << 'EOF' +Acquire::http::Timeout "30"; +Acquire::ftp::Timeout "30"; +Acquire::Retries "3"; +Acquire::http::Pipeline-Depth "0"; +Acquire::http::No-Cache "true"; +Acquire::BrokenProxy "true"; +Acquire::http::Proxy-Auto-Detect "/usr/local/bin/apt-proxy-detect"; +EOF + + # 配置多线程下载 + cat > /etc/apt/apt.conf.d/99parallel << 'EOF' +Acquire::Queue-Mode "access"; +Acquire::Retries "0"; +Acquire::http::Dl-Limit "0"; +Acquire::https::Dl-Limit "0"; +Acquire::ftp::Dl-Limit "0"; +EOF + + log_success "apt 配置优化完成" +} + +# 安装基础工具 +install_basic_tools() { + log_info "安装基础工具..." + + local packages=( + curl + wget + git + vim + htop + net-tools + dnsutils + telnet + unzip + zip + tree + jq + ncdu + tmux + screen + lsof + psmisc + apt-transport-https + ca-certificates + gnupg + gnupg2 + software-properties-common + ) + + apt update + apt install -y "${packages[@]}" + + log_success "基础工具安装完成" +} + +# 安装 Docker (从国内源) +install_docker() { + log_info "从国内源安装 Docker..." + + # 卸载可能存在的旧版本 + apt remove -y docker docker-engine docker.io containerd runc 2>/dev/null || true + + # 更新包索引 + apt update + + # 安装必要的包 + apt install -y ca-certificates curl gnupg lsb-release + + # 添加 Docker 的官方 GPG 密钥 + mkdir -p /etc/apt/keyrings + curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg + + # 设置仓库 + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null + + # 更新包索引 + apt update + + # 安装 Docker 最新版本 + apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + + # 配置 Docker 使用国内镜像 + mkdir -p /etc/docker + cat > /etc/docker/daemon.json << 'EOF' +{ + "registry-mirrors": [ + "https://registry.docker-cn.com", + "https://docker.mirrors.ustc.edu.cn", + "https://hub-mirror.c.163.com" + ], + "log-driver": "json-file", + "log-opts": { + "max-size": "100m", + "max-file": "3" + } +} +EOF + + # 启动 Docker 服务 + systemctl enable docker + systemctl start docker + + # 添加当前用户到 docker 组(如果用户存在) + if id -u "$SUDO_USER" >/dev/null 2>&1; then + usermod -aG docker "$SUDO_USER" + log_info "已将用户 $SUDO_USER 添加到 docker 组,请重新登录以生效" + fi + + # 测试 Docker 安装 + if docker --version >/dev/null 2>&1; then + log_success "Docker 安装成功,版本: $(docker --version)" + log_info "Docker 镜像加速器已配置" + else + log_error "Docker 安装失败" + exit 1 + fi +} + +# 安装开发工具 +install_dev_tools() { + log_info "安装开发工具..." + + local packages=( + build-essential + cmake + ninja-build + python3 + python3-pip + python3-venv + python3-dev + nodejs + npm + golang + rustc + cargo + openjdk-17-jdk + maven + gradle + ) + + apt update + apt install -y "${packages[@]}" + + # 配置 Python pip 国内源 + mkdir -p /root/.pip + cat > /root/.pip/pip.conf << 'EOF' +[global] +index-url = https://pypi.tuna.tsinghua.edu.cn/simple +[install] +trusted-host = https://pypi.tuna.tsinghua.edu.cn +EOF + + # 配置 npm 国内源 + npm config set registry https://registry.npmmirror.com + + # 配置 Go 国内代理 + mkdir -p /root/go + echo 'export GOPROXY=https://goproxy.cn,direct' >> /root/.bashrc + echo 'export GO111MODULE=on' >> /root/.bashrc + + # 配置 Rust 国内源 + mkdir -p /root/.cargo + cat > /root/.cargo/config << 'EOF' +[source.crates-io] +replace-with = 'tuna' + +[source.tuna] +registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git" +EOF + + log_success "开发工具安装完成" +} + +# 安装网络工具 +install_network_tools() { + log_info "安装网络工具..." + + local packages=( + openssh-server + openssh-client + iptables + ufw + fail2ban + nmap + tcpdump + wireshark + iperf3 + mtr + traceroute + whois + ntp + chrony + ) + + apt update + apt install -y "${packages[@]}" + + log_success "网络工具安装完成" +} + +# 安装监控工具 +install_monitoring_tools() { + log_info "安装监控工具..." + + local packages=( + prometheus + prometheus-node-exporter + grafana + zabbix-agent + nagios-nrpe-plugin + munin-node + collectd + sysstat + iotop + atop + nmon + ) + + apt update + apt install -y "${packages[@]}" + + log_success "监控工具安装完成" +} + +# 清理包缓存 +clean_cache() { + log_info "清理包缓存..." + + apt autoremove -y + apt autoclean -y + apt clean -y + + log_success "包缓存清理完成" +} + +# 显示包信息 +show_package_info() { + log_info "系统包信息:" + + echo "已安装包数量: $(dpkg -l | grep '^ii' | wc -l)" + echo "可用更新: $(apt list --upgradable 2>/dev/null | grep -v "Listing" | wc -l)" + echo "磁盘使用情况:" + df -h /var/cache/apt +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 包管理配置工具 + +用法: $0 [选项] [操作] + +操作: + optimize 优化 apt 配置 + basic 安装基础工具 + dev 安装开发工具 (不含 Docker) + docker 从国内源安装 Docker + network 安装网络工具 + monitor 安装监控工具 + clean 清理包缓存 + info 显示包信息 + all 执行所有操作 + +选项: + -h, --help 显示此帮助信息 + +示例: + $0 optimize # 优化 apt 配置 + $0 basic # 安装基础工具 + $0 docker # 从国内源安装 Docker + $0 all # 执行所有操作 + +EOF +} + +# 主函数 +main() { + local action="$1" + + case $action in + optimize) + optimize_apt + ;; + basic) + install_basic_tools + ;; + dev) + install_dev_tools + ;; + docker) + install_docker + ;; + network) + install_network_tools + ;; + monitor) + install_monitoring_tools + ;; + clean) + clean_cache + ;; + info) + show_package_info + ;; + all) + optimize_apt + install_basic_tools + install_dev_tools + install_docker + install_network_tools + install_monitoring_tools + ;; + ""|-h|--help) + show_help + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + log_success "包管理配置完成!" +} + +# 执行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/packages/install_docker.sh b/scripts/packages/install_docker.sh new file mode 100755 index 0000000..5501bd1 --- /dev/null +++ b/scripts/packages/install_docker.sh @@ -0,0 +1,331 @@ +#!/bin/bash + +# Debian 12 Docker 安装脚本 (使用国内源) +# 从国内镜像源安装 Docker CE + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 检查系统要求 +check_system() { + log_info "检查系统要求..." + + # 检查是否为 Debian 系统 + if ! command -v lsb_release &> /dev/null; then + apt update && apt install -y lsb-release + fi + + local distro=$(lsb_release -si) + local version=$(lsb_release -sr) + + if [[ "$distro" != "Debian" ]]; then + log_error "此脚本仅支持 Debian 系统" + exit 1 + fi + + if [[ "${version%%.*}" -lt 10 ]]; then + log_error "此脚本需要 Debian 10 或更高版本" + exit 1 + fi + + # 检查架构 + local arch=$(dpkg --print-architecture) + if [[ "$arch" != "amd64" && "$arch" != "arm64" ]]; then + log_error "不支持的架构: $arch" + exit 1 + fi + + log_success "系统检查通过: $distro $version ($arch)" +} + +# 卸载旧版本 +uninstall_old_versions() { + log_info "卸载可能存在的旧版本 Docker..." + + # 停止所有运行中的容器 + if command -v docker &> /dev/null; then + docker stop $(docker ps -aq) 2>/dev/null || true + fi + + # 卸载旧版本 + apt remove -y docker docker-engine docker.io containerd runc docker-compose 2>/dev/null || true + + # 清理相关文件 + rm -rf /var/lib/docker /etc/docker + rm -f /etc/apt/sources.list.d/docker.list + rm -f /etc/apt/keyrings/docker.gpg + + log_success "旧版本清理完成" +} + +# 安装依赖包 +install_dependencies() { + log_info "安装依赖包..." + + apt update + apt install -y \ + ca-certificates \ + curl \ + gnupg \ + lsb-release \ + apt-transport-https \ + software-properties-common + + log_success "依赖包安装完成" +} + +# 添加 Docker 仓库 +add_docker_repository() { + log_info "添加 Docker 仓库 (使用清华大学镜像源)..." + + # 创建密钥目录 + mkdir -p /etc/apt/keyrings + + # 下载并添加 GPG 密钥 + curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg + + # 添加仓库 + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null + + log_success "Docker 仓库添加完成" +} + +# 安装 Docker +install_docker() { + log_info "安装 Docker CE..." + + # 更新包索引 + apt update + + # 安装 Docker CE + apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + + log_success "Docker CE 安装完成" +} + +# 配置 Docker +configure_docker() { + log_info "配置 Docker..." + + # 创建配置目录 + mkdir -p /etc/docker + + # 配置 daemon.json + cat > /etc/docker/daemon.json << 'EOF' +{ + "registry-mirrors": [ + "https://registry.docker-cn.com", + "https://docker.mirrors.ustc.edu.cn", + "https://hub-mirror.c.163.com", + "https://mirror.baidubce.com" + ], + "log-driver": "json-file", + "log-opts": { + "max-size": "100m", + "max-file": "3" + }, + "storage-driver": "overlay2", + "exec-opts": ["native.cgroupdriver=systemd"], + "iptables": false +} +EOF + + # 配置 containerd + mkdir -p /etc/containerd + containerd config default | tee /etc/containerd/config.toml > /dev/null + + # 重新加载配置 + systemctl daemon-reload + + log_success "Docker 配置完成" +} + +# 启动服务 +start_services() { + log_info "启动 Docker 服务..." + + # 启动服务 + systemctl enable docker + systemctl enable containerd + systemctl start docker + systemctl start containerd + + # 等待服务启动 + sleep 2 + + # 检查服务状态 + if systemctl is-active --quiet docker; then + log_success "Docker 服务启动成功" + else + log_error "Docker 服务启动失败" + journalctl -u docker --no-pager -n 20 + exit 1 + fi +} + +# 配置用户权限 +configure_user_permissions() { + log_info "配置用户权限..." + + # 获取当前用户 + local current_user="" + if [[ -n "$SUDO_USER" ]]; then + current_user="$SUDO_USER" + elif [[ -n "$USER" && "$USER" != "root" ]]; then + current_user="$USER" + fi + + if [[ -n "$current_user" ]]; then + # 检查用户是否存在 + if id "$current_user" &>/dev/null; then + usermod -aG docker "$current_user" + log_success "已将用户 $current_user 添加到 docker 组" + log_warning "请重新登录或运行 'newgrp docker' 以使权限生效" + fi + fi +} + +# 测试安装 +test_installation() { + log_info "测试 Docker 安装..." + + # 检查版本 + local docker_version=$(docker --version) + local docker_compose_version=$(docker compose version 2>/dev/null || echo "docker-compose plugin") + + log_success "Docker 版本: $docker_version" + log_info "Docker Compose: $docker_compose_version" + + # 运行测试容器 + log_info "运行测试容器..." + if docker run --rm hello-world >/dev/null 2>&1; then + log_success "Docker 测试通过!" + else + log_warning "Docker 运行测试失败,但安装可能成功。请检查网络连接。" + fi + + # 显示使用信息 + cat << 'EOF' + +Docker 安装完成! + +常用命令: + docker --version # 查看版本 + docker run hello-world # 运行测试容器 + docker ps -a # 查看所有容器 + docker images # 查看镜像 + docker pull # 拉取镜像 + docker build -t . # 构建镜像 + +服务管理: + sudo systemctl start docker # 启动服务 + sudo systemctl stop docker # 停止服务 + sudo systemctl restart docker # 重启服务 + +配置说明: + - 已配置国内镜像加速器 + - 日志轮转已配置 (最大100M,保留3个文件) + - 使用 overlay2 存储驱动 + - 已启用 systemd cgroup 驱动 + +EOF +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 Docker 安装脚本 + +此脚本将从清华大学镜像源安装 Docker CE,并配置国内镜像加速器。 + +用法: $0 [选项] + +选项: + -h, --help 显示此帮助信息 + -f, --force 强制重新安装(不检查现有安装) + +示例: + $0 # 正常安装 + $0 --force # 强制重新安装 + +EOF +} + +# 主函数 +main() { + local force_install=false + + # 解析参数 + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + show_help + exit 0 + ;; + -f|--force) + force_install=true + shift + ;; + *) + log_error "未知选项: $1" + show_help + exit 1 + ;; + esac + done + + # 检查是否为 root 用户 + if [[ $EUID -ne 0 ]]; then + log_error "请使用 root 用户或 sudo 运行此脚本" + exit 1 + fi + + # 检查是否已安装 + if command -v docker &> /dev/null && [[ "$force_install" != true ]]; then + log_warning "Docker 已经安装。如需重新安装,请使用 --force 选项。" + docker --version + exit 0 + fi + + log_info "开始安装 Docker CE..." + echo + + check_system + uninstall_old_versions + install_dependencies + add_docker_repository + install_docker + configure_docker + start_services + configure_user_permissions + test_installation + + echo + log_success "Docker 安装完成!" +} + +# 执行主函数 +main "$@" diff --git a/scripts/packages/setup_docker_mirrors.sh b/scripts/packages/setup_docker_mirrors.sh new file mode 100755 index 0000000..86f50be --- /dev/null +++ b/scripts/packages/setup_docker_mirrors.sh @@ -0,0 +1,511 @@ +#!/bin/bash + +# Docker 镜像加速器快速设置脚本 +# 支持多种国内镜像源配置 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +PURPLE='\033[0;35m' +CYAN='\033[0;36m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +log_title() { + echo -e "${PURPLE}[DOCKER MIRRORS]${NC} $1" +} + +# 镜像源配置 +MIRRORS_aliyun="https://registry.cn-hangzhou.aliyuncs.com" +MIRRORS_tencent="https://mirror.ccs.tencentyun.com" +MIRRORS_huawei="https://mirror-1.trustie.net" +MIRRORS_netease="https://hub-mirror.c.163.com" +MIRRORS_ustc="https://docker.mirrors.ustc.edu.cn" +MIRRORS_docker_cn="https://registry.docker-cn.com" +MIRRORS_baidu="https://mirror.baidubce.com" +MIRRORS_tsinghua="https://mirrors.tuna.tsinghua.edu.cn" + +# 镜像源名称数组 +MIRROR_NAMES=("aliyun" "tencent" "huawei" "netease" "ustc" "docker_cn" "baidu" "tsinghua") + +# 配置文件路径 +DOCKER_CONFIG="/etc/docker/daemon.json" +DOCKER_CONFIG_BACKUP="/etc/docker/daemon.json.backup.$(date +%Y%m%d_%H%M%S)" + +# 检查 Docker 是否安装 +check_docker() { + if ! command -v docker &> /dev/null; then + log_error "Docker 未安装,请先安装 Docker" + echo "运行以下命令安装 Docker:" + echo " sudo ./scripts/packages/install_docker.sh" + exit 1 + fi + + if ! systemctl is-active --quiet docker; then + log_warning "Docker 服务未运行,正在启动..." + systemctl start docker + sleep 2 + if ! systemctl is-active --quiet docker; then + log_error "无法启动 Docker 服务" + exit 1 + fi + log_success "Docker 服务已启动" + fi +} + +# 检查 Docker 配置文件 +check_config() { + if [[ ! -f "$DOCKER_CONFIG" ]]; then + log_info "创建 Docker 配置文件..." + mkdir -p /etc/docker + echo '{}' > "$DOCKER_CONFIG" + fi +} + +# 备份当前配置 +backup_config() { + if [[ -f "$DOCKER_CONFIG" ]]; then + cp "$DOCKER_CONFIG" "$DOCKER_CONFIG_BACKUP" + log_info "配置已备份到: $DOCKER_CONFIG_BACKUP" + fi +} + +# 获取当前配置 +get_current_config() { + if [[ -f "$DOCKER_CONFIG" ]]; then + cat "$DOCKER_CONFIG" + else + echo "{}" + fi +} + +# 更新配置文件 +update_config() { + local new_config="$1" + echo "$new_config" > "$DOCKER_CONFIG" + log_info "Docker 配置已更新" +} + +# 重启 Docker 服务 +restart_docker() { + log_info "重启 Docker 服务..." + systemctl daemon-reload + systemctl restart docker + + # 等待服务启动 + sleep 3 + + if systemctl is-active --quiet docker; then + log_success "Docker 服务重启成功" + else + log_error "Docker 服务重启失败" + exit 1 + fi +} + +# 显示可用镜像源 +show_available_mirrors() { + log_title "可用 Docker 镜像源" + echo + printf "%-15s %-50s\n" "名称" "地址" + printf "%-15s %-50s\n" "----" "----------------------------------------" + for mirror_name in "${MIRROR_NAMES[@]}"; do + local mirror_var="MIRRORS_${mirror_name}" + local mirror_url="${!mirror_var}" + printf "%-15s %-50s\n" "$mirror_name" "$mirror_url" + done + echo +} + +# 显示当前配置 +show_current_config() { + log_title "当前 Docker 配置" + echo + + if [[ ! -f "$DOCKER_CONFIG" ]]; then + echo "暂无配置文件" + return + fi + + local config=$(get_current_config) + + # 检查是否有 registry-mirrors + if echo "$config" | jq -e '.["registry-mirrors"]' >/dev/null 2>&1; then + local mirrors=$(echo "$config" | jq -r '.["registry-mirrors"][]') + if [[ -n "$mirrors" ]]; then + echo "镜像加速器:" + echo "$mirrors" | while read -r mirror; do + # 反向查找镜像源名称 + local name="未知" + for key in "${!MIRRORS[@]}"; do + if [[ "${MIRRORS[$key]}" == "$mirror" ]]; then + name="$key" + break + fi + done + echo " - $name ($mirror)" + done + else + echo "镜像加速器: 未配置" + fi + else + echo "镜像加速器: 未配置" + fi + + # 显示其他配置 + if echo "$config" | jq -e '.log-driver' >/dev/null 2>&1; then + local log_driver=$(echo "$config" | jq -r '.["log-driver"]') + echo "日志驱动: $log_driver" + fi + + if echo "$config" | jq -e '.log-opts' >/dev/null 2>&1; then + local max_size=$(echo "$config" | jq -r '.["log-opts"]["max-size"] // empty') + local max_file=$(echo "$config" | jq -r '.["log-opts"]["max-file"] // empty') + if [[ -n "$max_size" && -n "$max_file" ]]; then + echo "日志配置: 最大文件大小 $max_size, 保留 $max_file 个文件" + fi + fi + echo +} + +# 添加镜像源 +add_mirror() { + local mirror_name="$1" + + local mirror_var="MIRRORS_${mirror_name}" + if [[ -z "${!mirror_var}" ]]; then + log_error "未知的镜像源: $mirror_name" + show_available_mirrors + exit 1 + fi + + local mirror_url="${!mirror_var}" + + check_config + backup_config + + local config=$(get_current_config) + + # 检查是否已存在 + if echo "$config" | jq -e ".\"registry-mirrors\"[]? | select(. == \"$mirror_url\")" >/dev/null 2>&1; then + log_warning "镜像源 $mirror_name 已经配置" + return + fi + + # 添加到配置中 + if echo "$config" | jq -e '.["registry-mirrors"]' >/dev/null 2>&1; then + # 如果已存在 registry-mirrors 数组,添加到数组中 + config=$(echo "$config" | jq --arg url "$mirror_url" '.["registry-mirrors"] += [$url]') + else + # 如果不存在,创建新的数组 + config=$(echo "$config" | jq --arg url "$mirror_url" '. + {"registry-mirrors": [$url]}') + fi + + update_config "$config" + log_success "已添加镜像源: $mirror_name ($mirror_url)" +} + +# 删除镜像源 +remove_mirror() { + local mirror_name="$1" + + if [[ "$mirror_name" == "all" ]]; then + # 删除所有镜像源 + check_config + backup_config + + local config=$(get_current_config) + config=$(echo "$config" | jq 'del(.["registry-mirrors"])') + update_config "$config" + log_success "已删除所有镜像源" + return + fi + + local mirror_var="MIRRORS_${mirror_name}" + if [[ -z "${!mirror_var}" ]]; then + log_error "未知的镜像源: $mirror_name" + show_available_mirrors + exit 1 + fi + + local mirror_url="${!mirror_var}" + + check_config + backup_config + + local config=$(get_current_config) + + # 检查是否存在 + if ! echo "$config" | jq -e ".\"registry-mirrors\"[]? | select(. == \"$mirror_url\")" >/dev/null 2>&1; then + log_warning "镜像源 $mirror_name 未配置" + return + fi + + # 从配置中删除 + config=$(echo "$config" | jq --arg url "$mirror_url" '.["registry-mirrors"] = (.["registry-mirrors"] | map(select(. != $url)))') + + # 如果数组为空,删除整个键 + if echo "$config" | jq -e '.["registry-mirrors"] | length == 0' >/dev/null 2>&1; then + config=$(echo "$config" | jq 'del(.["registry-mirrors"])') + fi + + update_config "$config" + log_success "已删除镜像源: $mirror_name ($mirror_url)" +} + +# 设置推荐镜像源组合 +set_recommended() { + log_info "设置推荐的镜像源组合 (阿里云 + 网易 + 华为云)..." + + check_config + backup_config + + local config=$(get_current_config) + + # 推荐的镜像源组合 + local recommended_mirrors=( + "https://registry.cn-hangzhou.aliyuncs.com" + "https://hub-mirror.c.163.com" + "https://mirror-1.trustie.net" + ) + + # 创建新的配置 + config=$(echo "$config" | jq --argjson mirrors "$(printf '%s\n' "${recommended_mirrors[@]}" | jq -R . | jq -s .)" '. + {"registry-mirrors": $mirrors}') + + update_config "$config" + log_success "已设置推荐镜像源组合" +} + +# 测试镜像源速度 +test_mirrors() { + log_title "测试镜像源速度" + echo + + local test_image="hello-world:latest" + + # 清理可能存在的测试镜像 + docker rmi "$test_image" >/dev/null 2>&1 || true + + echo "测试镜像: $test_image" + echo "测试结果:" + printf "%-15s %-15s %-20s\n" "镜像源" "状态" "耗时" + printf "%-15s %-15s %-20s\n" "-------" "-----" "----" + + for mirror_name in "${MIRROR_NAMES[@]}"; do + local mirror_var="MIRRORS_${mirror_name}" + local mirror_url="${!mirror_var}" + + # 临时设置镜像源 + check_config + local original_config=$(get_current_config) + local test_config=$(echo "$original_config" | jq --arg url "$mirror_url" '. + {"registry-mirrors": [$url]}') + echo "$test_config" > "$DOCKER_CONFIG" + + restart_docker >/dev/null 2>&1 + + # 测试拉取镜像 + local start_time=$(date +%s.%3N) + if timeout 30 docker pull "$test_image" >/dev/null 2>&1; then + local end_time=$(date +%s.%3N) + local duration=$(echo "$end_time - $start_time" | bc 2>/dev/null || echo "0") + printf "%-15s ${GREEN}%-15s${NC} %-20s\n" "$mirror_name" "成功" "${duration}s" + else + printf "%-15s ${RED}%-15s${NC} %-20s\n" "$mirror_name" "失败" "超时" + fi + + # 清理测试镜像 + docker rmi "$test_image" >/dev/null 2>&1 || true + done + + # 恢复原始配置 + echo "$original_config" > "$DOCKER_CONFIG" + restart_docker >/dev/null 2>&1 + + echo + log_info "速度测试完成" +} + +# 恢复备份配置 +restore_config() { + local backup_file="$1" + + if [[ -z "$backup_file" ]]; then + # 查找最新的备份文件 + backup_file=$(ls -t /etc/docker/daemon.json.backup.* 2>/dev/null | head -1) + if [[ -z "$backup_file" ]]; then + log_error "未找到备份文件" + exit 1 + fi + fi + + if [[ ! -f "$backup_file" ]]; then + log_error "备份文件不存在: $backup_file" + exit 1 + fi + + cp "$backup_file" "$DOCKER_CONFIG" + log_success "已恢复配置: $backup_file" +} + +# 显示帮助信息 +show_help() { + cat << EOF +Docker 镜像加速器快速设置脚本 + +此脚本帮助您快速配置 Docker 镜像加速器,提升镜像拉取速度。 + +用法: $0 [选项] [操作] [参数] + +操作: + list 显示可用镜像源 + show 显示当前配置 + add <镜像源> 添加镜像源 (例: add aliyun) + remove <镜像源> 删除镜像源 (例: remove aliyun) + remove all 删除所有镜像源 + recommend 设置推荐镜像源组合 + test 测试各镜像源速度 + restore [文件] 恢复备份配置 + restart 重启 Docker 服务 + demo 演示模式 (无需 root 权限) + +选项: + -h, --help 显示此帮助信息 + +可用镜像源: + aliyun - 阿里云镜像加速器 + tencent - 腾讯云镜像加速器 + huawei - 华为云镜像加速器 + netease - 网易镜像加速器 (推荐) + ustc - 中科大镜像加速器 + docker_cn - Docker 中国官方镜像 + baidu - 百度云镜像加速器 + tsinghua - 清华大学镜像加速器 (推荐) + +示例: + $0 demo # 演示模式 + sudo $0 list # 显示可用镜像源 + sudo $0 show # 显示当前配置 + sudo $0 add aliyun # 添加阿里云镜像源 + sudo $0 add netease # 添加网易镜像源 + sudo $0 recommend # 设置推荐组合 (阿里云+网易+华为云) + sudo $0 test # 测试镜像源速度 + sudo $0 remove aliyun # 删除阿里云镜像源 + sudo $0 remove all # 删除所有镜像源 + sudo $0 restart # 重启 Docker 服务 + +EOF +} + +# 主函数 +main() { + # 检查演示模式 + if [[ "$1" == "demo" ]]; then + log_title "Docker 镜像加速器设置脚本 - 演示模式" + echo + show_available_mirrors + echo "注意: 实际配置需要 root 权限" + echo "运行: sudo $0 [操作]" + echo + exit 0 + fi + + # 检查是否为 root 用户 + if [[ $EUID -ne 0 ]]; then + log_error "请使用 root 用户或 sudo 运行此脚本" + echo "提示: 使用 '$0 demo' 查看演示" + exit 1 + fi + + # 检查 jq 是否安装 + if ! command -v jq &> /dev/null; then + log_info "安装 jq 工具..." + apt update && apt install -y jq + fi + + # 检查 bc 是否安装(用于速度测试) + if ! command -v bc &> /dev/null; then + apt install -y bc + fi + + local action="$1" + shift + + case $action in + list) + show_available_mirrors + ;; + show) + check_docker + show_current_config + ;; + add) + check_docker + if [[ $# -eq 0 ]]; then + log_error "请指定要添加的镜像源" + show_available_mirrors + exit 1 + fi + add_mirror "$1" + restart_docker + ;; + remove) + check_docker + if [[ $# -eq 0 ]]; then + log_error "请指定要删除的镜像源" + exit 1 + fi + remove_mirror "$1" + restart_docker + ;; + recommend) + check_docker + set_recommended + restart_docker + ;; + test) + check_docker + test_mirrors + ;; + restore) + restore_config "$1" + restart_docker + ;; + restart) + check_docker + restart_docker + ;; + ""|-h|--help) + show_help + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + log_success "操作完成" +} + +# 执行主函数 +main "$@" diff --git a/scripts/security/configure_security.sh b/scripts/security/configure_security.sh new file mode 100644 index 0000000..8cb4d15 --- /dev/null +++ b/scripts/security/configure_security.sh @@ -0,0 +1,578 @@ +#!/bin/bash + +# Debian 12 安全配置脚本 +# 系统安全加固和配置 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 配置 fail2ban +configure_fail2ban() { + log_info "配置 fail2ban..." + + apt update + apt install -y fail2ban + + # 配置 fail2ban + cat > /etc/fail2ban/jail.local << 'EOF' +# EM Script Library - Fail2Ban Configuration + +[DEFAULT] +# Ban hosts for one hour: +bantime = 3600 + +# Override /etc/fail2ban/jail.d/00-firewalld.conf: +banaction = ufw + +# A host is banned if it has generated "maxretry" during the last "findtime" seconds. +findtime = 600 +maxretry = 5 + +# "ignoreip" can be a list of IP addresses, CIDR masks or DNS hosts. Fail2ban +# will not ban a host which matches an address in this list. Several addresses +# can be defined using space (and/or comma) separator. +ignoreip = 127.0.0.1/8 ::1 + +[sshd] +enabled = true +port = ssh +filter = sshd +logpath = /var/log/auth.log +maxretry = 3 +bantime = 86400 + +[sshd-ddos] +enabled = true +port = ssh +filter = sshd-ddos +logpath = /var/log/auth.log +maxretry = 3 +bantime = 86400 + +[dropbear] +enabled = false + +[nginx-http-auth] +enabled = false + +[nginx-noscript] +enabled = false + +[nginx-badbots] +enabled = false + +[nginx-noproxy] +enabled = false + +[nginx-botsearch] +enabled = false + +[nginx-req-limit] +enabled = false + +[nginx-ddos] +enabled = false + +[php-url-fopen] +enabled = false + +[suhosin] +enabled = false + +[lighttpd-auth] +enabled = false + +[roundcube-auth] +enabled = false + +[openwebmail] +enabled = false + +[horde] +enabled = false + +[groupoffice] +enabled = false + +[sogo-auth] +enabled = false + +[tine20] +enabled = false + +[drupal] +enabled = false + +[plesk-panel] +enabled = false + +[plesk-proftpd] +enabled = false + +[mod-security] +enabled = false + +[mod-evasive] +enabled = false + +[vsftpd] +enabled = false + +[proftpd] +enabled = false + +[pure-ftpd] +enabled = false + +[wuftpd] +enabled = false + +[postfix] +enabled = false + +[dovecot] +enabled = false + +[solid-pop3d] +enabled = false + +[exim] +enabled = false + +[selinux-ssh] +enabled = false + +[mythtv] +enabled = false + +[asterisk] +enabled = false + +[apache-auth] +enabled = false + +[apache-noscript] +enabled = false + +[apache-overflows] +enabled = false + +[apache-nohome] +enabled = false + +[apache-botsearch] +enabled = false + +[apache-noscript] +enabled = false + +[apache-modsecurity] +enabled = false + +[apache-shellshock] +enabled = false + +[openhab-auth] +enabled = false + +[nagios] +enabled = false + +[oracleims] +enabled = false + +[directadmin] +enabled = false + +[portscan] +enabled = false + +[ufw] +enabled = false + +[recidive] +enabled = true +logpath = /var/log/fail2ban.log +banaction = ufw +bantime = 604800 +findtime = 86400 +maxretry = 5 +EOF + + systemctl restart fail2ban + systemctl enable fail2ban + + log_success "fail2ban 配置完成" +} + +# 配置自动安全更新 +configure_auto_updates() { + log_info "配置自动安全更新..." + + apt install -y unattended-upgrades apt-listchanges + + # 配置自动更新 + cat > /etc/apt/apt.conf.d/50unattended-upgrades << 'EOF' +// EM Script Library - Unattended Upgrades Configuration +Unattended-Upgrade::Allowed-Origins { + "${distro_id}:${distro_codename}"; + "${distro_id}:${distro_codename}-security"; + "${distro_id}ESM:${distro_codename}"; + "${distro_id}:${distro_codename}-updates"; + "${distro_id}:${distro_codename}-proposed"; + "${distro_id}:${distro_codename}-backports"; +}; + +Unattended-Upgrade::Package-Blacklist { +}; + +Unattended-Upgrade::AutoFixInterruptedDpkg "true"; +Unattended-Upgrade::MinimalSteps "true"; +Unattended-Upgrade::InstallOnShutdown "false"; +Unattended-Upgrade::Mail "root"; +Unattended-Upgrade::MailOnlyOnError "true"; +Unattended-Upgrade::Remove-Unused-Kernel-Packages "true"; +Unattended-Upgrade::Remove-Unused-Dependencies "true"; +Unattended-Upgrade::Automatic-Reboot "false"; +Unattended-Upgrade::Automatic-Reboot-WithUsers "false"; +Unattended-Upgrade::SyslogEnable "true"; +Unattended-Upgrade::SyslogFacility "daemon"; +EOF + + # 启用自动更新 + cat > /etc/apt/apt.conf.d/20auto-upgrades << 'EOF' +// EM Script Library - Auto Upgrades Configuration +APT::Periodic::Update-Package-Lists "1"; +APT::Periodic::Download-Upgradeable-Packages "1"; +APT::Periodic::AutocleanInterval "7"; +APT::Periodic::Unattended-Upgrade "1"; +EOF + + systemctl restart unattended-upgrades + systemctl enable unattended-upgrades + + log_success "自动安全更新配置完成" +} + +# 强化 SSH 配置 +harden_ssh() { + log_info "强化 SSH 配置..." + + # 备份原始配置 + cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S) + + # 修改 SSH 配置 + sed -i 's/#PermitRootLogin yes/PermitRootLogin without-password/' /etc/ssh/sshd_config + sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config + sed -i 's/#PermitEmptyPasswords no/PermitEmptyPasswords no/' /etc/ssh/sshd_config + sed -i 's/#Protocol 2/Protocol 2/' /etc/ssh/sshd_config + sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config + sed -i 's/#MaxSessions 10/MaxSessions 5/' /etc/ssh/sshd_config + sed -i 's/#ClientAliveInterval 0/ClientAliveInterval 300/' /etc/ssh/sshd_config + sed -i 's/#ClientAliveCountMax 3/ClientAliveCountMax 2/' /etc/ssh/sshd_config + + # 添加额外安全配置 + cat >> /etc/ssh/sshd_config << 'EOF' + +# EM Script Library - SSH Hardening +# 禁用 TCP 转发 +AllowTcpForwarding no +X11Forwarding no + +# 禁用用户环境设置 +PermitUserEnvironment no + +# 限制登录用户(取消注释并修改为允许的用户) +# AllowUsers yourusername + +# 使用强加密算法 +Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr +MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com +KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256 + +# 日志级别 +LogLevel VERBOSE +EOF + + # 测试配置 + if sshd -t; then + systemctl restart ssh + log_success "SSH 配置强化完成" + else + log_error "SSH 配置测试失败,已恢复原始配置" + cp /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config + systemctl restart ssh + exit 1 + fi +} + +# 配置 AppArmor +configure_apparmor() { + log_info "配置 AppArmor..." + + apt install -y apparmor apparmor-utils apparmor-profiles + + # 启用 AppArmor + systemctl enable apparmor + systemctl start apparmor + + # 检查状态 + if aa-status >/dev/null 2>&1; then + log_success "AppArmor 配置完成" + aa-status | head -10 + else + log_warning "AppArmor 可能未正确启用" + fi +} + +# 配置内核安全参数 +configure_kernel_security() { + log_info "配置内核安全参数..." + + cat > /etc/sysctl.d/99-security.conf << 'EOF' +# EM Script Library - Kernel Security Configuration + +# 网络安全 +net.ipv4.conf.all.rp_filter = 1 +net.ipv4.conf.default.rp_filter = 1 +net.ipv4.conf.all.accept_redirects = 0 +net.ipv4.conf.default.accept_redirects = 0 +net.ipv4.conf.all.secure_redirects = 0 +net.ipv4.conf.default.secure_redirects = 0 +net.ipv4.conf.all.accept_source_route = 0 +net.ipv4.conf.default.accept_source_route = 0 +net.ipv4.conf.all.send_redirects = 0 +net.ipv4.conf.default.send_redirects = 0 +net.ipv4.conf.all.log_martians = 1 +net.ipv4.conf.default.log_martians = 1 + +# IPv6 安全 +net.ipv6.conf.all.accept_redirects = 0 +net.ipv6.conf.default.accept_redirects = 0 +net.ipv6.conf.all.accept_source_route = 0 +net.ipv6.conf.default.accept_source_route = 0 + +# TCP 安全 +net.ipv4.tcp_syncookies = 1 +net.ipv4.tcp_synack_retries = 5 +net.ipv4.tcp_syn_retries = 5 +net.ipv4.tcp_max_syn_backlog = 2048 + +# ICMP 安全 +net.ipv4.icmp_echo_ignore_broadcasts = 1 +net.ipv4.icmp_ignore_bogus_error_responses = 1 + +# 文件系统安全 +fs.suid_dumpable = 0 +kernel.randomize_va_space = 2 + +# 进程安全 +kernel.panic = 10 +kernel.panic_on_oops = 1 +EOF + + sysctl -p /etc/sysctl.d/99-security.conf + + log_success "内核安全参数配置完成" +} + +# 安装和配置 ClamAV 杀毒软件 +configure_clamav() { + log_info "安装和配置 ClamAV..." + + apt install -y clamav clamav-daemon + + # 更新病毒库 + systemctl stop clamav-freshclam + freshclam + systemctl start clamav-freshclam + systemctl enable clamav-freshclam + + # 配置定时扫描 + cat > /etc/cron.daily/clamav-scan << 'EOF' +#!/bin/bash +# EM Script Library - ClamAV Daily Scan +SCAN_DIR="/home /tmp /var/tmp /var/www" +LOG_FILE="/var/log/clamav/daily-scan.log" + +mkdir -p /var/log/clamav +clamscan -r --log="$LOG_FILE" --quiet $SCAN_DIR + +# 发送报告(如果发现病毒) +if grep -q "FOUND" "$LOG_FILE"; then + mail -s "ClamAV Virus Alert" root < "$LOG_FILE" +fi +EOF + + chmod +x /etc/cron.daily/clamav-scan + + log_success "ClamAV 配置完成" +} + +# 配置 sudo +configure_sudo() { + log_info "配置 sudo 安全策略..." + + # 创建 sudoers 配置 + cat > /etc/sudoers.d/em-security << 'EOF' +# EM Script Library - Sudo Security Configuration + +# 要求密码验证 +Defaults env_reset +Defaults mail_badpass +Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +# 记录 sudo 命令 +Defaults log_host, log_year, logfile="/var/log/sudo.log" + +# 限制环境变量 +Defaults env_check+="HOME EDITOR" +Defaults env_delete+="HOME EDITOR" + +# 超时设置 +Defaults timestamp_timeout=15 + +# 允许特定用户组使用 sudo +#%sudo ALL=(ALL:ALL) ALL +EOF + + # 验证 sudoers 文件 + visudo -c -f /etc/sudoers.d/em-security + + log_success "sudo 安全配置完成" +} + +# 显示安全状态 +show_security_status() { + log_info "系统安全状态检查:" + + echo "=== SSH 配置 ===" + sshd -T | grep -E "(permitrootlogin|passwordauthentication|maxauthtries)" | head -5 + + echo "" + echo "=== 防火墙状态 ===" + ufw status | head -10 + + echo "" + echo "=== Fail2Ban 状态 ===" + fail2ban-client status 2>/dev/null || echo "Fail2Ban 未运行" + + echo "" + echo "=== 自动更新状态 ===" + systemctl is-active unattended-upgrades 2>/dev/null || echo "自动更新未启用" + + echo "" + echo "=== 内核安全参数 ===" + sysctl -a | grep -E "(rp_filter|accept_redirects|tcp_syncookies)" | head -5 + + echo "" + echo "=== 开放端口 ===" + ss -tuln | grep LISTEN | head -10 +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 安全配置工具 + +用法: $0 [选项] [操作] + +操作: + fail2ban 配置 fail2ban 入侵检测 + auto-updates 配置自动安全更新 + ssh-harden 强化 SSH 配置 + apparmor 配置 AppArmor + kernel-sec 配置内核安全参数 + clamav 安装和配置 ClamAV 杀毒软件 + sudo-config 配置 sudo 安全策略 + status 显示安全状态 + all 执行所有安全配置 + +选项: + -h, --help 显示此帮助信息 + +示例: + $0 fail2ban # 配置 fail2ban + $0 ssh-harden # 强化 SSH + $0 status # 查看安全状态 + $0 all # 执行所有配置 + +EOF +} + +# 主函数 +main() { + local action="$1" + + case $action in + fail2ban) + configure_fail2ban + ;; + auto-updates) + configure_auto_updates + ;; + ssh-harden) + harden_ssh + ;; + apparmor) + configure_apparmor + ;; + kernel-sec) + configure_kernel_security + ;; + clamav) + configure_clamav + ;; + sudo-config) + configure_sudo + ;; + status) + show_security_status + ;; + all) + configure_fail2ban + configure_auto_updates + harden_ssh + configure_apparmor + configure_kernel_security + configure_clamav + configure_sudo + ;; + ""|-h|--help) + show_help + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + log_success "安全配置完成!" +} + +# 执行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/sources/configure_sources.sh b/scripts/sources/configure_sources.sh new file mode 100644 index 0000000..6f98693 --- /dev/null +++ b/scripts/sources/configure_sources.sh @@ -0,0 +1,353 @@ +#!/bin/bash + +# Debian 12 国内源配置脚本 +# 支持多种国内镜像源 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 备份当前源配置 +backup_sources() { + local backup_dir="/root/sources_backup_$(date +%Y%m%d_%H%M%S)" + mkdir -p "$backup_dir" + + log_info "备份当前源配置到: $backup_dir" + + if [[ -f /etc/apt/sources.list ]]; then + cp /etc/apt/sources.list "$backup_dir/" + log_success "已备份 /etc/apt/sources.list" + fi + + if [[ -d /etc/apt/sources.list.d ]]; then + cp -r /etc/apt/sources.list.d "$backup_dir/" + log_success "已备份 /etc/apt/sources.list.d/" + fi + + echo "$backup_dir" > /tmp/sources_backup_path + log_success "备份完成,路径已保存到 /tmp/sources_backup_path" +} + +# 恢复源配置 +restore_sources() { + local backup_path="$1" + + if [[ -z "$backup_path" ]]; then + if [[ -f /tmp/sources_backup_path ]]; then + backup_path=$(cat /tmp/sources_backup_path) + else + log_error "未找到备份路径" + return 1 + fi + fi + + if [[ ! -d "$backup_path" ]]; then + log_error "备份目录不存在: $backup_path" + return 1 + fi + + log_info "从 $backup_path 恢复源配置" + + if [[ -f "$backup_path/sources.list" ]]; then + cp "$backup_path/sources.list" /etc/apt/sources.list + log_success "已恢复 /etc/apt/sources.list" + fi + + if [[ -d "$backup_path/sources.list.d" ]]; then + cp -r "$backup_path/sources.list.d" /etc/apt/ + log_success "已恢复 /etc/apt/sources.list.d/" + fi + + log_success "源配置恢复完成" +} + +# 配置阿里云源 +configure_aliyun() { + log_info "配置阿里云镜像源..." + + cat > /etc/apt/sources.list << 'EOF' +deb https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib +deb-src https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib +deb https://mirrors.aliyun.com/debian-security/ bookworm-security main +deb-src https://mirrors.aliyun.com/debian-security/ bookworm-security main +deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb-src https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib +deb-src https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib +EOF + + log_success "阿里云源配置完成" +} + +# 配置清华大学源 +configure_tsinghua() { + log_info "配置清华大学镜像源..." + + cat > /etc/apt/sources.list << 'EOF' +deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware +deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware +deb https://mirrors.tuna.tsinghua.edu.cn/debian-security/ bookworm-security main contrib non-free non-free-firmware +deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security/ bookworm-security main contrib non-free non-free-firmware +deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware +deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware +deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware +deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware +EOF + + log_success "清华大学源配置完成" +} + +# 配置网易源 +configure_163() { + log_info "配置网易镜像源..." + + cat > /etc/apt/sources.list << 'EOF' +deb https://mirrors.163.com/debian/ bookworm main non-free non-free-firmware contrib +deb-src https://mirrors.163.com/debian/ bookworm main non-free non-free-firmware contrib +deb https://mirrors.163.com/debian-security/ bookworm-security main +deb-src https://mirrors.163.com/debian-security/ bookworm-security main +deb https://mirrors.163.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb-src https://mirrors.163.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb https://mirrors.163.com/debian/ bookworm-backports main non-free non-free-firmware contrib +deb-src https://mirrors.163.com/debian/ bookworm-backports main non-free non-free-firmware contrib +EOF + + log_success "网易源配置完成" +} + +# 配置中科大源 +configure_ustc() { + log_info "配置中科大镜像源..." + + cat > /etc/apt/sources.list << 'EOF' +deb https://mirrors.ustc.edu.cn/debian/ bookworm main contrib non-free non-free-firmware +deb-src https://mirrors.ustc.edu.cn/debian/ bookworm main contrib non-free non-free-firmware +deb https://mirrors.ustc.edu.cn/debian-security/ bookworm-security main contrib non-free non-free-firmware +deb-src https://mirrors.ustc.edu.cn/debian-security/ bookworm-security main contrib non-free non-free-firmware +deb https://mirrors.ustc.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware +deb-src https://mirrors.ustc.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware +deb https://mirrors.ustc.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware +deb-src https://mirrors.ustc.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware +EOF + + log_success "中科大源配置完成" +} + +# 配置华为云源 +configure_huawei() { + log_info "配置华为云镜像源..." + + cat > /etc/apt/sources.list << 'EOF' +deb https://mirrors.huaweicloud.com/debian/ bookworm main non-free non-free-firmware contrib +deb-src https://mirrors.huaweicloud.com/debian/ bookworm main non-free non-free-firmware contrib +deb https://mirrors.huaweicloud.com/debian-security/ bookworm-security main +deb-src https://mirrors.huaweicloud.com/debian-security/ bookworm-security main +deb https://mirrors.huaweicloud.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb-src https://mirrors.huaweicloud.com/debian/ bookworm-updates main non-free non-free-firmware contrib +deb https://mirrors.huaweicloud.com/debian/ bookworm-backports main non-free non-free-firmware contrib +deb-src https://mirrors.huaweicloud.com/debian/ bookworm-backports main non-free non-free-firmware contrib +EOF + + log_success "华为云源配置完成" +} + +# 测试源连接 +test_sources() { + log_info "测试源连接速度..." + + local sources=("https://mirrors.aliyun.com" + "https://mirrors.tuna.tsinghua.edu.cn" + "https://mirrors.163.com" + "https://mirrors.ustc.edu.cn" + "https://mirrors.huaweicloud.com") + + local fastest_source="" + local fastest_time=999 + + for source in "${sources[@]}"; do + log_info "测试 $source ..." + local start_time=$(date +%s%N) + if curl -s --connect-timeout 5 --max-time 10 "${source}/debian/dists/bookworm/Release" > /dev/null 2>&1; then + local end_time=$(date +%s%N) + local time_diff=$(( (end_time - start_time) / 1000000 )) + log_success "$source 响应时间: ${time_diff}ms" + + if (( time_diff < fastest_time )); then + fastest_time=$time_diff + fastest_source=$source + fi + else + log_warning "$source 连接失败" + fi + done + + if [[ -n "$fastest_source" ]]; then + log_success "最快源: $fastest_source (${fastest_time}ms)" + echo "$fastest_source" + else + log_error "所有源都无法连接" + return 1 + fi +} + +# 更新包索引 +update_packages() { + log_info "更新包索引..." + apt update + log_success "包索引更新完成" +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 国内源配置工具 + +用法: $0 [选项] [源名称] + +源名称: + aliyun 阿里云镜像源 + tsinghua 清华大学镜像源 + 163 网易镜像源 + ustc 中科大镜像源 + huawei 华为云镜像源 + test 测试所有源速度并选择最快 + backup 备份当前源配置 + restore 恢复源配置 + +选项: + -h, --help 显示此帮助信息 + -n, --no-update 配置完成后不更新包索引 + +示例: + $0 aliyun # 配置阿里云源 + $0 test # 测试并选择最快源 + $0 backup # 备份当前配置 + $0 restore /path/to/backup # 从指定路径恢复 + +EOF +} + +# 主函数 +main() { + local no_update=false + local action="" + + # 参数解析 + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + show_help + exit 0 + ;; + -n|--no-update) + no_update=true + shift + ;; + -*) + log_error "未知选项: $1" + show_help + exit 1 + ;; + *) + action="$1" + shift + break + ;; + esac + done + + case $action in + aliyun) + backup_sources + configure_aliyun + ;; + tsinghua) + backup_sources + configure_tsinghua + ;; + 163) + backup_sources + configure_163 + ;; + ustc) + backup_sources + configure_ustc + ;; + huawei) + backup_sources + configure_huawei + ;; + test) + local fastest=$(test_sources) + if [[ $? -eq 0 ]]; then + case $fastest in + *aliyun*) + configure_aliyun + ;; + *tuna.tsinghua*) + configure_tsinghua + ;; + *163*) + configure_163 + ;; + *ustc*) + configure_ustc + ;; + *huaweicloud*) + configure_huawei + ;; + esac + fi + ;; + backup) + backup_sources + exit 0 + ;; + restore) + restore_sources "$1" + exit 0 + ;; + "") + log_error "未指定操作" + show_help + exit 1 + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + # 更新包索引 + if [[ "$no_update" != "true" ]]; then + update_packages + fi + + log_success "源配置完成!" +} + +# 执行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/system/configure_system.sh b/scripts/system/configure_system.sh new file mode 100644 index 0000000..73f9b7f --- /dev/null +++ b/scripts/system/configure_system.sh @@ -0,0 +1,396 @@ +#!/bin/bash + +# Debian 12 系统配置脚本 +# 系统基础配置和优化 + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 配置时区 +configure_timezone() { + log_info "配置时区为 Asia/Shanghai..." + + # 设置时区 + timedatectl set-timezone Asia/Shanghai + + # 安装并配置 chrony + apt update + apt install -y chrony + + # 配置 chrony 使用国内 NTP 服务器 + cat > /etc/chrony/chrony.conf << 'EOF' +# NTP servers from Alibaba Cloud +server ntp.aliyun.com iburst +server ntp1.aliyun.com iburst +server ntp2.aliyun.com iburst +server ntp3.aliyun.com iburst + +# NTP servers from Tencent Cloud +server time1.cloud.tencent.com iburst +server time2.cloud.tencent.com iburst + +# NTP servers from Baidu +server ntp1.baidu.com iburst +server ntp2.baidu.com iburst + +# Allow NTP client access from local network +allow 192.168.0.0/16 +allow 10.0.0.0/8 +allow 172.16.0.0/12 + +# Serve time even if not synchronized to a time source +local stratum 10 + +# Specify directory for log files +logdir /var/log/chrony + +# Select which information is logged +log measurements statistics tracking +EOF + + systemctl restart chrony + systemctl enable chrony + + log_success "时区配置完成" +} + +# 配置语言环境 +configure_locale() { + log_info "配置语言环境..." + + # 生成中文 locale + sed -i 's/# zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/' /etc/locale.gen + sed -i 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen + + locale-gen + + # 设置默认语言环境 + cat > /etc/default/locale << 'EOF' +LANG=en_US.UTF-8 +LANGUAGE=en_US:en +LC_CTYPE="en_US.UTF-8" +LC_NUMERIC=zh_CN.UTF-8 +LC_TIME=zh_CN.UTF-8 +LC_COLLATE="en_US.UTF-8" +LC_MONETARY=zh_CN.UTF-8 +LC_MESSAGES="en_US.UTF-8" +LC_PAPER=zh_CN.UTF-8 +LC_NAME=zh_CN.UTF-8 +LC_ADDRESS=zh_CN.UTF-8 +LC_TELEPHONE=zh_CN.UTF-8 +LC_MEASUREMENT=zh_CN.UTF-8 +LC_IDENTIFICATION=zh_CN.UTF-8 +EOF + + # 重新加载 locale 设置 + update-locale LANG=en_US.UTF-8 + + log_success "语言环境配置完成" +} + +# 配置系统限制 +configure_limits() { + log_info "配置系统限制..." + + cat >> /etc/security/limits.conf << 'EOF' + +# EM Script Library - System Limits Configuration +* soft nofile 65536 +* hard nofile 65536 +* soft nproc 65536 +* hard nproc 65536 +root soft nofile 65536 +root hard nofile 65536 +root soft nproc 65536 +root hard nproc 65536 + +# Increase core file size +* soft core unlimited +* hard core unlimited +root soft core unlimited +root hard core unlimited +EOF + + # 配置 sysctl 参数 + cat > /etc/sysctl.d/99-custom.conf << 'EOF' +# EM Script Library - System Control Configuration + +# Increase system file descriptor limits +fs.file-max = 655360 + +# Network optimizations +net.core.somaxconn = 65535 +net.core.netdev_max_backlog = 250000 +net.ipv4.tcp_max_syn_backlog = 250000 +net.ipv4.ip_local_port_range = 1024 65535 + +# TCP optimizations +net.ipv4.tcp_slow_start_after_idle = 0 +net.ipv4.tcp_tw_reuse = 1 +net.ipv4.tcp_tw_recycle = 1 +net.ipv4.tcp_fin_timeout = 15 +net.ipv4.tcp_keepalive_time = 600 +net.ipv4.tcp_keepalive_intvl = 60 +net.ipv4.tcp_keepalive_probes = 3 + +# Memory optimizations +vm.swappiness = 10 +vm.dirty_ratio = 20 +vm.dirty_background_ratio = 10 +vm.vfs_cache_pressure = 50 + +# Security enhancements +net.ipv4.conf.all.rp_filter = 1 +net.ipv4.conf.default.rp_filter = 1 +net.ipv4.conf.all.accept_redirects = 0 +net.ipv4.conf.default.accept_redirects = 0 +net.ipv4.conf.all.secure_redirects = 0 +net.ipv4.conf.default.secure_redirects = 0 +EOF + + # 应用 sysctl 配置 + sysctl -p /etc/sysctl.d/99-custom.conf + + log_success "系统限制配置完成" +} + +# 配置 SSH +configure_ssh() { + log_info "配置 SSH 服务..." + + # 备份原始配置 + cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup + + # 配置 SSH + cat > /etc/ssh/sshd_config << 'EOF' +# EM Script Library - SSH Configuration + +# Basic configuration +Port 22 +AddressFamily any +ListenAddress 0.0.0.0 +ListenAddress :: + +# Host keys +HostKey /etc/ssh/ssh_host_rsa_key +HostKey /etc/ssh/ssh_host_ecdsa_key +HostKey /etc/ssh/ssh_host_ed25519_key + +# Logging +LogLevel INFO +SyslogFacility AUTH + +# Authentication +PermitRootLogin yes +StrictModes yes +MaxAuthTries 6 +MaxSessions 10 + +# Password authentication +PasswordAuthentication yes + +# Public key authentication +PubkeyAuthentication yes +AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2 + +# GSSAPI options +GSSAPIAuthentication no +GSSAPICleanupCredentials no + +# Kerberos options +KerberosAuthentication no +KerberosOrLocalPasswd yes +KerberosTicketCleanup yes +KerberosGetAFSToken no + +# Security options +UsePAM yes +AllowAgentForwarding yes +AllowTcpForwarding yes +GatewayPorts no +X11Forwarding yes +X11DisplayOffset 10 +X11UseLocalhost yes +PermitTTY yes +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +PermitUserEnvironment no +Compression delayed +ClientAliveInterval 60 +ClientAliveCountMax 3 +UseDNS no +PidFile /var/run/sshd.pid +MaxStartups 10:30:100 +PermitTunnel no +ChrootDirectory none +VersionAddendum none + +# Allow client to pass locale environment variables +AcceptEnv LANG LC_* + +# Override default of no subsystems +Subsystem sftp /usr/lib/openssh/sftp-server +EOF + + # 重启 SSH 服务 + systemctl restart ssh + systemctl enable ssh + + log_success "SSH 配置完成" +} + +# 配置防火墙 +configure_firewall() { + log_info "配置防火墙..." + + # 安装并启用 UFW + apt update + apt install -y ufw + + # 配置 UFW + ufw --force reset + ufw default deny incoming + ufw default allow outgoing + + # 允许 SSH + ufw allow ssh + ufw allow 22/tcp + + # 允许 HTTP/HTTPS + ufw allow 80/tcp + ufw allow 443/tcp + + # 启用防火墙 + echo "y" | ufw enable + + log_success "防火墙配置完成" +} + +# 配置日志轮转 +configure_logrotate() { + log_info "配置日志轮转..." + + cat > /etc/logrotate.d/custom << 'EOF' +/var/log/*.log { + daily + missingok + rotate 52 + compress + delaycompress + notifempty + create 644 root root + postrotate + systemctl reload rsyslog.service || true + endscript +} + +/var/log/apt/*.log { + daily + missingok + rotate 12 + compress + delaycompress + notifempty + create 644 root root +} +EOF + + log_success "日志轮转配置完成" +} + +# 显示帮助信息 +show_help() { + cat << EOF +Debian 12 系统配置工具 + +用法: $0 [选项] [操作] + +操作: + timezone 配置时区和 NTP + locale 配置语言环境 + limits 配置系统限制 + ssh 配置 SSH 服务 + firewall 配置防火墙 + logrotate 配置日志轮转 + all 执行所有配置 + +选项: + -h, --help 显示此帮助信息 + +示例: + $0 timezone # 配置时区 + $0 all # 执行所有配置 + +EOF +} + +# 主函数 +main() { + local action="$1" + + case $action in + timezone) + configure_timezone + ;; + locale) + configure_locale + ;; + limits) + configure_limits + ;; + ssh) + configure_ssh + ;; + firewall) + configure_firewall + ;; + logrotate) + configure_logrotate + ;; + all) + configure_timezone + configure_locale + configure_limits + configure_ssh + configure_firewall + configure_logrotate + ;; + ""|-h|--help) + show_help + ;; + *) + log_error "未知操作: $action" + show_help + exit 1 + ;; + esac + + log_success "系统配置完成!" +} + +# 执行主函数 +main "$@" \ No newline at end of file