方法一:
function random_unused_port {
(netstat --listening --all --tcp --numeric |
sed '1,2d; s/[^[:space:]]*[[:space:]]*[^[:space:]]*[[:space:]]*[^[:space:]]*[[:space:]]*[^[:space:]]*:\([0-9]*\)[[:space:]]*.*/\1/g' |
sort -n | uniq; seq 1 1000; seq 1 65535
) | sort -n | uniq -u | shuf -n 1
}
RANDOM_PORT=$(random_unused_port)
方法二:
来源:https://www.shuzhiduo.com/A/l1dybNgbze/
#!/bin/bash
# @Desc 此脚本用于获取一个指定区间且未被占用的随机端口号
# @Author Hellxz <hellxz001@foxmail.com>
PORT=0
#判断当前端口是否被占用,没被占用返回0,反之1
function Listening {
TCPListeningnum=`netstat -an | grep ":$1 " | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l`
UDPListeningnum=`netstat -an | grep ":$1 " | awk '$1 == "udp" && $NF == "0.0.0.0:*" {print $0}' | wc -l`
(( Listeningnum = TCPListeningnum + UDPListeningnum ))
if [ $Listeningnum == 0 ]; then
echo "0"
else
echo "1"
fi
}
#指定区间随机数
function random_range {
shuf -i $1-$2 -n1
}
#得到随机端口
function get_random_port {
templ=0
while [ $PORT == 0 ]; do
temp1=`random_range $1 $2`
if [ `Listening $temp1` == 0 ] ; then
PORT=$temp1
fi
done
echo "port=$PORT"
}
get_random_port 1 10000; #这里指定了1~10000区间,从中任取一个未占用端口号
示例