Skip to content

Instantly share code, notes, and snippets.

@alice-xu
Created July 1, 2014 01:57
Show Gist options
  • Save alice-xu/54aaf92e0ddf6643b811 to your computer and use it in GitHub Desktop.
Save alice-xu/54aaf92e0ddf6643b811 to your computer and use it in GitHub Desktop.
Process memory monitoring script for Zabbix
#!/usr/bin/env bash
#
# proc_mem.sh:
# Process memory monitoring script for Zabbix
#
# $1: process name
# $2: effective user name
# $3: mode(sum/max/min/avg)
# $4: args pattern
#
# Get parameters from args(set default if no param).
[ -z "$1" ] && COMM='.*' || COMM="$1"
[ -z "$2" ] && EUSER='.*' || EUSER="$2"
[ -z "$3" ] && MODE='sum' || MODE="$3"
[ -z "$4" ] && ARGS_PATTERN='.*' || ARGS_PATTERN="$4"
# Get process list.
PLIST=$( ps -eo rss,comm,euser,args --no-headers )
# Calculate min, max, avg or sum by specified parameter.
case "${MODE}" in
"min")
echo "${PLIST}" \
| awk -v comm="^${COMM}$" -v euser="^${EUSER}$" -v args_pattern="${ARGS_PATTERN}" \
'BEGIN {MIN=0;CNT=0}{
if (($2 ~ comm) && ($3 ~ euser)){
args="";
for(i=4;i<=NF;i++){args=args""$i};
if (args ~ args_pattern) {
if (CNT == 0) { MIN=$1;CNT+=1 } else if ( MIN > $1 ) { MIN=$1 }
}
}
} END {print MIN}'
;;
"max")
echo "${PLIST}" \
| awk -v comm="^${COMM}$" -v euser="^${EUSER}$" -v args_pattern="${ARGS_PATTERN}" \
'BEGIN {MAX=0}{
if (($2 ~ comm) && ($3 ~ euser)){
args="";
for(i=4;i<=NF;i++){args=args""$i};
if (args ~ args_pattern) {
if (MAX < $1) { MAX=$1 }
}
}
} END {print MAX}'
;;
"avg")
echo "${PLIST}" \
| awk -v comm="^${COMM}$" -v euser="^${EUSER}$" -v args_pattern="${ARGS_PATTERN}" \
'BEGIN {SUM=0;CNT=0}{
if (($2 ~ comm) && ($3 ~ euser)){
args="";
for(i=4;i<=NF;i++){args=args""$i};
if (args ~ args_pattern) { SUM+=$1;CNT+=1 }
}
} END {printf("%d\n", SUM/CNT)}'
;;
"sum")
echo "${PLIST}" \
| awk -v comm="^${COMM}$" -v euser="^${EUSER}$" -v args_pattern="${ARGS_PATTERN}" \
'BEGIN {SUM=0}{
if (($2 ~ comm) && ($3 ~ euser)){
args="";
for(i=4;i<=NF;i++){args=args""$i};
if (args ~ args_pattern) { SUM+=$1 }
}
} END {print SUM}'
;;
*)
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment