linux下shell监控脚本

线程数:  thread_num = $(pstree -p $PID | wc -l)

打开文件数: open_files = $(lsof -p $PID | wc -l)

cpu占用率: cpu = 'top -bn 1 -p $PID | awk 'NR==8{PRINT $9}''

虚存使用量: vmem = 'ps aux | grep $PID | grep -v grep | awk '{print $5}''   #单位m

                    vmem = 'top -bn 1 -p $PID | awk 'NR==8{print $5}''    #单位k

内存使用量: vmem = 'ps aux | grep $PID | grep -v grep | awk '{print $6}''   #单位m

                    vmem = 'top -bn 1 -p $PID | awk 'NR==8{print $6}''    #单位k

   

shell 脚本如下:

#! /bin/bash

# 间隔时间
SLEEP_TIME=30


if [ "$#" -lt 1 ]   # $# 传递给脚本或函数的参数个数
then
    echo "Usage: $0 program"   # $0 脚本名称
    exit -1;
fi

# 第一个参数为被监控的进程ID
PID="$1"
FILTER="grep\|monitor\|ps\|top\|lsof\|pstree\|sz\|rz\|gdb"
PROCESS_NAME=$(ps -ef | grep ${PID} | grep -v ${FILTER} | awk '{print $8}' | awk -F '[/]' '{print $NF}')
# 自动抓取进程名,拼接日志文件名 [进程名]_[PID]_stress_monitoring_record.log
LOG="${PROCESS_NAME}_${PID}_stress_monitoring_record.log"

thread_num=0
open_files=0
vmem=0
mem=0
cpu_info=""


while true
do
    # 判断被监控的进程是否启动
    PRO_NOW=`ps aux | grep $PID | grep -v ${FILTER} | wc -l`
    if [ $PRO_NOW -eq 0 ]
    then 
        echo "`date +"%Y-%m-%d %H:%M:%S"`, $PID is not running!!!!!!!!!!!!!" >> ./$LOG
    else
        #线程数
        thread_num=$(pstree -p $PID | wc -l)
        #打开文件数
        open_files=$(lsof -p $PID | wc -l)
        #cpu占用率
        cpu_info=`top -bn 1 -p $PID | awk 'NR==8 {print $9}'`
        #虚拟内存使用量
        vmem=`ps aux | grep $PID | grep -v ${FILTER} | awk '{print $5}'`
        #内存使用量
        mem=`ps aux | grep $PID | grep -v ${FILTER} | awk '{print $6}'`
        #输出到日志文件
        echo -e "`date +"%Y-%m-%d\t%H:%M:%S"`\t${vmem}\t${mem}\t${cpu_info}\t${open_files}\t${thread_num}" >> ./${LOG}
    fi
    sleep $SLEEP_TIME
done


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值