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

相关推荐

  • 什么是云搜索?

    云搜索是运用云计算技术的搜索引擎,可以绑定多个域名,定义搜索范围和性质,同时,不同域名可以有不同UI和流程,这个UI和流程由运行在云计算服务器上的个性化程序完成。 作为新型搜索引擎,与传统搜索引擎需要输入多个关键字不同的是,用户可以告诉搜索引擎每个搜索关键字的比重,每个搜索关键字都被置于“搜索云”中,并用不同大小,粗细的字型区分。

    2023-02-08 13:40:01
  • 外贸原单

    外贸原单是指国外大品牌提供面料、版型,到国内寻找厂家生产的商品。也被称为余单或尾单,如果质量合格,这些商品就是专卖店里的“正品”。

    2024-01-15 17:12:59