Port Numbers Extraction from Logs
Sample Log File
Save the logs in a file named sample_port_log.txt
.
2023-10-22 12:01:23 INFO Connection established on port 22 from IP 192.168.1.5.
2023-10-22 12:05:45 WARNING Unauthorized access attempt on port 80 from 10.0.0.2.
2023-10-22 12:07:30 INFO Connection established on port 443 from IP 192.168.1.7.
2023-10-22 12:09:15 ERROR Connection timeout on port 3389 from 203.0.113.5.
2023-10-22 12:10:00 INFO Connection established on port 21 from IP 192.168.1.9.
2023-10-22 12:12:12 WARNING Unauthorized access attempt on port 23 from 10.0.0.3.
Python Code
Save the code in a file named extract_ports.py
.
extract_ports.py
import re
# Define a function to extract port numbers from a log file
def extract_ports_from_log(log_file_path):
# Open the log file and read its content
with open(log_file_path, 'r') as file:
log_data = file.read()
# Use a regular expression to find all port numbers in the log data
ports = re.findall(r'\b\d{1,5}\b', log_data) # Extract numbers between 0 and 65535
valid_ports = [port for port in ports if 0 <= int(port) <= 65535]
# Return the list of extracted port numbers
return valid_ports
# Call the function and print the extracted port numbers
ports = extract_ports_from_log('sample_ports_log.txt')
print("Extracted Port Numbers:")
for port in ports:
print(port)