Skip to main content

Extract IP Address from Logs

Sample Log File

Save the logs in a file named sample_log.txt.

2023-10-22 12:01:23 INFO User 'admin' logged in from 192.168.1.5
2023-10-22 12:05:45 WARNING Unauthorized access attempt from 10.0.0.2
2023-10-22 12:07:30 INFO User 'john_doe' logged in from 192.168.1.7
2023-10-22 12:09:15 ERROR Connection timeout from 203.0.113.5
2023-10-22 12:10:00 INFO User 'alice' logged in from 192.168.1.9
2023-10-22 12:12:12 WARNING Unauthorized access attempt from 10.0.0.3

Python Code

Save the code in a file named extract_ips.py.

extract_ips.py
import re

# Define a function to extract IP addresses from a log file
def extract_ips_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 IP addresses in the log data
ip_addresses = re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', log_data)

# Return the list of extracted IP addresses
return ip_addresses

# Call the function and print the extracted IP addresses
ips = extract_ips_from_log('sample_log.txt')
print("Extracted IP Addresses:")
for ip in ips:
print(ip)

Run the Python script using the command: python extract_ips.py.

This will display the extracted IP addresses from the sample log file.