在 linux 下經常需要殺死(重啟)監聽某端口的進程, 因此就寫了一個小腳本,
通過 ss
命令獲取監聽制定端口的進程 PID, 然后通過 kill
命令結束掉進程:
#!/bin/sh
# set -x
function get_pid_by_listened_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}')
echo $pid
}
function kill_pid_by_listened_port() {
pid=$(get_pid_by_listened_port $1)
[[ -n "$pid" ]] && { echo "find pid: $pid, kill it..."; kill $pid; }
[[ -n "$pid" ]] || { echo "not found listened port: $1"; }
}
kill_pid_by_listened_port 8080