zabbix api批量添加主机python脚本


zabbix实现smokeping的功能,所需文件已放到附件python

[root@localhost smokeping]# ls
all  create_graph.py  create_other_screen.py  define  monitor.py  zabbix_tool.py  zbx_cli.py  target zbx_export_templates.xml zbxsmokepingprimary

all文件里面记录需要监控的ip地址格式如下:

220.178.75.134
211.91.88.129
211.138.180.2
202.38.64.1
202.175.3.3

安装supervisord后台运行监控脚本create_graph.py

easy_install supervisor

配置文件加入以下行

cat /etc/supervisord.conf

[program:zabbixsmokeping]
directory = /usr/local/zabbix/share/zabbix/alertscripts/smokeping
command = python create_graph.py
autostart = true
startsecs = 5
autorestart = true
startretries = 3
user = root
redirect_stderr = true
stdout_logfile_maxbytes = 20MB
stdout_logfile_backups = 20
stdout_logfile = /var/log/usercenter_stdout.log
;environment=PYTHONPATH=$PYTHONPATH:/path/to/somewhere

zabbix启用externalscripts 以及配置fping功能。

zabbix前端导入模板文件zbx_export_templates.xml,zbxsmokepingprimary数据采集脚本放到/usr/local/zabbix/share/zabbix/externalscripts文件夹下需要修改以下内容:

#!/bin/bash
# Where is your zabbix server
ZBXSERVER=192.168.0.72
# where is fping tool?
FPING=/usr/sbin/fping
# where is zabbix_sender tool?
ZBXSENDER=/usr/local/zabbix/bin/zabbix_sender
# Where to send ping
IP=$1
# How many ping to send
COUNT=$2
# What interval between ping [ms]
INTERVAL=$3
# How many bytes in one ping
BYTES=$4
# 'Hostname' of the host which will collect data
HOSTNAME=$5

if [ $# -lt 5 ]
then
echo
echo " Not enough parameters"
echo " Usage: zbxsmokeping <HOST_IP> <NUMBERS_OF_PINGS> <INTERVAL> <BYTES> <TO_WHICH_HOST_SEND_DATA_IN_ZABBIX>"
echo " Zabbix External Check Item ex.: zbxsmokeping[{HOST.IP},6,1000,68,{HOST.HOST}]"
exit 2
fi
# debug
#echo $FPING -b $BYTES -c $COUNT -q -p $INTERVAL $IP 2>&1

OUTPUT=`$FPING -b $BYTES -c $COUNT -q -p $INTERVAL $IP 2>&1 | awk '{print $5,$8}' | tr -d "%|," | tr -s " " "/" | awk -F"/" '{print $3,$4,$5,$6}'`
tab=( $OUTPUT )
# debug
# echo $ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLoss -o ${tab[0]}
# echo $ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyMin -o ${tab[1]}
# echo $ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyMax -o ${tab[3]}
# echo $ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyAvg -o ${tab[2]}

$ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLoss -o ${tab[0]}  | grep -v  "Failed 0" &> /dev/null
$ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyMin -o ${tab[1]} | grep -v  "Failed 0" &>/dev/null
$ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyMax -o ${tab[3]} |grep -v  "Failed 0"  &>/dev/null
$ZBXSENDER -z $ZBXSERVER -p 10051 -s $HOSTNAME -k PrimaryLatencyAvg -o ${tab[2]} | grep -v  "Failed 0"  &>/dev/null

使用脚本批量添加主机需要用到的文件如下:

zabbix_tool.py  zbx_cli.py  target

修改zabbix_tool.py里面的zabbix登陆地址以及用户名和密码。

target写入需要批量添加的ip,格式:可见名,ip用逗号隔开。

net202,221.13.65.35
net203,211.139.73.34
net204,210.26.176.33

三个文件放到同级目录执行 python zbx_cli.py -A

输入组名和模板名


Whatever is worth doing is worth doing well.