# 开启BBR加速 enable_kernel_bbr(){ if [ "$(id -u)" -ne 0 ]; then echo "请使用 root 权限运行该操作" return 1 fi # 检测容器环境 local virt_type="" if command -v systemd-detect-virt >/dev/null 2>&1; then virt_type=$(systemd-detect-virt 2>/dev/null) fi case "$virt_type" in lxc|openvz|docker|podman|container-other) echo "检测到当前运行于容器环境: $virt_type" echo "请在宿主机开启 BBR" return 1 ;; esac if [ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" = "bbr" ]; then echo "BBR加速 已经开启,无需重复操作" return 0 fi # 尝试加载 bbr 模块(新内核可能已内建) if command -v modprobe >/dev/null 2>&1; then modprobe tcp_bbr 2>/dev/null || true fi # 检查内核是否支持 BBR if ! sysctl net.ipv4.tcp_available_congestion_control 2>/dev/null | grep -qw bbr; then echo "当前系统内核不支持 BBR" return 1 fi set_sysctl_conf(){ local key="$1" local value="$2" local file="/etc/sysctl.conf" touch "$file" # 转义 key,避免 . 被 grep/sed 当作正则 local escaped_key escaped_key=$(printf '%s\n' "$key" | sed 's/[.[\*^$()+?{|]/\\&/g') if grep -qE "^[[:space:]]*#?[[:space:]]*$escaped_key[[:space:]]*=" "$file"; then sed -i "s|^[[:space:]]*#\?[[:space:]]*$escaped_key[[:space:]]*=.*|$key = $value|" "$file" else echo "$key = $value" >> "$file" fi } # 写入配置 set_sysctl_conf "net.core.default_qdisc" "fq" set_sysctl_conf "net.ipv4.tcp_congestion_control" "bbr" # 立即生效 sysctl -w net.core.default_qdisc=fq >/dev/null 2>&1 sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null 2>&1 # 验证是否成功 if [ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" = "bbr" ]; then echo "BBR加速 已开启" else echo "BBR开启失败" return 1 fi }