python3 port monitoring

I used to use shell combined with nmap for port monitoring. Recently, I just had time to rewrite it with python.

Monitoring effect:

image.png

The mysql database is used to read the IP address, output IP detailed information, record the failure time, and send to record whether a variable has occurred.

image.png

# -*- coding: utf-8 -*-
# @Time : 2020-4-10 22:13
# @Author : yejunhai
# @Site :
# @File : port_monitor.py
# @Software: PyCharm


import pymysql
import socket
import sys
import time
import requests
import json


def msg(text) :
    #Send to corporate WeChat robot
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    api_url = "" # This is the webhook address generated by the enterprise WeChat robot, just change it to yours.
    json_text = {
        "msgtype" : "text",
        "text" : {
            "content" : text
        },
    }
    requests.post(api_url, json.dumps(json_text), headers=headers).content

def port_check(ip,port):
    #Check socket return value
    s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    result=s.connect_ex((ip,int(port)))
    return result

def out_log(text):
    #Run write log. . . . . . .
    with open(f'{sys.argv[0].split(".")[0]}.log','a') as f:
        print(text,file=f)


def down_time(ip):
    #Calculate the failure time, mysql can also be calculated, not--!
    cursor.execute(f"SELECT mzt.start_time,mzt.end_time FROM mzt WHERE mzt.ip = '{ip}'")
    total_time = cursor.fetchone()
    try:
        start_time = total_time[0]
        end_time =total_time[1]
        duration = end_time-start_time
        return f "\ nStart time of this fault {start_time} \ nEnd time of this fault {end_time} \ nDuration time of this fault {duration}"
    except:
        return "\ nThe failure start time is not recorded"

#Time format
cur_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

# Open database connection
db = pymysql.connect("127.0.0.1",user = "root",passwd = "root",db = "zwy")
# Use the cursor () method to create a cursor object
cursor = db.cursor()
# SQL query statement
sql = "SELECT mzt.ip, mzt.port1, mzt.port2, mzt.send, mzt.` 部署 FROM` FROM mzt "
# try:

cursor.execute(sql)
results = cursor.fetchall()
#Obtain IP and port and start doing things
for row in results:
    ip=row[0]
    port1=row[1]
    port2=row[2]
    send=row[3]
    description=row[4]
    #Check multiple ports
    for port in port1,port2:
        if port != '' and port != None:
            port_status=port_check(ip,port)
            if port_status != 0 and send == 0:
                cursor.execute (f "UPDATE mzt SET send = '1' WHERE mzt.ip = '{ip}'") #Update after an alarm occurs to prevent constant alarm
                cursor.execute (f "UPDATE mzt SET start_time = '{cur_time}' WHERE mzt.ip = '{ip}'") #Record failure time
                db.commit()
                msg (f "{cur_time} {description} {ip}: {port} The port is closed, please check!") #Send alarm
                out_log (f "{cur_time} {ip}: {port} check {port_status} send: {send}") #write log
            elif port_status == 0 and send == 1:
                cursor.execute(f"UPDATE mzt SET send = '0' WHERE mzt.ip = '{ip}'")
                cursor.execute(f"UPDATE mzt SET end_time = '{cur_time}' WHERE mzt.ip = '{ip}'")
                db.commit()
                msg (f "{cur_time} {description} {ip}: {port} Port recovery. {down_time (ip)}")
                out_log(f"{cur_time} {ip}:{port} check {port_status} send: {send}")
            else:
                out_log(f"{cur_time} {ip}:{port} check {port_status} send: {send}")
# except:
#     print("Error: unable to fetch data")
#Close the database
db.close()

#Old traditional crontab run regularly

*/1 * * * * /usr/bin/python3 /root/port_monitor.py

Guess you like

Origin blog.51cto.com/junhai/2487499