1.自动发现实例端口脚本,用于zbx item prototypes
#!/bin/bash
REDIS_PORT=`ps aux |grep redis-server | grep -v 'grep'|awk -F'[:]' '{print $4}'`
COUNT=`echo "$REDIS_PORT" | wc -l`
INDEX=0
echo '{"data":['
echo "$REDIS_PORT" | while read LINE; do
echo -n '{"{#PORTNUM}":"'$LINE'"}'
INDEX=`expr $INDEX + 1`
if [ $INDEX -lt $COUNT ]; then
echo ','
fi
done
echo ']}'
{"data":[
{"{#PORTNUM}":"6379"},
{"{#PORTNUM}":"6380"}]}
2.crontab周期取数脚本,每1分钟运行两次,zbx每30s取值一次
* * * * * /bin/sh /usr/local/zabbix/bin/redis_port_cron.sh
#!/bin/bash
# redis_port_cron.sh
# 获取CPU使用临时存储
for (( i=0;i < 2;i=(i+1) ));do
TMP_DATA=/tmp/redis_cpu_util_tmp.log
DEST_DATA=/tmp/redis_cpu_util.log
echo "REDIS_PORT CPU_percent MEM_percent MEM_GB" > $TMP_DATA
pid_array=`ps aux |grep redis-server | grep -v 'grep' | awk '{print $2}'`
for pid in ${pid_array[@]}
do
redis_port=`top -c -b -n 1 -p $pid|tail -n 2 |awk -F'[:]' 'NR==1{print $3}'`
redis_cpu_util=`top -c -b -n 1 -p $pid | tail -2|awk 'NR==1{print $9}'`
redis_mem_util=`top -c -b -n 1 -p $pid | tail -2|awk 'NR==1{print $10}'`
redis_mem_MAX=`awk '($1 == "MemTotal:"){print $2/1048576}' /proc/meminfo`
redis_mem_GB=`awk 'BEGIN{print "'$redis_mem_MAX'"*"'$redis_mem_util'"/100}'`
echo $redis_port $redis_cpu_util $redis_mem_util $redis_mem_GB >> $TMP_DATA
done
sleep 20
done
[ -e $TMP_DATA ]&& mv $TMP_DATA $DEST_DATA
- 运行结果如下,第一列是端口号,第二列是CPU百分比,第三列是内存百分比,将内存转换成GB:
REDIS_PORT CPU_percent MEM_percent MEM_GB
6379 0.0 0.8 0.0146658
6380 0.0 0.4 0.00733288
3.zbx传key值
#!/bin/bash
# redis_custom_check.sh
ZBX_REDIS_PORT="$1"
ZBX_REDIS_KEY="$2"
# source data file
SOURCE_DATA=/tmp/redis_cpu_util.log
# No data file to read from
if [ ! -f "$SOURCE_DATA" ]; then
echo "NO DATA FILE FOR READ"
exit 1
fi
# 1st check the device exists and gets data gathered by cron job
port_count=$(grep -Ec "^$ZBX_REDIS_PORT" $SOURCE_DATA)
if [ $port_count -eq 0 ]; then
echo "NO DATA FOR READ"
exit 1
fi
# 2nd grab the data from the source file
case $ZBX_REDIS_PORT in
CPU_percent ) grep -E "^$ZBX_REDIS_PORT" $SOURCE_DATA | awk '{print $2}';;
MEM_percent ) grep -E "^$ZBX_REDIS_PORT" $SOURCE_DATA | awk '{print $3}';;
MEM_GB) grep -E "^$ZBX_REDIS_PORT" $SOURCE_DATA | awk '{print $4}';;
*) echo "ERROR_WRONG_PARAM"; exit 1;;
esac
exit 0
4.重启zbx agent 测试key
UserParameter=redis.port.discovery,/bin/sh /usr/local/zabbix/bin/redis_port_discovery.sh
UserParameter=redis.instance.util[*],/bin/sh /usr/local/zabbix/bin/redis_custom_check.sh $1 $2
zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,CPU_percent]
zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,MEM_GB]
zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,MEM_percent]
[root@GZ-LT-DB-redis01 zabbix_agentd.conf.d]# zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,CPU_percent]
0.0
[root@GZ-LT-DB-redis01 zabbix_agentd.conf.d]# zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,MEM_GB]
0.0146658
[root@GZ-LT-DB-redis01 zabbix_agentd.conf.d]# zabbix_get -s 127.0.0.1 -k redis.instance.util[6379,MEM_percent]
0.8
5.建item和图形