Question: i keep having this error in my code here's my code: import re import datetime from csv import DictReader, DictWriter class LogEntry: def _ _

i keep having this error in my code here's my code:
import re
import datetime
from csv import DictReader, DictWriter
class LogEntry:
def __init__(self, event_time, internal_ip, port_number, protocol, action, rule_id, source_ip, country, country_name):
self.event_time = LogEntry.parse_datetime(event_time)
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
@staticmethod
def _parse_datetime(timestamp):
try:
return datetime.datetime.strptime(timestamp,"%Y-%m-%d %H:%M:%S %Z")
except ValueError:
raise ValueError("Invalid timestamp format")
@property
def ipv4_class(self):
octets = self.source_ip.split(".")
if len(octets)!=4:
return None
octet_value = int(octets[0])
if 0= octet_value =127:
return "A"
elif 128= octet_value =191:
return "B"
elif 192= octet_value =223:
return "C"
else:
return None
@staticmethod
def country_count(log_entries, country_code):
filtered_enteries =[entry for entry in log_entries if entry.country.lower()== country_code.lower()]
count = len(filtered_enteries)
print(f"Number of entries from {country_code.upper()}: {count}")
@staticmethod
def parse(log_entries, args, month):
filtered_entries =[entry for entry in log_entries if entry.event_time.month == month]
if filtered_entries:
output_filename = f"{args.filename.split('.')[0]}_{args.month}_logs.csv"
try:
with open(output_filename, mode='w', newline='') as csvfile:
fieldnames = log_entries[0].__dict__.keys()
writer = DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for entry in filtered_entries:
writer.writerow(entry.__dict__)
print(f"Filtered log entries exported to {output_filename}")
except FileNotFoundError:
print(f"Error: File '{output_filename}' not found.")
except PermissionError:
print(f"Error: Insufficient permissions to write to '{output_filename}'.")
else:
print("No entries found for the given month.")
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):
if len(log_entries)>5:
print("First 5 entries:")
for i in range(5):
print(f"{log_entries[i]}")
else:
print("All entries:")
for entry in log_entries:
print(entry)
def deny_count(log_entries):
denied_entries =[entry for entry in log_entries if entry.action == "Deny"]
count = len(denied_entries)
print(f"Number of denied entries: {count}")
def main():
args = parse_args()
filename = args.filename
log_entries =[]
filename = "firewall_logs_sample.csv"
with open(filename,'r', newline='') 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)
for log_entry in log_entries[:5]:
timezone = pytz.timezone('UTC')
formatted_time = log_entry.event_time.astimezone(timezone).strftime('%Y-%m-%d %H:%M:%S%z')
print(f"{formatted_time},{log_entry.action},{log_entry.source_ip},{log_entry.ipv4_class},{log_entry.country_name}")
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)
and here's the error i keep having:
 i keep having this error in my code here's my code:

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!