#!/usr/bin/env python import sys, os, time from datetime import datetime, timedelta, date, time as dt_time import socket hostname = socket.gethostname() fileList = "./List.ip" date = datetime.now() - timedelta(minutes=10) date = date.strftime('%H:%M:%S') from commands import * import smtplib def mail(message): smtp_server = "localhost" smtp_port = 25 smtp_user= "root@%s" % hostname subject = 'Ahtung!! Security SSH audit alert' to = "mail@example.ru" mail_lib = smtplib.SMTP(smtp_server, smtp_port) msg = 'From: %s\r\nTo: %s\r\nContent-Type: text/html; charset="utf-8"\r\nSubject: %s\r\n Return-Path: <root@%s>\r\n\r\n' % (smtp_user, to, subject, hostname) msg += message mail_lib.sendmail(smtp_user, to, msg) listLog = getoutput('''cat /var/log/secure |grep "Accepted password for" | awk '{if($3>="'''+date+'''"){print $3 " " $9 " " $11 }}' ''') if listLog: for line in listLog.split('\n'): matchIp = 0 matchName = 0 curIp = line.split()[2] for lineLs in open(fileList): if len(lineLs.strip()) == 0 or lineLs[0] == "#" or lineLs[0] == " ": continue if line.split()[1] == lineLs.split()[0]: matchName = 1 listIp = lineLs.split()[1] i = 0 for c in listIp.strip().split("."): if c.strip() == "0": break i = i + 1 if listIp.strip().split(".")[0:i] == curIp.split(".")[0:i]: matchIp = 1 if not matchIp: if not matchName: print("This user %s not found !!!" % line.split()[1]) message = "This user %s not found !!!" % line.split()[1] mail(message) else: print("Ahtung! User {0} logged from unknown IP {1} in time {2}").format(line.split()[1], line.split()[2], line.split()[0]) message = "Ahtung! User "+line.split()[1]+" logged from unknown IP "+line.split()[2]+" in time "+line.split()[0] mail(message)
#Vasya vasya 1.2.3.4 vasya 12.13.14.0
Source: https://habr.com/ru/post/361863/
All Articles