python-分析主机攻击日志,完成攻击态势图

接昨晚的服务器被攻击事项。

想利用黑客对我服务器的攻击完成攻击地理位置来源视图展现。
1、分析secure 日志,提取月份,日期,ip等信息

cat /var/log/secure |awk '{if($2 == 01)print  }' | awk '/Failed/{print $(NF-3)}' | sort | uniq -c | awk '{print $2" = "$1;}' | awk -F[=] '{if($2 > 100)print  }'

2、提取的数据存入数据库中。(现版本还无法实现增量)

由于python3不再支持MySQLdb
我这里选用了  PyMySQL

PyMySQL菜鸟教程
3、使用html进行页面展现。

  上1.0版本源码
# -*-coding:utf-8 -*-
# BY WANGCC

import re
from datetime import date
import pymysql

logfile = r'log.txt'
months = {
          'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,
          'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12
         }
t = date.today()
month = t.strftime('%b')
day = t.strftime('%d')
month_days = {}


def read_file(file_name):
    pat = re.compile(' (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) ')
    lines = []
    f = open(file_name, 'r')
    line = f.readline()
    while line:
        line = f.readline()
        try:
            if line.split()[0] == month and (int(day) - int(line.split()[1])) < 7 and (int(day) - int(line.split()[1])) >= 0:
                if re.search(pat,line):
                     lines.append(line)
            elif (months[month] - months[line.split()[0]]) == 1 or (months[month] - months[line.split()[0]]) == -11:
                if (int(day) + month_days[line.split()[0]] - int(line.split()[1])) < 7 and re.search(pat,line):
                    lines.append(line)
        except IndexError:
            pass
    for line in lines:
        ip = re.findall(pat,line)[0]
        mysql(month, day, ip)
    label = f.tell()  # 获得当前文件句柄
    f.close()

    return month,day,ip



def mysql(month,day,ip):

    # 打开数据库连接
    db = pymysql.connect("127.0.0.1", "root", "tZQowE6p5#)t", "monitor", charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # SQL 插入语句
    #sql ="UPDATE monitor SET ip='20.20.20.20' WHERE id = '1'"   #update
    print((day))
    sql="insert into monitor(ip,month,day)value ('%s','%s','%s')"%(ip,month,day)
    try:
        print('try')
        # 执行sql语句
        print(ip,month,day)
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
        print('try--end')
    except Exception as e:
        print(e,'发生错误时回滚')
        # 发生错误时回滚
        db.rollback()
    # 关闭数据库连接
    db.close()

if __name__ == '__main__':
    month,day,ip = read_file(logfile)

这个是根据ip查询所属地理位置。

# -*-coding:utf-8 -*-
# BY WANGCC
import requests
import IPy


def get_location(ip):
    url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?co=&resource_id=6006&t=1529895387942&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110203920624944751099_1529894588086&_=1529894588088&query=%s' % ip
    # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}
    r = requests.get(url)
    r.encoding = r.apparent_encoding
    html = r.text
    c1 = html.split('location":"')[1]
    c2 = c1.split('","')[0]
    return c2


def check_ip(ip):
    try:
        IPy.IP(ip)
        return True
    except Exception as e:
        print(e)
        return False


def ip_bae(ip):
    if check_ip(ip):
        return (get_location(ip))


if __name__ == '__main__':
    ip = '114.114.114.114'
    print(ip_bae(ip))

这里有几点需要记录:
1、很长一段时间里,提取出来的ip只有1个,这是因为列表里把数据都放在了一行里。
2、在按行读取文件时,如果是个空行,程序会报错,需要加try、except 就可以避免这个问题。
3、现在在读取文件时,不能控制读取时间和增量查询。
4、re模块需要重新学一下,其实是个简单的东西,但是今天差不多是捉摸了一下午。

实际因素,代码写的少。

    原文作者:wangcc_sd
    原文地址: https://www.jianshu.com/p/4258d82722cd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞