【问题标题】:Testing whether or not a port is in use with bash and netstat?测试端口是否与 bash 和 netstat 一起使用?
【发布时间】:2016-03-02 01:24:44
【问题描述】:

我已经编写了一个相当长且中等复杂的 Bash 脚本,它使我能够非常轻松地使用选定的选项启动我的 Node 服务器......问题是它无法正常工作。

给我带来麻烦的部分在这里......

if netstat -an | grep ":$REQUESTED_PORT" > /dev/null
then
    SERVICE_PIDS_STRING=`lsof -i tcp:$REQUESTED_PORT -t`
    OLD_IFS="$IFS"
    IFS='
    '
    read -a SERVICE_PIDS <<< "${SERVICE_PIDS_STRING}"
    IFS="$OLD_IFS"
    printf 'Port is in use by the following service(s)...\n\n-------------------\n\nProcess : PID\n\n'
    for PID in "${SERVICE_PIDS[@]}"
        do
            PROCESS_NAME=`ps -p $PID -o comm=`
            printf "$PROCESS_NAME : $PID\n"
        done
    printf "\n-------------------\n\nPlease kill the procceses utilizing port $REQUESTED_PORT and run this script again...exiting.\n"
    exit

此脚本的预期功能是使用netstat 来测试请求的端口是否繁忙。如果是这样,它会报告使用该端口的 PID,以便用户可以根据需要终止它们。

我相当肯定这是我使用netstat 的方式的问题。偶尔,netstat if 语句会触发,即使没有任何东西在使用该端口。 lsof 工作正常,并且不报告任何使用该端口的 PID。

但是,当脚本最后一次出现此错误时,我声明了REQUESTED_PORT,然后运行了netstat -an | grep ":$REQUESTED_PORT"。外壳没有报告任何内容。

导致它在不适当的时间触发的问题是什么?

编辑

我还应该提到这台机器正在运行 Debian Jessie。

【问题讨论】:

  • 虽然 bash 脚本可能被归类为编程,但您可能会在 unix & linux 上获得更好的网络实用程序结果。
  • @BrettHale,感谢您的回复。我认为您是对的,如果将这个问题放在 StackExchange 的 UNIX 和 Linux 类别中会更好。我应该删除我的问题并在那里再次提问,将我的问题留在这里并在那里再次提问,还是请求版主移动我的问题?
  • 你看过bash标签中的其他帖子吗?这完全在“编程”的范围内。确实,不然怎么会有这样的标签?

标签: bash netstat lsof


【解决方案1】:

您正在搜索大量文本,而您想要的数字可能会出现在任何地方。最好缩小搜索范围;您可以在同一步骤中获取您的 PID 和进程名称。其他一些优化如下:

# upper case variable names should be reserved for the shell
if service_pids_string=$(lsof +c 15 -i tcp:$requested_port)
then
    # make an array with newline separated string containing spaces
    # note we're only setting IFS for this one command
    IFS=$'\n' read -r -d '' -a service_pids <<< "$service_pids_string"
    # remove the first element containing column headers
    service_pids=("${service_pids[@]:1}")
    printf 'Port is in use by the following service(s)...\n\n-------------------\n\nProcess : PID\n\n'
    for pid in "${service_pids[@]}"
    do
        # simple space-separated text to array
        pid=($pid)
        echo "${pid[0]} : ${pid[1]}"
    done
    # printf should be passed variables as parameters
    printf "\n-------------------\n\nPlease kill the procceses utilizing port %s and run this script again...exiting.\n" $requested_port
fi

您应该通过shellcheck.net 运行您的脚本;它可能会发现我没有发现的其他潜在问题。

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2011-01-14
    • 2020-11-25
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多