1、背景
As a tester,维护着测试环境10+台服务器,每台服务器上部署着若干个web应用,经常会出现服务器的一些OOM,磁盘占用100%,虽然有定期的一些脚本做清理,但是依然会经常出现一些状况,加之想用些小脚本解决些问题,于是就开始整。
2、思路
脚本语言: 比较熟悉python,也挺喜欢python,那就python搞吧。
大致过程: 在一台服务器上(且叫他master),执行python脚本,去获取每台其他测试服务器(叫他们slaves)的磁盘信息,内存信息,然后将执行结果邮件发送到我的邮箱,再通过jenkins进行一些自动化调度,于是乎~不用登陆到服务器,也能知道每台服务器的信息了!
3、实现代码
两个脚本,一个去获取服务器的信息,另一个专门负责发邮件。
execCommandBatch.py 故名思议,批量在服务器上执行某个命令
#coding:utf-8
import subprocess
import re
import time
def execCommandForServers(ip,command):
sshLogin="ssh root@"+ip
sshCommand=sshLogin+''' "'''+command+'''"'''
res=subprocess.Popen(sshCommand,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#执行完命令,然后就是解析结果
commandOut=res.stdout.readlines()
return commandOut
#这里command 设置成参数,如果需要执行其他的命令,也方便扩展。
def getResult(command):
res=""
ipList=[\
'192.168.8.1','192.168.8.7',\
'192.168.8.2','192.168.8.8',\
'192.168.8.3','192.168.8.9',\
'192.168.8.4','192.168.8.10',\
'192.168.8.5','192.168.8.11',\
'192.168.8.6','192.168.8.12',\
]
for ip in ipList:
res+='\n'
res+="["+ip+"]"
execRes=execCommandForServers(ip,command)
for line in execRes:
res+=line
return res
#print getResult('df -h')
mail-memInfo.py
#coding:utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os
import execCommandBatch as mymodle
import time
#创建一个带附件的实例
'''
msg = MIMEMultipart()
res=os.listdir(os.getcwd())
for i in range(0,len(res)):
if res[i].endswith('zip'):
att1 = MIMEText(open(res[i], 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename='+res[i]
msg.attach(att1)
'''
currentTime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
mailText=mymodle.getResult('df -h')
msg=MIMEText(mailText,'plain','utf-8')
#加邮件头
msg['to'] = '收件地址'
msg['from'] = '发件地址'
msg['subject'] = '测试环境服务器-磁盘信息-'+currentTime
#发送邮件
try:
server = smtplib.SMTP()
server.connect('smtp.qq.com')
server.login('发件地址','发件邮箱的密码')#XXX为用户名,XXXXX为密码
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e)
5、执行效果