如何在命令行中执行1TB日志文件python脚本

时间:2018-06-01 01:54:18

标签: python sys

我有一个日志文件,其容量为1TB。我不确定如何在命令行中运行此python脚本。我使用sys库但仍未添加我的csv数据。

下面是我的python代码。

import re
import sys
from csv import writer
import datetime
log_file = '/Users/kiya/Desktop/mysql/ipscan/ip.txt'
output_file = '/Users/kiya/Desktop/mysql/ipscan/output.csv'

try:
    ip_file =sys.argv[1]
except Exception:
    print("usage: pythone3 {} [ip file]".format(sys.argv[0]))
    sys.exit()

name_to_check = 'MBX_AUTHENTICATION_FAILED'

with open(log_file,encoding="utf-8") as infile:
    for line in infile:
        if name_to_check in line:
            username = re.search(r'(?<=userName=)(.*)(?=,)', line)
            username = username.group()

            ip = re.search(r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',line)
            ip = ip.group()

            with open(output_file, 'a') as outfile:
                outfile.write('{username},{ip}\n'.format(username=username, ip=ip))

1 个答案:

答案 0 :(得分:0)

尝试此功能,如果问题仍然存在,请检查您的搜索正则表达式:

from sys import argv

log_file = ""
if len(argv) > 0 :
    log_file = argv[1]
else :
    quit("No log_file specified, exiting script.")

with open(log_file, encoding="utf-8") as infile:
    for line in infile:
        if name_to_check in line:

            username = re.search(r'(?<=userName=)(.*)(?=,)', line)
            username = username.group()

            date = re.search(r'(?P<date>\d{8})\s+(?P<time>\d{9})\+(?P<zone>\d{4})', line)
            date = datetime.datetime.strptime(date.group('date'), "%Y%m%d").strftime("%Y-%m-%d")
            print(date)

            time = re.search(r'(?P<date>\d{8})\s+(?P<time>\d{9})\+(?P<zone>\d{4})', line)
            time = datetime.datetime.strptime(time.group('time'), "%H%M%S%f").strftime("%H:%M:%S")
            print(time)

            ip = re.search(r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',line)

            with open(output_file, "ab", buffering=0) as outfile:
                outfile.write( ("{},{},{},{}\n".format(username, date, time, ip)).encode() )