python写mysql脚本_使用python写一个监控mysql的脚本,在zabbix web上加上模板

使用python写一个监控mysql的脚本,在zabbix web上加上模板:

##先使用MySQLdb的接口关联数据库。

[root@cml python]# cat check_Mysql_custom.py

#!/usr/local/bin/python

'''author = chenmingle'''

'''Description:get mysql status'''

import os

import sys

try:

import MySQLdb as mysql

except Exception, e:

print e

print "pip install MySQL-python"

sys.exit(1)

con = mysql.connect(host='localhost',user='root',passwd='passwd',)

def processlist():

cur = con.cursor()

sql1 = 'show processlist'

a = str(cur.execute(sql1))

print a

def slave_status():

cur = con.cursor()

sql2 = cur.execute('show status like "%Slave_running%";')

status2 = str(cur.fetchall())

check2 = status2.split("'")[3]

if check2 == 'ON':

print 0

else:

print 1

def show_status(type):

cur = con.cursor()

b = cur.execute('show status like "%s";' %(type))

for i in cur.fetchall():

cat = str(i)

check = str(cat.split("'")[3])

print check

def main(type):

if type == 'processlist':

processlist()

elif type == 'slave_status':

slave_status()

else:

show_status(type)

if __name__ == '__main__':

try:

type = sys.argv[1]

except Exception, e:

print "Usage: python %s type" % sys.argv[0]

sys.exit(1)

main(type)

假如执行测试时报以下错误:

[root@cml python]# python check_Mysql_custom.py slave_status

Traceback (most recent call last):

File "test.py", line 14, in

con = mysql.connect(user='zabbix',passwd='',port=3306)

File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect

return Connection(*args, **kwargs)

File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__

super(Connection, self).__init__(*args, **kwargs2)

_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")

执行以下命令可以解决:

[root@cml python]# mkdir /var/lib/mysql

[root@cml python]# ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

##测试一下脚本:

[root@cml python]# python check_Mysql_custom.py processlist

3

[root@cml python]# python check_Mysql_custom.py Connections

55876

##测试显示所有在mysql中show status的都可以输出信息出来:

##写一个模板配置文件(自定义key值):

[root@cml zabbix_agentd.d]# cat Mysql_Custom.conf

UserParameter=mysql.Custom[*],/usr/local/bin/python /home/python/check_Mysql_custom.py $1

##在zabbix web界面上加入模板:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

##增加一个Appaliactions:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

##加入item值:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值