Shell脚本查看端口是否被占用

#!/bin/sh
 
# 检查端口是否被占用并输出占用程序
check_port_usage() {
    port=$1
    # 使用netstat命令检查端口
    result=$(netstat -tuln | grep :$port)
    if [ -z "$result" ]; then
        echo "Port $port is not being used."
    else
        # 输出占用端口的进程ID
        echo "Port $port is being used by the following processes:"
        netstat -tulnp | grep :$port
    fi
}
 
# 主函数,检查多个端口
main() {
    # 定义需要检查的端口数组
    ports=(80 443 8080)
    for port in "${ports[@]}"; do
        check_port_usage $port
    done
}
 
# 调用主函数
main

 

posted @ 2024-03-28 17:31  Sherlock先生  阅读(555)  评论(0编辑  收藏  举报