python程序—利用socket监控端口

时间:2020-12-16 22:43:35

利用socket监控服务器端口,端口不通时,发邮件提醒

import yagmail #导入yagmail模块
import re #导入re模块,进行正则匹配
import socket #导入socket模块 def sendmail(subject,contents):
#连接邮箱服务器
yag = yagmail.SMTP(user='发件人邮箱',password='授权密码',host='smtp.163.com')
#发送邮件
yag.send(to='收件人邮箱',subject=subject, contents=contents)
#断开连接
yag.close() hosts = ['1.1.1.1:90','2.2.2.2:8080','127.0.0.1:80','3.3.3.3:50','192.168.1.1:9090'] #监测的服务器IP和端口 for host in hosts:
ip = re.compile('(.*?):(.*)').search(host).group() #正则匹配,过滤出IP
port = re.compile('(.*?):(.*)').search(host).group() #正则匹配,过滤出端口号
server = socket.socket()#tcp协议
server.settimeout()#设置超时时间
res = server.connect_ex((ip,int(port))) #res == 0代表端口号启用|res != 0代表端口号没启用 if res != :
subject='端口监测结果'
contents='%s---%s:不通' % (ip, port)
sendmail(subject,contents)