# Mysql自动发现

vim /usr/local/zabbix/scripts/discovery_mysql.py

```python

# -*- coding: utf-8 -*-

try:

import json

except:

import simplejson as json

import commands

(status, output) = commands.getstatusoutput("""sudo netstat -tlnp| grep mysqld |awk '{print $4}'|awk -F':' '{print $(NF)}'|sort -u""")

outputs = output.split('\n')

result = []

for one in outputs:

result.append( {'{#ONE}': one} )

print( json.dumps({'data':result},sort_keys=True,indent=4) )

```

Zabbix添加Sudo权限

```shell

zabbix ALL= NOPASSWD: /bin/netstat

Defaults:zabbix !requiretty

```

Zabbix自定义Key配置

```shell

UserParameter=mysql.discovery,python /usr/local/zabbix/discovery_mysql.py

```

重启Agent

# 监控Mysql主从同步

主从监控权限用户的创建

```shell

7. grant usage,replication client on . to 'monitor'@'127.0.0.1' identified by 'shijiangepwd';

8. flush privileges;

```

监控Mysql主从的Shell脚本check_mysql_slave.sh

```shell

port=$1

key=$2

mysql -umonitor -pshijiangepwd -h 127.0.0.1 -P${port} -e "show slave status\G"|grep "${key}\:"|awk '{print $2}' 2>/dev/null

```

Zabbix自定义Key监控Mysql主从

```shell

10. UserParameter=mysql.slave.status[*],sh check_mysql_slave.sh $1 $2 2>/dev/null

11. 重启Agent

```