Linux获取监听指定端口的进程PID

在 Linux 下经常需要杀死(重启)监听某端口的进程, 因此就写了一个小脚本, 通过 ss 命令获取监听制定端口的进程 PID, 然后通过 kill 命令结束掉进程:

#!/bin/sh

# set -x

[[ $# -lt 1 ]] && { echo 'param error: must have one param(port)'; exit -1; }
[[ $# -gt 1 ]] && { echo 'param error: only support one param(port)'; exit -1; }

function get_pid_by_listen_port() {
        pattern_str="*:$1\b"
        pid=$(ss -n -t -l -p | grep "$pattern_str" | column -t | awk -F ',' '{print $(NF-1)}')

        # 当版本号为 "ss utility, iproute2-ss161009" 时, ss 命令输出格式为:
        #              LISTEN  0  5  *:8000  *:*  users:(("python2.7",pid=7130,fd=3))
        # 此时需要进一步处理, 只获取进程 PID 值.
        [[ $pid =~ "pid" ]] && pid=$(echo $pid | awk -F '=' '{print $NF}')

        echo $pid
}

pid=$(get_pid_by_listen_port $1)
if [ -n "$pid" ]
then
        echo "find pid: $pid, kill it..."
        kill $pid
else
        echo 'cannot find listened port: '$1
        exit -1
fi

如果只是想放入 .bashrc 或 .zshrc 的话, 可以使用下面这个版本:

function kill_pid_by_listen_port() {
        [[ $# -lt 1  ]] && { echo 'param error: must have one param(port)'; return -1;  }
        [[ $# -gt 1  ]] && { echo 'param error: only support one param(port)'; return -1;  }

        pattern_str="*:$1\b"
        pid=$(ss -n -t -l -p | grep "$pattern_str" | column -t | awk -F ',' '{print $(NF-1)}')

        # 当版本号为 "ss utility, iproute2-ss161009" 时, ss 命令输出格式为:
        #              LISTEN  0  5  *:8000  *:*  users:(("python2.7",pid=7130,fd=3))
        # 此时需要进一步处理, 只获取进程 PID 值.
        [[ $pid =~ "pid" ]] && pid=$(echo $pid | awk -F '=' '{print $NF}')

        [[ -n "$pid" ]] && { "find pid: $pid, kill it..." }
        [[ -n "$pid" ]] || { echo "not found listened port: $1" }
}

想了解更多关于Linux获取监听指定端口的进程PID的内容,请扫微信
或微信搜索jiemingpan

本文链接:http://www.soufuzi.com/jianzhan/2989

(0)
上一篇 2025-04-08 00:59:27
下一篇 2025-04-08 00:59:27

相关推荐

  • 服务器未被授权访问什么意思

    "服务器未被授权访问"意味着某个服务器在试图接收用户请求时被拒绝或限制。这种情况通常是由于服务器管理员对资源或功能设置了访问控制规则,而用户未能通过这些规则来获得访问权限。当用户尝试访问受保护的文件、目录或服务时,服务器会返回错误消息,通知用户他们被拒绝访问。 服务器未被授权访问的原因可能有很多,以下是一些常见的情况: 没有正确的凭证:服务器可能要求用户提供有效的凭证(如用户名和密码)以验证用户身份。如果用户

    2025-05-10 15:08:58
  • ADP国际快递

    ADP express Co. established in 2001, has tried be a top level company in the logistics industry. ADP express inc. is one of leading courier in china that offers all kind of shipping through china area. At this time,

    2023-07-08 16:41:16