歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux獲取監聽指定端口的進程PID

Linux獲取監聽指定端口的進程PID

日期:2017/2/28 13:47:38   编辑:Linux教程

在 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" }
}

Copyright © Linux教程網 All Rights Reserved