如何统计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
如何熟悉Base Shell的变量的间接引用?

1 前言 一个问题,一篇文章,一出故事。 笔者希望以一个变量名称去引用另一个变量,于是整理此文。 2 …

Bash
如何实现文件夹路径转纯数字符串?

1 前言 一个问题,一篇文章,一出故事。 由于由于需要设置某目录的配额,配额要求为每个目录指定一个项 …

Bash
如何获取VSFTP昨天活跃和有效用户?

1 前言 一个问题,一篇文章,一出故事。 笔者生产环境有台老旧的FTP服务器,用户众多。笔者希望每天 …