hysteria_docker/bin/update_port.sh
2025-10-09 21:54:23 +08:00

72 lines
2.1 KiB
Bash
Raw 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 old_port=$(jq -r '.listen' "$config_dir/config.json" | awk -F : '{print $2}')
local port
read -p "请输入新的端口[当前端口: $old_port]: " port
# 如果输入端口为空, 查找空闲端口
if [[ -z "$port" ]]; then
port=$(find_free_port)
if [[ -z "$port" ]]; then
echo "未能找到可用端口!" >&2
return 1
fi
echo "未输入端口,自动分配可用端口: $port"
fi
modify_json_file "$config_dir/config.json" ".listen" ":$port"
echo "端口修改成功!新端口为: $port"
}
change_port