Linux Shell 判断指定端口是否已经被占用

一、方法

1. 使用命令

netstat [-acCeFghilMnNoprstuvVwx][-A<网络类型>][--ip]

2. 脚本

(1) 创建

vi test.sh

(2) 初始化

if netstat -an | grep "$1" | grep -i listen >/dev/null ; then
    echo "$1 is running."
else
    echo "$1 is not running."
fi

(3) 赋权

chmod +x test.sh

(4) 运行

./test.sh 8080

二、参考

1. 官方

https://linux.die.net/man/8/netstat

https://www.runoob.com/linux/linux-comm-netstat.html

2. 其他

https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/

https://unix.stackexchange.com/questions/149419/how-to-check-whether-a-particular-port-is-open-on-a-machine-from-a-shell-script

https://serverfault.com/questions/1078483/how-to-find-out-what-service-is-listening-on-a-specific-port-of-a-ubuntu-server/1079542

https://serverfault.com/questions/309052/check-if-port-is-open-or-closed-on-a-linux-server

posted @ 2023-07-29 20:46  白马黑衣  阅读(618)  评论(0编辑  收藏  举报