#-*- encoding:utf-8 -*-
#!/usr/bin/env python # name IsOpen.py import os import socket import time import smtplib from email.mime.text import MIMEText mailto_list=["rootliu@****.com"] mail_host="smtp.****.com" #设置服务器 mail_user="rootliu@****.com" #用户名 mail_pass="******" #口令 mail_postfix="****.com" #发件箱的后缀 def send_mail(mailto_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容 me="VPN Server is down"+"<"+mail_user+"@"+mail_postfix+">" #这里的hello可以任意设置,收到信后,将按照设置显示 msg = MIMEText(content,_subtype='html',_charset='gb2312') #创建一个实例,这里设置为html格式邮件 msg['Subject'] = sub #设置主题 msg['From'] = me msg['To'] = ";".join(mailto_list) try: s = smtplib.SMTP() s.connect(mail_host) #连接smtp服务器 s.login(mail_user,mail_pass) #登陆服务器 s.sendmail(me, mailto_list, msg.as_string()) #发送邮件 s.close() return True except Exception as e: print str(e) return False def IsOpen(ip,port,flag): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((ip,int(port))) s.shutdown(2) print ('%d is open'% port) return True except: print ('%d is down' % port) return False if __name__ == '__main__': while(1>0): flag=1 IsOpen('127.0.0.1',80,flag) time.sleep(5) flag=IsOpen('127.0.0.1',80,flag) print (flag) if flag==False: send_mail(mailto_list,"VPN Server is down","error") time.sleep(5)