Welcome to ZiTechurity, your trusted source for cutting-edge cybersecurity insights and practical tools. In today’s fast-evolving threat landscape, security analysts need to be equipped with efficient, customizable tools that can help them quickly analyze logs, detect Indicators of Compromise (IOCs), and scan networks.
Python, with its simplicity and rich ecosystem, is a prime language for building such tools. In this post, we’ll share 5 essential Python scripts every security analyst should have in their arsenal to make daily security tasks easier and more effective.
1. Log File Parser and Analyzer
Logs are the backbone of threat detection. This script parses common log formats, filters suspicious events, and generates simple summaries.
python
import re
# Customize this regex to match your log format
log_pattern = re.compile(r'(\S+) - - \[(.*?)\] "(\S+) (.*?) HTTP/\d\.\d" (\d{3})')
def analyze_logs(logfile):
status_codes = {}
with open(logfile, 'r') as f:
for line in f:
match = log_pattern.match(line)
if match:
ip, timestamp, method, url, status = match.groups()
status_codes[status] = status_codes.get(status, 0) + 1
print("HTTP Status Code Summary:")
for status, count in status_codes.items():
print(f"Status {status}: {count} times")
if __name__ == "__main__":
analyze_logs('access.log')
Use Case: Quickly identify unusual spikes in HTTP status codes like 500 errors or 403 denied requests when analyzing web server logs.
2. IOC (Indicator of Compromise) Checker
A simple script to scan files or directories for known IOCs such as suspicious IPs, domain names, or file hashes.
python
import os
# Sample IOC list (expand as needed)
iocs = {
'ips': ['192.168.1.100', '10.0.0.5'],
'domains': ['malicious-domain.com', 'badactor.net'],
'hashes': ['5d41402abc4b2a76b9719d911017c592'] # example MD5 hash
}
def check_ioc_in_file(filepath):
with open(filepath, 'r', errors='ignore') as file:
content = file.read()
for ip in iocs['ips']:
if ip in content:
print(f'IOC Found - IP: {ip} in {filepath}')
for domain in iocs['domains']:
if domain in content:
print(f'IOC Found - Domain: {domain} in {filepath}')
for hsh in iocs['hashes']:
if hsh in content:
print(f'IOC Found - Hash: {hsh} in {filepath}')
def scan_directory(path):
for root, dirs, files in os.walk(path):
for file in files:
check_ioc_in_file(os.path.join(root, file))
if __name__ == "__main__":
scan_directory('./logs')
Use Case: Automate IOC scanning of log directories or configuration files to quickly detect compromised indicators.
3. Simple Network Scanner
Discover active hosts on your network by pinging IP address ranges.
python
import subprocess
import ipaddress
def ping_host(ip):
result = subprocess.run(['ping', '-c', '1', '-W', '1', str(ip)], stdout=subprocess.DEVNULL)
return result.returncode == 0
def scan_network(network):
net = ipaddress.IPv4Network(network)
print(f"Scanning network: {network}")
for ip in net.hosts():
if ping_host(ip):
print(f"{ip} is active")
if __name__ == "__main__":
scan_network('192.168.1.0/24')
Use Case: Quickly identify live devices in a subnet to audit network exposure or locate unauthorized hosts.
4. Password Strength Checker
Check if passwords meet common strength criteria, useful during incident responses or audits.
python
import re
def check_password_strength(password):
if len(password) < 8:
return "Weak: Less than 8 characters"
if not re.search(r"[A-Z]", password):
return "Weak: No uppercase letter"
if not re.search(r"[a-z]", password):
return "Weak: No lowercase letter"
if not re.search(r"[0-9]", password):
return "Weak: No digits"
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
return "Weak: No special character"
return "Strong password"
if __name__ == "__main__":
passwords = ['password123', 'P@ssword', 'StrongPass1!']
for pwd in passwords:
print(f"{pwd}: {check_password_strength(pwd)}")
Use Case: Validate password policies or flag weak passwords found during investigations.
5. Log File Tailer with Real-time Filtering
Tail logs live and filter entries containing keywords of interest, similar to a custom tail -f
with grep.
python
import time
def tail_log(filepath, keyword):
with open(filepath, 'r') as f:
# Go to the end of file
f.seek(0, 2)
while True:
line = f.readline()
if not line:
time.sleep(0.5)
continue
if keyword in line:
print(line.strip())
if __name__ == "__main__":
tail_log('access.log', 'ERROR')
Use Case: Monitor logs in real-time during incident investigations for critical errors or alerts.
Final Thoughts
Equipping yourself with these 5 essential Python scripts will empower you as a security analyst to analyze logs faster, detect threats proactively, and streamline network reconnaissance. Python’s flexibility lets you customize and extend these scripts as your environment evolves.
At ZiTechurity, we’re passionate about blending practical tools with security expertise to help professionals like you stay one step ahead of attackers.
Stay tuned for more hands-on scripts, tutorials, and threat intelligence insights.