57 lines
1.6 KiB
Bash
57 lines
1.6 KiB
Bash
#!/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
|
||
}
|
||
|
||
update_port(){
|
||
local script_dir=$(cd "$(dirname "$0")"; pwd)
|
||
local config_dir="$script_dir/../conf"
|
||
source "$script_dir/utils/jq_util.sh"
|
||
|
||
local port=$(find_free_port)
|
||
modify_json_file "$config_dir/config.json" ".inbounds[0].port" "$port"
|
||
echo "设置端口成功"
|
||
}
|
||
|
||
update_port |