python简单实现服务器信息自动邮件发送


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')



文件2

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)


4、jenkins配置很简单,增加一个job,配置上调度策略,然后执行这个python脚本即可


5、执行效果




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值