import re
import csv
import matplotlib.pyplot as plt
log_file_content = """
2024-01-01 12:00:00 User1 accessed from 192.168.1.1
2024-01-01 13:00:00 User2 accessed from 10.0.0.2
2024-01-01 14:00:00 User3 accessed from 192.168.1.3
2024-01-01 14:02:00 User4 accessed from 192.168.1.1
2024-01-01 14:10:00 User5 accessed from 192.168.1.1
2024-01-01 15:00:00 User6 accessed from 192.168.1.3
2024-01-01 15:05:00 User7 accessed from 192.168.1.1
2024-01-01 15:20:00 User8 accessed from 192.168.1.3
2024-01-01 15:30:00 User9 accessed from 192.168.1.5
2024-01-01 15:45:00 User10 accessed from 192.168.1.1
"""
#定义一个正则表达式来匹配IP地址
ip_pattern = r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b'
#使用re.findall找到所有匹配的IP地址
ip_addresses = re.findall(ip_pattern, log_file_content)
#定义一个函数来解析日志条目
def parse_log_entry(entry):
    #使用空格分割字符串
    parts = entry.split()
    # 获取IP地址
    ip = parts[-1]
    # 获取时间戳和用户名
    timestamp = ' '.join(parts[:3])
    user = parts[4]
    # 返回一个字典表示的日志信息
    return {
        'timestamp': timestamp,
        'user': user,
        'ip': ip
    }
#将日志内容分割成单独的条目
log_entries = log_file_content.strip().split('\n')
#解析每个日志条目并添加到结果列表中
parsed_logs = [parse_log_entry(entry) for entry in log_entries]
#初始化一个空字典来存储IP地址的访问次数
ip_access_counts = {}
#遍历解析后的日志信息
for log in parsed_logs:
    #如果IP地址已经在字典中，则增加计数
    if log['ip'] in ip_access_counts:
        ip_access_counts[log['ip']] += 1
    #否则，添加到字典中，初始计数为1
    else:
        ip_access_counts[log['ip']] = 1
# 对IP地址的访问次数进行降序排序
sorted_ip_access_counts = sorted(ip_access_counts.items(), key=lambda x: x[1], reverse=True)
#打印访问次数最多的IP地址
for ip, count in sorted_ip_access_counts:
    print(f"IP {ip} was accessed {count} time(s)")

#创建一个新的CSV文件并写入表头
with open('access_counts.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['IP Address', 'Access Count'])
    #写入每个IP地址的访问次数
    for ip, count in sorted_ip_access_counts:
        csvwriter.writerow([ip, count])
print("Access count data has been written to 'access_counts.csv'")

#只显示访问次数最多的前3个IP地址
top_3_ips = sorted_ip_access_counts[:3]
#创建条形图
plt.bar([ip[0] for ip in top_3_ips], [ip[1] for ip in top_3_ips])
plt.xlabel('IP Address')
plt.ylabel('Access Count')
plt.title('Top 3 Most Frequent IP Addresses')
plt.xticks(rotation=45)  # 旋转x轴标签以避免重叠
plt.show()
