服务进程状态信息检测工具

  Linux

基本信息:
来源:蓝鲸智云
功能:根据进程名或PID或进程命令行参数查询进程,并输出相关进程信息
类型:脚本工具
版本号:0.1
开发语言:Bash
文件大小:4KB
OS版本兼容:Centos6/Centos7/Ubuntu14.04/Debian8.2
部署环境:Linux
语言支持:en_US.UTF-8

详情:
使用方法:./get_proc_stat.sh [value]
: 指定查找类型,可选: name(按进程名), pid(按进程id), arg(按进程执行参数)
[value]: 指定查找的条件,如果有特殊字符,请使用引号

执行结果示例:
字段名含义:
PID: 进程ID
COMMAND: 进程名
USER: 执行用户
%CPU: CPU使用率
RSS: 实际使用物理内存
STAT: 进程状态
STARTED: 进程启动时间
CWD: 进程启动时的工作目录
FH: 打开文件句柄数,NOACCESS表示权限不足
CHD: 子进程数量

# ./get_proc_stat.sh name rsync

PID COMMAND USER %CPU RSS STAT STARTED CWD FH CHD
13676 rsync root 0.0 96 Ss Mon May 19 16:03:52 2014 NULL NOACCESS 0
14516 rsync 20036 0.0 440 Ss Wed Dec 30 15:57:14 2015 /home/test 4 0
#!/usr/bin/env bash
#===============================================================================
#
#          FILE: get_proc_stat.sh
# 
#         USAGE: ./get_proc_stat.sh [name|pid|arg] [value]
# 
#   DESCRIPTION: 根据进程名或PID或进程命令行参数查询进程,并输出相关进程信息
# 
#       OPTIONS: ---
#  REQUIREMENTS: ---
#          BUGS: ---
#         NOTES: ---
#  ORGANIZATION: BlueKing
#       CREATED: 02/14/2017 14:34
#      REVISION:  ---
#===============================================================================

set -o nounset                              # Treat unset variables as an error

ok () {
    echo "(date +%F\ %T)||BASH_LINENO|info|job success: *"    exit 0
}

die () {
    echo "(date +%F\ %T)|$|BASH_LINENO|error|job fail: *" >&2
    exit 1
}

usage() {    cat <<_OO_
USAGE:
    get_proc_stat.sh [name|pid|arg] [value]

_OO_
    exit 1
}

# 通过/proc/下获取文件句柄和进程工作目录
get_pid_stat_proc() {
    local pids="1"

    {
    shopt -s nullglob
    echo "CWD FH"
    for pid in {pids/,/ /}; do
    cwd=(readlink -f "/proc/pid/cwd")
    fds=(/proc/pid/fd/*)
    fd_cnt={#fds[@]}
    [[ -z "cwd" ]] && cwd="NULL"
    (( fd_cnt == 0 )) && fd_cnt="NOACCESS"
    echo "cwdfd_cnt"
    done
    } | column -t 
}

# 获取指定PID的所有子进程PID
get_chd_pid() {
    local chd_pids=(pgrep -P "1" | xargs)
    for cpid in chd_pids; do
    echo "cpid"
    get_chd_pid "cpid"
    done
}

# 输出进程的所有子进程数量
get_pid_cpid_cnt() {
    local pids="1"

    {
    shopt -s nullglob
    echo "CHD"
    for pid in {pids/,/ }; do
    chd=(get_chd_pid "pid" | wc -l)
    echo "chd"
    done
    } | column -t
}


# 汇总输出
get_pid_stat() {
    local pids="1"

    if [[ -z "pids" ]]; then
    die "no such process."
    fi

    # sort pids
    pids=(echo "pids" | sed s'/,/\n/g'  | sort -n | xargs | sed 's/ /,/g')

    ps_output=(ps -p "pids" -o pid,comm,user,pcpu,rss,stat,lstart)
    cwd_output=(get_pid_stat_proc "pids") 
    cpid_output=(get_pid_cpid_cnt "pids")
    paste <(echo "ps_output") <(echo "cwd_output") <(echo "cpid_output")
}

if [[# -eq 2 ]]; then
    case 1 in    name)   pids=(pgrep -d, -x "2") ;;
    arg)    pids=(pgrep -d, -f "2") ;;
    pid)    pids="2" ;;
    *)  usage ;;
    esac

    get_pid_stat "$pids"
else
    usage
fi