Как я могу выполнить скрипт Python файла журнала 1 ТБ в командной строке - PullRequest
0 голосов
/ 01 июня 2018

У меня есть файл журнала, который состоит из 1 ТБ.Я не уверен, что, как запустить этот скрипт 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 голосов
/ 01 июня 2018

Попробуйте, это работает хорошо, и если проблема не устранена, проверьте регулярное выражение поиска:

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() )
...