python实现端口扫描监控,宕机则发送邮件

Posted 年岁有加,并非垂老

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现端口扫描监控,宕机则发送邮件相关的知识,希望对你有一定的参考价值。

 

 

import socket

def get_ip_status(ip,port):
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        server.connect((ip,port))
        print({0} port {1} is open.format(ip,port))
    except Exception as err:
        print({0} port {1} is down.format(ip,port))
        send_mail(ip,port)//宕机就发送邮件
    finally:
        server.close()
        
def send_mail(ip,port):
    fromAddr = "*********@126.com"
    toAddr = "*********@126.com"
    password = "************"
    smtp_server = "smtp.126.com"
    import smtplib
    from email.mime.text import MIMEText
    msg = MIMEText("Test body")  //处理邮件文本内容
    msg[Subject] = "the {0}:{1} is down".format(ip,port)
    //msg[‘Subject‘] = ‘%s %d is down!!!‘ %(ip,port)
    server = smtplib.SMTP(smtp_server,25)
    server.login(fromAddr,password)
    server.sendmail(fromAddr,toAddr,msg.as_string())
    
‘‘‘
if __name__ == __main__:
    host = 172.16.60.223
    port = [9000,9001,9002,9003,9008,9009]
    for p in port:
        get_ip_status(host,p)
        ‘‘‘
//多个ip不同端口扫描
if __name__ == __main__:
    host_port = {172.16.60.223:[9000,9001,9002,9003,9008,9009],172.16.60.40:[8003,8004,8005,8007,8011]}
    for h,p in host_port.items():
        for p in p:
            get_ip_status(h,p)

 

以上是关于python实现端口扫描监控,宕机则发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

zabbix实现邮件报警

Python3 实现简易ping监控并发送报警邮件

python实现自动监控网站并发送邮件告警

python发送邮件

Zabbix邮件告警

Python网络开发基础,实现udp聊天器小案例