目的:选择一定范围内第一个可用的端口。例如,如果端口 600 不可用,则将检查端口 601 的可用性。
试图:以下脚本按预期工作,但在我看来过于全面:
PORT=601; until [ $PORT -gt 610 ]; do
if ! [[ `ss -nat | grep "*:$PORT\s"` ]]; then
echo $PORT;
exit 0;
elif [ $PORT -eq 610 ]; then
echo "no ports available";
exit 1;
fi;
let PORT+=1;
done
预期答案:提供最简洁脚本的答案将被投票并接受。请注意,脚本仍然应该能够符合目标。
答案1
这个怎么样。仅调用ss
一次即可受益。
USED=$(ss -nat '( sport >= :601 and sport <= :610 )'|awk 'NR>1{print substr($4,3)}')
for PORT in {601..610}; do
echo $USED | grep $PORT >/dev/null
if [ $? != 0 ];then
echo $PORT
exit 0
fi
done
echo no ports available
exit 1
稍微短一点的尝试:
USED=$(ss -nat '( sport >= :601 and sport <= :610 )'|awk 'NR>1{print substr($4,3)}')
for PORT in {601..610}; do
[[ ! "$USED" =~ "$PORT" ]] && echo $PORT && exit 0
done
echo no ports available
exit 1
答案2
PORT=$(ss -nat | cut -b47- | sort -n |
awk 'BEGIN{p=601} $1+0>610{exit(1)} $1+0==p{p++} $1+0>p{print p;exit}') ||
echo "no ports available"
作为信息,这是我的产品的输出格式ss -nat
。因此cut -b47-
正好切入题为“港口。
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 127.0.0.1:9292 *:*
LISTEN 0 9 *:21 *:*
LISTEN 0 10 192.168.1.2:53 *:*
LISTEN 0 128 192.168.1.2:8000 *:*
ESTAB 0 0 127.0.0.1:8000 127.0.0.1:38587
TIME-WAIT 0 0 127.0.0.1:8000 127.0.0.1:38574
LISTEN 0 16 ::1:3493 :::*
LISTEN 0 128 :::111 :::*
LISTEN 0 128 ::1:631 :::*