服务器A需要调用服务器B上面的服务,但是经常遇到连接超时的问题,需要监控一下网络状态:
shell脚本:
#!/bin/sh
PYTHON_PATH=/usr/bin
ping -c 5 www.suiyuan521.com
if [ "$?" != "0" ]; then
$PYTHON_PATH/python send_email.py "I can not connect to abc.com"
fi
python发送邮件脚本:
# !/usr/bin/python
"""just a send email python script"""
#-*- coding: utf8 -*-
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Header import Header
from email.MIMEImage import MIMEImage
import smtplib
import sys
import datetime
import mimetypes
import os
"""send_email function"""
def send_email(subject, body):
sender = 'suiyuan@521.com'
file_name = './abc.txt'
msgRoot = MIMEMultipart()
msgRoot["Accept-Charset"] = "UTF-8"
msgRoot["Accept-Language"] = "zh-CN"
msgRoot['Subject'] = Header(subject,"UTF-8")
msgRoot['From'] = sender
receivers = ['suiyuan521@love.com']
msgRoot['To'] = ','.join(receivers)
msgRoot.preamble = '%s is a MIME message' % (subject)
msgAlternative = MIMEMultipart("alternative")
msgRoot.attach(msgAlternative)
if not body:
body = "随缘吧APP不错,给你带来缘分"
msgText = MIMEText(body)
msgText.set_charset("UTF-8")
msgText = MIMEText(body, 'html', 'UTF-8')
msgText.set_charset("UTF-8")
msgAlternative.attach(msgText)
// 发送附件
ctype,encoding = mimetypes.guess_type(file_name)
if ctype is None or encoding is not None:
ctype='application/octet-stream'
maintype,subtype = ctype.split('/',1)
file_msg=MIMEImage(open(file_name,'rb').read(),subtype)
basename = os.path.basename(file_name)
file_msg.add_header('Content-Disposition','attachment', filename = basename)
msgAlternative.attach(file_msg)
s = smtplib.SMTP('proxy-in.suiyuan.com') // 设置邮件服务器地址
s.sendmail(sender, receivers, msgRoot.as_string())
s.quit()
"""main function"""
if __name__ == '__main__':
body = sys.argv[1]
now_time = datetime.datetime.now()
yes_time = now_time + datetime.timedelta(days=-1)
yes_time_nyr = yes_time.strftime('%Y-%m-%d')
subject = "随缘吧助您监控网络状态"
send_email(subject,body)
然后将shell脚本加入crontab定时任务就可以了。
*/10 * * * * cd /home/suiyuan/app/monitor; sh monitorNet.sh