hysteria_docker/bin/update_port.sh
2025-11-20 19:24:36 +08:00

57 lines
1.7 KiB
Bash
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
# 查找空闲端口
find_free_port() {
local start="${1:-10001}"
local max="${2:-65535}"
# 收集当前监听端口TCP + UDP
local used_ports raw
if command -v ss >/dev/null 2>&1; then
raw=$(ss -lntu 2>/dev/null || true)
used_ports=$(printf "%s\n" "$raw" | awk '{print $5}' | sed -n '2,$p' | sed -E 's/.*[:]//g' | sed '/^$/d')
elif command -v netstat >/dev/null 2>&1; then
raw=$(netstat -lntu 2>/dev/null || true)
used_ports=$(printf "%s\n" "$raw" | awk '{print $4}' | sed -n '2,$p' | sed -E 's/.*[:]//g' | sed '/^$/d')
elif command -v lsof >/dev/null 2>&1; then
raw=$(lsof -i -P -n 2>/dev/null || true)
used_ports=$(printf "%s\n" "$raw" | awk '/LISTEN/ {print $9}' | sed -E 's/.*[:]//g' | sed '/^$/d')
else
echo "Error: neither ss, netstat nor lsof is available to check listening ports." >&2
return 2
fi
# 用关联数组记录已占用端口(需要 bash 4+
declare -A used_map
local p
for p in $used_ports; do
# 过滤掉非数字
if [[ $p =~ ^[0-9]+$ ]]; then
used_map["$p"]=1
fi
done
# 从 start 到 max 逐个检查
for ((port = start; port <= max; port++)); do
if [[ -z "${used_map[$port]}" ]]; then
echo "$port"
return 0
fi
done
# 没找到可用端口
echo "Error: No available port found in range $start-$max" >&2
return 1
}
change_port(){
local script_dir=$(cd "$(dirname "$0")"; pwd)
local config_dir=$(readlink -f "$script_dir/../")
source "$script_dir/utils/jq_util.sh"
local port=$(find_free_port)
modify_json_file "$config_dir/config.json" ".listen" ":$port"
echo "已分配新的空闲端口, 设置端口成功"
}
change_port