如何统计Linux打开文件前10进程?

Bash

1 前言

一个问题,一篇文章,一出故事。
笔者生产环境有台服务最近压力比较大,打开的文件数量不断地往上涨,于是笔者需要写一个脚本用于分析前十打开文件的进程。
此脚本将扫描系统所有打开文件的进程然后统计前十名的进程,然后打印简表以供运维用于分析和故障排除。

2 最佳实践

2.1 创建管理脚本

vim ~/scripts/getOpenFileTop.sh

加入如下配置,

#!/bin/bash

top="10"
openFileTop="/root/openFileTop.txt"
lsofile="/root/lsof.txt"

getOpenFileTop() {
        for pid in `awk -F' ' '{print $2}' "$lsofile" | grep -v PID | sort -nru`; do
                total=`awk -F' ' '$2 == '"$pid" "$lsofile" | wc -l`
                echo "$pid $total"
        done | sort -rn -k 2 | head -n "$top"
        if [ -f "$lsofile" ]; then
                rm -f "$lsofile"
        fi
}

getOpenFileTable() {
        openFileTop=$1
        echo -e "PID\tOpenFile\tCMD"
        IFS=$'\n'
        for list in $openFileTop; do
                pid=`echo "$list" | awk -F' ' '{print $1}'`
                total=`echo "$list" | awk -F' ' '{print $2}'`
                cmd=`ps -ef | grep "$pid" | grep -v grep | awk -F' ' '$2 =='"$pid"' {for (i=8;i<=NF;i++)printf("%s ", $i);print ""}'`
                echo -e "$pid\t$total\t$cmd"
        done
}

lsof | tee "$lsofile"
list=`getOpenFileTop`
echo -e "\n"
getOpenFileTable "$list" | tee "$openFileTop"

2.2 执行脚本

sh ~/scripts/getOpenFileTop.sh
没有评论

发表回复

Bash
如何用Tigase监控Elasticsearch集群?

1 前言 一个问题,一篇文章,一出故事。 笔者生产中有一套Elasticsearch集群,笔者为了能 …

Bash
如何用Base Shell获取ES集群状态?

1 前言 一个问题,一篇文章,一出故事。 笔者想要通过Base Shell获取Elasticsear …

Bash
如何熟悉grep命令?

截取括弧“()”中的字符串, echo “This is a test (sample string …