在日志文件中,如何检测端口是否危险?

时间:2017-09-07 13:08:16

标签: python log-analysis

我知道基本的python,我有一个日志文件,我也打印了日志文件中的端口输出,输出中有很多端口。

我想知道如何只从打印端口中取出危险的端口

  • 此外,我还需要从危险端口获取IP地址
  • 最后如何知道IP地址是本地IP还是全局IP
import os
from collections import Counter
asc_order = []
def openfile(filename):
    if os.path.exists(filename):
        return open(filename, "r").read()
    else:
        return None
def parselog(logline):
    c = logline.split(" ")
    r = {}
    i = -1
    for var in c:
        i += 1
        if i == 1:
            a = var.split("\t")
            for el in a:
                if el.startswith("date="): r["date"] = el.split("=")[1]
        elif i > 1:
            v = var.split("=", 1)
            try:
                r[v[0]] = v[1].strip("\"")
            except:
                pass
    return r
def splitline(logall):
    c = logall.split("\n")
    r = []
    for el in c:
        r.append(el.strip("\r"))
    return r
def main():
    f = openfile("/Users/angelin/Desktop/new sec/2017-04-18_010.082.012.003.txt")
    if f is None:
        print("File not found")
        return
    s = splitline(f)
    counts = {}
    for el in s:
        if len(el) > 50:
            p = parselog(el)
            if "dstport" in p:
                # increment counter
                if p["dstport"] in counts:
                    counts[str(p["dstport"])] += 1
                else:
                    counts[str(p["dstport"])] = 1
                asc_order.append(p["dstport"])
    ascending = map(int, asc_order)
    ascending.sort()
    for port in ascending:
        print ("Dest Port : %d" % port)
    print ""
    k = map(int, counts.keys())
    k.sort()
    sorted(k, key=counts.get)    
    y = sorted(counts.items(), key=lambda x: x[1], reverse=True)
    for x, z in y:
        print  ('Dest Port %s Count: %s' % (x, z))


if __name__ == "__main__": main()

这是日志文件样本

2017-04-17 00:00:00 Local7.Info 10.82.12.3  
date=2017-04-16 
time=23:59:59 
devname=IDS-DC14-001 
devid=FGT90D3Z15018997 
logid=1059028704 
type=utm 
subtype=app-ctrl 
eventtype=app-ctrl-all 
level=information 
vd=root 
appid=27946 
user="" 
srcip=10.80.10.249 
srcport=9170 
srcintf="wan1" 
dstip=208.91.112.198 
dstport=53 
dstintf="wan1" 
profiletype="applist" 
proto=17 service="DNS" 
policyid=3 
sessionid=39717767 
applist="sniffer-profile" 
appcat="Cloud.IT" 
app="Fortiguard.Search" 
action=pass 
msg="Cloud.IT: Fortiguard.Search," 
apprisk=medium

1 个答案:

答案 0 :(得分:0)

你在这里问了很多事情,总的来说你想要实现的是模糊的,所以我只能给你一些一般的答案:

  1. 您需要找到定义一次迭代的日志模式。
  2. 例如,如果每次迭代都以

    开头

    2017-04-17 00:00:00 Local7.Info 10.82.12.3

    apprisk=medium

    结尾

    然后你需要隔离它们并将整个日志分成这样的块

    1. 使用正则表达式帮助您准确匹配字符串

    2. 定义危险端口:

    3. dangerousPorts = [80,8080,27015] # etc

      1. ,最后检查:

        if port in dangerousPorts: warnSomeone()