方法一:

  1. function random_unused_port {
  2. (netstat --listening --all --tcp --numeric |
  3. sed '1,2d; s/[^[:space:]]*[[:space:]]*[^[:space:]]*[[:space:]]*[^[:space:]]*[[:space:]]*[^[:space:]]*:\([0-9]*\)[[:space:]]*.*/\1/g' |
  4. sort -n | uniq; seq 1 1000; seq 1 65535
  5. ) | sort -n | uniq -u | shuf -n 1
  6. }
  7. RANDOM_PORT=$(random_unused_port)

方法二:

来源:https://www.shuzhiduo.com/A/l1dybNgbze/

  1. #!/bin/bash
  2. # @Desc 此脚本用于获取一个指定区间且未被占用的随机端口号
  3. # @Author Hellxz <hellxz001@foxmail.com>
  4. PORT=0
  5. #判断当前端口是否被占用,没被占用返回0,反之1
  6. function Listening {
  7. TCPListeningnum=`netstat -an | grep ":$1 " | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l`
  8. UDPListeningnum=`netstat -an | grep ":$1 " | awk '$1 == "udp" && $NF == "0.0.0.0:*" {print $0}' | wc -l`
  9. (( Listeningnum = TCPListeningnum + UDPListeningnum ))
  10. if [ $Listeningnum == 0 ]; then
  11. echo "0"
  12. else
  13. echo "1"
  14. fi
  15. }
  16. #指定区间随机数
  17. function random_range {
  18. shuf -i $1-$2 -n1
  19. }
  20. #得到随机端口
  21. function get_random_port {
  22. templ=0
  23. while [ $PORT == 0 ]; do
  24. temp1=`random_range $1 $2`
  25. if [ `Listening $temp1` == 0 ] ; then
  26. PORT=$temp1
  27. fi
  28. done
  29. echo "port=$PORT"
  30. }
  31. get_random_port 1 10000; #这里指定了1~10000区间,从中任取一个未占用端口号

示例
image.png