1.检查端口
[root@izwz9hcixm5361yy4uz40az ~]# netstat -lntup|grep mysql
tcp6 0 0 :::3306 :::* LISTEN 1849/mysqld
2.过滤获取mysql端口
[root@izwz9hcixm5361yy4uz40az ~]# netstat -lntp|awk -F "[ :\t]+" '/mysqld/{print$4}'
3306
3.创建自动发现多实例脚本
[root@izwz9hcixm5361yy4uz40az ~]# cat /server/scripts/mysql_discovery.sh
#!/bin/bash
#mysql low-level discovery
res=$(netstat -lntp|awk -F "[ :\t]+" '/mysqld/{print$4}')
port=($res)
printf '{'
printf '"data":['
for key in ${!port[@]}
do
if [[ "${#port[@]}" -gt 1 && "${key}" -ne "$((${#port[@]}-1))" ]];then
printf '{'
printf "\"{#MYSQLPORT}\":\"${port[${key}]}\"},"
else [[ "${key}" -eq "((${#port[@]}-1))" ]]
printf '{'
printf "\"{#MYSQLPORT}\":\"${port[${key}]}\"}"
fi
done
printf ']'
printf '}\n'
4.测试自动发现脚本
[root@izwz9hcixm5361yy4uz40az ~]# bash /server/scripts/mysql_discovery.sh
{"data":[{"{#MYSQLPORT}":"3306"}]}
5.创建自动发现配置文件
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# pwd
/etc/zabbix/zabbix_agentd.d
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# vim mysql_discovery.conf
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# cat mysql_discovery.conf
UserParameter=mysql.discovery,/bin/bash /server/scripts/mysql_discovery.sh
查看客户端配置zabbix_agentd.conf
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# grep "^[a-Z]" /etc/zabbix/zabbix_agentd.conf
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=127.0.0.1
ServerActive=127.0.0.1
Hostname=Zabbix server
Include=/etc/zabbix/zabbix_agentd.d/*.conf
6.重启zabbix-agent
systemctl restart zabbix-agent.service
7.zabbix_get测试取key
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# zabbix_get -s 127.0.0.1 -k mysql.discovery
{"data":[{"{#MYSQLPORT}":"3306"}]}
故障
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
{"data":[]}
原因是zabbix用户不能使用netstat的-p参数
解决方法为给netstat命令添加s权限
[root@m01 ~]# which netstat
/usr/bin/netstat
[root@m01 ~]# chmod u+s /usr/bin/netstat
8.web页面创建自动发现规则模版
9.模仿zabbix自带的mysql监控配置修改监控项
[root@m01 ~]# cat /etc/zabbix/zabbix_agentd.d/userparameter_mysql.conf
UserParameter=mysql.status[*],echo "show global status where Variable_name='$1';" | HOME=/var/lib/zabbix mysql -uroot -p123456 2>/dev/null -P $2 -N | awk '{print $$2}'
[root@m01 ~]# systemctl restart zabbix-agent.service
10.测试访问监控项
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# zabbix_get -s 127.0.0.1 -k mysql.status[Uptime,3306]
593253
11.web页面创建监控项原型
新建监控原型
12.web页面设置主机关联模版
13.查看是否已经自动添加成功
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# systemctl stop mysqld
[root@izwz9hcixm5361yy4uz40az zabbix_agentd.d]# systemctl start mysqld
由于本机sql服务端口为3306,zabbix客户端和服务端在同一台机器,mysql stop时,会发邮件通知,这是zabbix服务端已经关闭了,所以没有看到3306启动,这个需要多一台客户机或者建一个多实例验证。