Skip to content

Instantly share code, notes, and snippets.

@NNdroid
Last active November 15, 2026 14:27
Show Gist options
  • Select an option

  • Save NNdroid/b1fbc5fa01da57a1372c6d2968776b68 to your computer and use it in GitHub Desktop.

Select an option

Save NNdroid/b1fbc5fa01da57a1372c6d2968776b68 to your computer and use it in GitHub Desktop.
#!/bin/bash
# tcp-brutal-manager 智能管理脚本
set -u
BIN="/usr/local/sbin/tcp-brutal-manager"
URL="https://gist.githubusercontent.com/NNdroid/b1fbc5fa01da57a1372c6d2968776b68/raw/tcp-brutal-manager.sh"
info() { echo "[信息] $*"; }
warn() { echo "[警告] $*" >&2; }
err() { echo "[错误] $*" >&2; }
# 必须以 root 运行
if [[ $EUID -ne 0 ]]; then
err "请使用 root 权限运行此脚本(例如 sudo bash $0)"
exit 1
fi
# 下载管理脚本
download_manager() {
local tmp
tmp="$(mktemp)" || { err "无法创建临时文件"; return 1; }
info "未找到 $BIN,开始从 Gist 下载..."
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$URL" -o "$tmp"
elif command -v wget >/dev/null 2>&1; then
wget -qO "$tmp" "$URL"
else
err "系统中缺少 curl 或 wget,无法下载"
rm -f "$tmp"
return 1
fi
if [[ $? -ne 0 ]]; then
err "下载失败,请检查网络或链接"
rm -f "$tmp"
return 1
fi
# 简单校验:文件非空且以 shebang 开头
if [[ ! -s "$tmp" ]] || ! head -n 1 "$tmp" | grep -q '^#!'; then
err "下载的文件内容异常,已放弃安装"
rm -f "$tmp"
return 1
fi
mkdir -p "$(dirname "$BIN")"
mv -f "$tmp" "$BIN" || { err "无法写入 $BIN"; rm -f "$tmp"; return 1; }
info "下载完成:$BIN"
return 0
}
# 确保管理脚本存在且可执行
ensure_manager() {
if [[ ! -f "$BIN" ]]; then
download_manager || exit 1
fi
if [[ ! -x "$BIN" ]]; then
chmod +x "$BIN" || { err "无法赋予执行权限:$BIN"; exit 1; }
info "已赋予执行权限:$BIN"
fi
}
# 校验是否为大于 1 的整数
is_valid_rate() {
[[ "$1" =~ ^[0-9]+$ ]] && (( 10#$1 > 1 ))
}
# 循环读取,直到输入合法
read_rate() {
local prompt="$1" val
while true; do
read -rp "$prompt" val
if is_valid_rate "$val"; then
echo "$val"
return 0
fi
warn "输入无效,请输入大于 1 的整数"
done
}
do_install() {
local ipv4_rate ipv6_rate
ipv4_rate="$(read_rate 'IPv4 速率(整数,>1): ')"
ipv6_rate="$(read_rate 'IPv6 速率(整数,>1): ')"
info "开始安装:IPv4=$ipv4_rate,IPv6=$ipv6_rate"
"$BIN" install --ipv4-rate "$ipv4_rate" --ipv6-rate "$ipv6_rate" --yes
}
do_uninstall() {
local confirm
read -rp "确认卸载 tcp-brutal?[y/N]: " confirm
if [[ "$confirm" =~ ^[Yy]$ ]]; then
info "开始卸载..."
"$BIN" uninstall --yes
else
info "已取消卸载"
fi
}
show_menu() {
echo "========================================"
echo " tcp-brutal-manager 管理菜单"
echo "========================================"
echo " 1) 安装"
echo " 2) 卸载"
echo " 0) 退出"
echo "========================================"
read -rp "请选择: " choice
case "$choice" in
1) do_install ;;
2) do_uninstall ;;
0) exit 0 ;;
*) warn "无效选项" ;;
esac
}
main() {
ensure_manager
case "${1:-}" in
install) do_install ;;
uninstall) do_uninstall ;;
"") show_menu ;;
*)
err "未知参数:$1"
echo "用法:$0 [install|uninstall]"
exit 1
;;
esac
}
main "$@"
#!/usr/bin/env bash
set -Eeuo pipefail
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
MANAGER_BIN="/usr/local/sbin/tcp-brutal-manager"
CONFIG_FILE="/etc/default/tcp-brutal"
MODULE_FILE="/etc/modules-load.d/brutal.conf"
SERVICE_FILE="/etc/systemd/system/tcp-brutal-rules.service"
SERVICE_NAME="tcp-brutal-rules.service"
STATE_DIR="/var/lib/tcp-brutal-manager"
FILE_BACKUP_DIR="$STATE_DIR/file-backups"
log() { printf '[TCP-BRUTAL] %s\n' "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
require_root() {
[[ ${EUID} -eq 0 ]] || die "Run this command as root."
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}
valid_rate() {
[[ "$1" =~ ^[1-9][0-9]*$ ]]
}
# Classify each route independently. A dynamic RA route must not cause
# unrelated static default routes in the same address family to be skipped.
is_dynamic_route() {
local line="$1"
[[ "$line" =~ [[:space:]]proto[[:space:]](ra|dhcp)([[:space:]]|$) ]] && return 0
[[ "$line" =~ [[:space:]]expires([[:space:]]|$) ]] && return 0
return 1
}
STATIC_ROUTES=()
filter_static_routes() {
local line
STATIC_ROUTES=()
for line in "$@"; do
[[ -n "$line" ]] || continue
if is_dynamic_route "$line"; then
log "Preserving dynamically managed default route: $line"
else
STATIC_ROUTES+=("$line")
fi
done
}
backup_file_once() {
local target="$1" key="$2"
local marker="$FILE_BACKUP_DIR/$key.done"
local backup="$FILE_BACKUP_DIR/$key.original"
[[ -e "$marker" ]] && return 0
[[ ! -d "$target" ]] || die "Expected a file, found directory: $target"
mkdir -p "$FILE_BACKUP_DIR"
if [[ -e "$target" || -L "$target" ]]; then
cp -a -- "$target" "$backup"
: > "$FILE_BACKUP_DIR/$key.existed"
log "Backed up existing file: $target"
else
log "Will create file: $target"
fi
: > "$marker"
}
restore_file() {
local target="$1" key="$2"
local marker="$FILE_BACKUP_DIR/$key.done"
local backup="$FILE_BACKUP_DIR/$key.original"
[[ -e "$marker" ]] || return 0
rm -f -- "$target"
if [[ -e "$FILE_BACKUP_DIR/$key.existed" ]]; then
mkdir -p "$(dirname "$target")"
cp -a -- "$backup" "$target"
log "Restored original file: $target"
else
log "Removed installed file: $target"
fi
}
capture_service_state() {
mkdir -p "$STATE_DIR"
[[ -e "$STATE_DIR/service-state-captured" ]] && return 0
if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
: > "$STATE_DIR/service-was-enabled"
fi
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
: > "$STATE_DIR/service-was-active"
fi
: > "$STATE_DIR/service-state-captured"
}
snapshot_route() {
local family="$1" file="$2"
shift 2
if [[ ! -e "$file" ]]; then
printf '%s\n' "$@" > "$file"
log "Saved original IPv${family} default route(s): $file"
fi
}
snapshot_rule() {
local prefix="$1" file="$2"
[[ -e "$file" ]] && return 0
awk -v dst="dst=$prefix" '$1 == dst { print }' /proc/net/tcp_brutal/rules > "$file"
log "Saved previous rule state for $prefix"
}
read_rate() {
local label="$1" provided="$2" auto_yes="$3" outvar="$4"
local rate="$provided"
if [[ -z "$rate" ]]; then
if [[ "$auto_yes" == "1" || ! -t 0 ]]; then
rate="500"
else
read -r -p "$label Brutal rate in Mbps [500]: " rate || rate=""
rate="${rate:-500}"
fi
fi
valid_rate "$rate" || die "Invalid $label rate '$rate'. Use a positive integer in Mbps."
printf -v "$outvar" '%s' "$rate"
}
route_to_brutal() {
local family="$1" file="$2"
local line token i count=0 original_metric brutal_metric
local -a fields=() route_args=()
[[ -s "$file" ]] || die "Missing saved IPv${family} route: $file"
while IFS= read -r line; do
[[ -n "$line" ]] || continue
read -r -a fields <<< "$line"
[[ "${fields[0]:-}" == "default" ]] || continue
route_args=()
original_metric=1024
i=1
while (( i < ${#fields[@]} )); do
token="${fields[$i]}"
case "$token" in
proto|table)
i=$((i + 2))
;;
metric)
original_metric="${fields[$((i + 1))]:-1024}"
i=$((i + 2))
;;
expires)
# Dynamic routes are filtered before reaching this function.
i=$((i + 2))
;;
congctl)
i=$((i + 1))
if [[ "${fields[$i]:-}" == "lock" ]]; then
i=$((i + 1))
fi
i=$((i + 1))
;;
*)
route_args+=("$token")
i=$((i + 1))
;;
esac
done
[[ "$original_metric" =~ ^[0-9]+$ ]] || original_metric=1024
if (( original_metric > 0 )); then
brutal_metric=$((original_metric - 1))
else
brutal_metric=0
fi
log "Installing IPv${family} Brutal default route (metric ${brutal_metric}): $line"
ip "-$family" route replace default "${route_args[@]}" \
metric "$brutal_metric" congctl lock brutal proto 233 table main
count=$((count + 1))
done < "$file"
(( count > 0 )) || die "No static default route found in $file"
}
restore_routes() {
local family="$1" file="$2"
local line token i
local -a fields=() route_args=()
[[ -s "$file" ]] || return 0
# Delete only this manager's routes; RA/DHCP defaults are not touched.
ip "-$family" route del default proto 233 table main >/dev/null 2>&1 || true
while IFS= read -r line; do
[[ -n "$line" ]] || continue
read -r -a fields <<< "$line"
[[ "${fields[0]:-}" == "default" ]] || continue
route_args=()
i=0
while (( i < ${#fields[@]} )); do
token="${fields[$i]}"
if [[ "$token" == "table" ]]; then
i=$((i + 2))
else
route_args+=("$token")
i=$((i + 1))
fi
done
log "Restoring original IPv${family} route: $line"
ip "-$family" route replace "${route_args[@]}" table main
done < "$file"
}
apply_family() {
local family="$1" prefix="$2" rate="$3" route_file="$4"
local -a all_routes=() current_routes=()
local attempt has_brutal=0
local line
for ((attempt = 1; attempt <= 30; attempt++)); do
mapfile -t all_routes < <(ip "-$family" route show table main default)
filter_static_routes "${all_routes[@]}"
current_routes=("${STATIC_ROUTES[@]}")
((${#current_routes[@]} > 0)) && break
sleep 1
done
((${#current_routes[@]} > 0)) ||
die "No manageable static IPv${family} default route is available. Dynamic RA/DHCP routes were left untouched."
for line in "${current_routes[@]}"; do
[[ "$line" =~ [[:space:]]proto[[:space:]]233([[:space:]]|$) ]] && has_brutal=1
done
# Snapshot only static routes. Dynamic RA/DHCP routes remain untouched.
if (( has_brutal == 0 )); then
printf '%s\n' "${current_routes[@]}" > "$route_file"
elif [[ ! -s "$route_file" ]]; then
die "Current IPv${family} route is already proto 233 but no restore point exists."
fi
log "Adding IPv${family} Brutal rule: ${rate} Mbps"
brutalctl add "$prefix" "$rate" noroute
route_to_brutal "$family" "$route_file"
}
cmd_apply() {
require_root
[[ -r "$CONFIG_FILE" ]] || die "Missing config: $CONFIG_FILE"
[[ -d "$STATE_DIR" ]] || die "Missing state directory: $STATE_DIR. Run install first."
require_cmd ip
require_cmd modprobe
require_cmd brutalctl
# The config is generated by this script and contains only numeric values.
# shellcheck disable=SC1090
source "$CONFIG_FILE"
modprobe brutal
[[ -r /proc/net/tcp_brutal/rules ]] || die "TCP Brutal kernel interface is unavailable."
[[ "${BRUTAL_IPV4_ENABLED:-0}" == "1" ]] &&
apply_family 4 "0.0.0.0/0" "${BRUTAL_IPV4_RATE:-500}" "$STATE_DIR/ipv4.routes"
[[ "${BRUTAL_IPV6_ENABLED:-0}" == "1" ]] &&
apply_family 6 "::/0" "${BRUTAL_IPV6_RATE:-500}" "$STATE_DIR/ipv6.routes"
log "Apply completed."
brutalctl list
}
cmd_install() {
require_root
require_cmd ip
require_cmd systemctl
require_cmd modprobe
require_cmd install
require_cmd brutalctl
[[ -x "$MANAGER_BIN" ]] || die "Save this script as $MANAGER_BIN and chmod 755 it first."
local arg_v4="" arg_v6="" auto_yes=0
while (($#)); do
case "$1" in
--ipv4-rate)
(($# >= 2)) || die "--ipv4-rate requires a value"
arg_v4="$2"; shift 2 ;;
--ipv6-rate)
(($# >= 2)) || die "--ipv6-rate requires a value"
arg_v6="$2"; shift 2 ;;
--yes|-y)
auto_yes=1; shift ;;
-h|--help)
echo "Usage: tcp-brutal-manager install [--ipv4-rate Mbps] [--ipv6-rate Mbps] [--yes]"
return 0 ;;
*) die "Unknown install option: $1" ;;
esac
done
modprobe brutal || die "Failed to load kernel module brutal."
[[ -r /proc/net/tcp_brutal/rules ]] || die "TCP Brutal kernel interface is unavailable."
local -a v4_all_routes=() v6_all_routes=()
local -a v4_routes=() v6_routes=()
mapfile -t v4_all_routes < <(ip -4 route show table main default)
mapfile -t v6_all_routes < <(ip -6 route show table main default)
local v4_enabled=0 v6_enabled=0 rate4=500 rate6=500
filter_static_routes "${v4_all_routes[@]}"
v4_routes=("${STATIC_ROUTES[@]}")
if ((${#v4_routes[@]} > 0)); then
v4_enabled=1
log "Static IPv4 default route detected."
elif ((${#v4_all_routes[@]} > 0)); then
log "IPv4 defaults are dynamically managed; preserving them and skipping IPv4."
else
log "No IPv4 default route detected; IPv4 will be skipped."
fi
filter_static_routes "${v6_all_routes[@]}"
v6_routes=("${STATIC_ROUTES[@]}")
if ((${#v6_routes[@]} > 0)); then
v6_enabled=1
log "Static IPv6 default route detected."
elif ((${#v6_all_routes[@]} > 0)); then
log "IPv6 defaults are dynamically managed; preserving them and skipping IPv6."
else
log "No IPv6 default route detected; IPv6 will be skipped."
fi
(( v4_enabled || v6_enabled )) || die "No supported static default route found for IPv4 or IPv6."
(( v4_enabled == 0 )) || read_rate "IPv4" "$arg_v4" "$auto_yes" rate4
(( v6_enabled == 0 )) || read_rate "IPv6" "$arg_v6" "$auto_yes" rate6
log "Detected configuration: IPv4=${v4_enabled}, IPv6=${v6_enabled}"
(( v4_enabled == 0 )) || log "IPv4 rate: ${rate4} Mbps"
(( v6_enabled == 0 )) || log "IPv6 rate: ${rate6} Mbps"
if [[ "$auto_yes" != "1" && -t 0 ]]; then
local answer
read -r -p "Proceed with installation? [y/N] " answer || answer=""
[[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]] || { log "Cancelled."; return 0; }
fi
mkdir -p "$STATE_DIR"
capture_service_state
# Stop an older instance before replacing its unit file.
systemctl stop "$SERVICE_NAME" >/dev/null 2>&1 || true
if (( v4_enabled )); then
snapshot_route 4 "$STATE_DIR/ipv4.routes" "${v4_routes[@]}"
snapshot_rule "0.0.0.0/0" "$STATE_DIR/ipv4.rule"
fi
if (( v6_enabled )); then
snapshot_route 6 "$STATE_DIR/ipv6.routes" "${v6_routes[@]}"
snapshot_rule "::/0" "$STATE_DIR/ipv6.rule"
fi
backup_file_once "$MODULE_FILE" module_conf
backup_file_once "$CONFIG_FILE" config
backup_file_once "$SERVICE_FILE" service
mkdir -p /etc/modules-load.d /etc/default /etc/systemd/system
cat > "$MODULE_FILE" <<'MODULE_EOF'
brutal
MODULE_EOF
chmod 644 "$MODULE_FILE"
cat > "$CONFIG_FILE" <<CONFIG_EOF
# Managed by tcp-brutal-manager
BRUTAL_IPV4_ENABLED=$v4_enabled
BRUTAL_IPV4_RATE=$rate4
BRUTAL_IPV6_ENABLED=$v6_enabled
BRUTAL_IPV6_RATE=$rate6
CONFIG_EOF
chmod 644 "$CONFIG_FILE"
cat > "$SERVICE_FILE" <<'SERVICE_EOF'
[Unit]
Description=TCP Brutal IPv4/IPv6 Rules and Routes
Wants=network-online.target
After=network-online.target systemd-modules-load.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/tcp-brutal-manager apply
RemainAfterExit=yes
TimeoutStartSec=120
[Install]
WantedBy=multi-user.target
SERVICE_EOF
chmod 644 "$SERVICE_FILE"
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
if ! systemctl restart "$SERVICE_NAME"; then
log "Service failed. Recent journal:"
journalctl -u "$SERVICE_NAME" -n 100 --no-pager || true
die "Installation failed. Run '$MANAGER_BIN uninstall' to roll back."
fi
log "Installation completed."
"$MANAGER_BIN" status || true
}
restore_rule() {
local prefix="$1" file="$2"
local line token rate="" gain="20" lock="1" command_line
[[ -r /proc/net/tcp_brutal/rules ]] || return 0
brutalctl del "$prefix" >/dev/null 2>&1 || true
if [[ -s "$file" ]]; then
IFS= read -r line < "$file" || true
for token in $line; do
case "$token" in
rate=*) rate="${token#rate=}" ;;
gain=*) gain="${token#gain=}" ;;
lock=*) lock="${token#lock=}" ;;
esac
done
if [[ "$rate" =~ ^[0-9]+$ && "$gain" =~ ^[0-9]+$ ]]; then
command_line="add $prefix rate=$rate gain=$gain"
[[ "$lock" == "0" ]] && command_line+=" nolock"
if printf '%s\n' "$command_line" > /proc/net/tcp_brutal/rules; then
log "Restored previous Brutal rule for $prefix"
else
log "WARNING: failed to restore previous rule for $prefix"
fi
fi
fi
}
cmd_uninstall() {
require_root
require_cmd systemctl
require_cmd ip
local auto_yes=0
while (($#)); do
case "$1" in
--yes|-y) auto_yes=1; shift ;;
-h|--help)
echo "Usage: tcp-brutal-manager uninstall [--yes]"
return 0 ;;
*) die "Unknown uninstall option: $1" ;;
esac
done
[[ -d "$STATE_DIR" ]] || die "No installation state found at $STATE_DIR."
if [[ "$auto_yes" != "1" && -t 0 ]]; then
local answer
read -r -p "Uninstall TCP Brutal rules/service and restore saved routes? [y/N] " answer || answer=""
[[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]] || { log "Cancelled."; return 0; }
elif [[ "$auto_yes" != "1" ]]; then
die "Use uninstall --yes for non-interactive execution."
fi
systemctl disable --now "$SERVICE_NAME" >/dev/null 2>&1 || true
if command -v modprobe >/dev/null 2>&1; then
modprobe brutal >/dev/null 2>&1 || true
fi
# Delete our /0 rules, restore any previous matching rules, then restore routes.
if [[ -e "$STATE_DIR/ipv4.routes" ]]; then
restore_rule "0.0.0.0/0" "$STATE_DIR/ipv4.rule"
restore_routes 4 "$STATE_DIR/ipv4.routes"
fi
if [[ -e "$STATE_DIR/ipv6.routes" ]]; then
restore_rule "::/0" "$STATE_DIR/ipv6.rule"
restore_routes 6 "$STATE_DIR/ipv6.routes"
fi
# Restore files that existed before install; remove files that were newly created.
restore_file "$MODULE_FILE" module_conf
restore_file "$CONFIG_FILE" config
restore_file "$SERVICE_FILE" service
systemctl daemon-reload
if [[ -e "$STATE_DIR/service-was-enabled" ]]; then
systemctl enable "$SERVICE_NAME" >/dev/null 2>&1 || true
fi
if [[ -e "$STATE_DIR/service-was-active" ]]; then
systemctl start "$SERVICE_NAME" >/dev/null 2>&1 || true
fi
rm -rf -- "$STATE_DIR"
log "Uninstall completed. The manager command itself is kept at $MANAGER_BIN."
}
cmd_status() {
echo '===== systemd ====='
systemctl status tcp-brutal-rules.service --no-pager || true
echo
echo '===== IPv4 Brutal routes ====='
ip -4 route show table main proto 233 || true
echo
echo '===== IPv6 Brutal routes ====='
ip -6 route show table main proto 233 || true
echo
echo '===== Brutal rules ====='
if command -v brutalctl >/dev/null 2>&1; then
brutalctl list || true
elif [[ -r /proc/net/tcp_brutal/rules ]]; then
cat /proc/net/tcp_brutal/rules
else
echo 'TCP Brutal module is not loaded.'
fi
}
usage() {
cat <<'USAGE'
TCP Brutal manager
Usage:
tcp-brutal-manager install [--ipv4-rate Mbps] [--ipv6-rate Mbps] [--yes]
tcp-brutal-manager uninstall [--yes]
tcp-brutal-manager apply
tcp-brutal-manager status
Examples:
tcp-brutal-manager install
tcp-brutal-manager install --ipv4-rate 500 --ipv6-rate 800
tcp-brutal-manager install --yes
tcp-brutal-manager uninstall
tcp-brutal-manager uninstall --yes
USAGE
}
command_name="${1:-help}"
shift || true
case "$command_name" in
install) cmd_install "$@" ;;
uninstall) cmd_uninstall "$@" ;;
apply) cmd_apply "$@" ;;
status) cmd_status "$@" ;;
help|-h|--help) usage ;;
*) usage; die "Unknown command: $command_name" ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment