Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have a problem with my code and here is my code: log _ analyzer.py import re from datetime import datetime import csv import pytz

I have a problem with my code and here is my code:
log_analyzer.py
import re
from datetime import datetime
import csv
import pytz
class LogEntry:
def __init__(self, event_time, internal_ip, port_number, protocol, action, rule_id, source_ip, country, country_name):
self.event_time = datetime.strptime(event_time, '%Y-%m-%d %H:%M:%S %Z').replace(tzinfo=pytz.UTC)
self.internal_ip = internal_ip
self.port_number = port_number
self.protocol = protocol
self.action = action
self.rule_id = rule_id
self.source_ip = source_ip
self.country = country
self.country_name = country_name
@property
def ipv4_class(self):
first_octet = int(self.source_ip.split('.')[0])
if 1= first_octet =126:
return 'A'
elif 128= first_octet =191:
return 'B'
elif 192= first_octet =223:
return 'C'
elif 224= first_octet =239:
return 'D'
else:
return 'Unknown'
@staticmethod
def country_count(log_entries, country_code):
filtered_enteries =[entry for entry in log_entries if entry.country.lower()== country_code.lower()]
print(f"{len(filtered_enteries)} log entries from the {country_code.upper()} were recorded.")
return filtered_enteries
@staticmethod
def parse(log_entries, month):
filtered_entries =[entry for entry in log_entries if entry.event_time.month == month]
print(f"{len(filtered_entries)} log entries were recorded in month {month}.")
return filtered_entries
index.py
from log_analyzer import LogEntry
import argparse
import csv
import pytz
def parse_args():
parser = argparse.ArgumentParser(description="Accept a CSV file of firewall log data and prepare it for analysis")
parser.add_argument("--filename", "-f", required=True, help="Filename")
parser.add_argument("--action", "-a", required=True, help="Execute an action on the CSV file (valid values are 'head', 'deny', 'source', and 'parse')")
parser.add_argument("--country-code", "-c", help="2-letter country code for 'source' action")
parser.add_argument("--month", "-m", type=int, help="Month for the 'parse' action")
return parser.parse_args()
def print_head(log_entries):
for log_entry in log_entries[:5]:
print(log_entry.__dict__)
def deny_count(log_entries):
denied_entries =[entry for entry in log_entries if entry.action == "Deny"]
print(f"Number of denied entries: {len(denied_entries)}")
def main():
args = parse_args()
filename = args.filename
log_entries =[]
filename = "firewall_logs_sample.csv"
with open(filename,'r', encoding="utf8") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
log_entry = LogEntry(row['event_time'], row['internal_ip'], row['port_number'], row['protocol'], row['action'], row['rule_id'], row['source_ip'], row['country'], row['country_name'])
log_entries.append(log_entry)
if args.action == "head":
print_head(log_entries)
elif args.action == "deny":
deny_count(log_entries)
elif args.action == 'source' and args.country:
country_count = LogEntry.country_count(log_entries, args.country)
elif args.action == "parse":
if args.month and 1= args.month =12:
filtered_entries = LogEntry.parse(log_entries, args.month)
# Export filtered entries to CSV file
if filtered_entries:
output_filename = f"{args.filename.split('.')[0]}_{args.month}_logs.csv"
with open(output_filename, mode='w', newline='') as csvfile:
fieldnames = log_entries[0].__dict__.keys()
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for entry in filtered_entries:
writer.writerow(entry.__dict__)
print(f"Filtered log entries exported to {output_filename}")
else:
print("Invalid month provided. Month must be an integer between 1 and 12.")
if __name__=="__main__":
main()
this is the error i got from the output:
C:\Users\akinn\OneDrive - Indiana University (1)\CIT30900\Firewall Log Analyzer v.1-2>python index.py --filename firewall_logs_2022.csv --action head
{'event_time': datetime.datetime(2022,1,1,0,18,38, tzinfo=), 'internal_ip': '10.248.203.131', 'port_number': '20', 'protocol': 'FTP - Data', 'action': 'Allow', 'rule_id': '186', 'source_ip': '216.57.223.121', 'country': 'US', 'country_name': 'United States'}
C:\Users\akinn\OneDrive - Indiana University (1)\CIT30900\Firewall Log Analyzer v.1-2>python index.py --filename firewall_logs_2022.csv --action deny
Number of denied entries: 12
C:\Users\akinn\OneDrive - Indiana University (1)\CIT30900\Fi
And this is what the output is supposed to look like:
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Learning MySQL Get A Handle On Your Data

Authors: Seyed M M Tahaghoghi

1st Edition

0596529465, 9780596529468

More Books

Students also viewed these Databases questions

Question

1. How is the newspaper help to our daily life?

Answered: 1 week ago

Question

1. Prepare a short profile of Mikhail Zoshchenko ?

Answered: 1 week ago

Question

What is psychology disorder?

Answered: 1 week ago