最近开始学习python,发现这个语言跟linux 上的shell相比较来说还是有一定的可取之处,但是在一些命令格式和复杂程度还是有很多区别,时间的一个格式化在shell内相对简单,python内相对复杂。(个人的看法不喜欢勿喷)
下面放出一个监控mysql连接数的python脚本,欢迎各路神仙来指点下小弟,小弟自学python
脚本如下:
# coding=utf-8
import MySQLdb #数据库模块
import urllib,urllib2 #curl命令模块
import time #时间模块
def seller():
sumseller=[]
cnnseller=MySQLdb.connect("host","user","passwd","dbname",port)
cursor=cnnseller.cursor()
cursor.execute("select db,SUBSTRING_INDEX(host,':',1) as ip , count(*) from information_schema.processlist group by ip;")
#cursor.execute("select version()")
row=cursor.fetchall()
cnnseller.commit()
cnnseller.close()
for i in row:
sumseller.append(i[2])
#print i
sellerdb=sum(sumseller)
return sellerdb
def product():
sumproduct = []
cnnproduct = MySQLdb.connect("host","user","passwd","dbname",port)
cursor = cnnproduct.cursor()
cursor.execute("select db,SUBSTRING_INDEX(host,':',1) as ip , count(*) from information_schema.processlist group by ip;")
row = cursor.fetchall()
cnnproduct.commit()
cnnproduct.close()
for i in row:
sumproduct.append(i[2])
productdb = sum(sumproduct)
return productdb
def cms():
sumcms=[]
cnncms=MySQLdb.connect("host","user","passwd","dbname",port)
cursor=cnncms.cursor()
cursor.execute("select db,SUBSTRING_INDEX(host,':',1) as ip , count(*) from information_schema.processlist group by ip;")
row=cursor.fetchall()
cnncms.commit()
cnncms.close()
for i in row:
sumcms.append(i[2])
cmsdb=sum(sumcms)
return cmsdb
#将函数的值存储下来
sellerdbsum=seller()
productdbsum=product()
cmsdbsum=cms()
#定义时间 为可用常规时间 2016-10-12 %X是 分时秒
nowtime=time.strftime('%Y-%m-%d %X')
#将获取的函数值写入文件,在write()传递多个参数时候用+连接
fseller=open("db1.txt","a+")
fseller.write(str(nowtime)+"is"+str(sellerdbsum)+'\n')
fseller.close()
fproduct=open("db2.txt","a+")
fproduct.write(str(nowtime)+"is"+srt(productdbsum)+'\n')
fproduct.close()
fcms=open("db3.txt","a+")
fcms.write(str(nowtime)+"is"+str(cmsdbsum)+'\n')
fcms.close()
#判断连接数是否超标,超标发短信报警
if sellerdbsum > 1500:
parmas="报警信息%s"%sellerdbsum
f=urllib.urlopen("http://msmurl",parmas)
f.read()
elif productdbsum > 1500:
parmas="报警信息%s"%sellerdbsum
f=urllib.urlopen("http://msmurl",parmas)
f.read()
elif cmsdbsum > 720:
parmas="报警信息%s"%sellerdbsum
f=urllib.urlopen("http://msmurl",parmas)
f.read()
脚本写的不好欢迎各位指正