5 Python Scripts That Saved Me Hours During My Cybersecurity Internship

5 Python Scripts That Saved Me Hours During My Cybersecurity Internship

5 Python Scripts I Actually Use for Security Tasks — Real Code From My Internship at Inhok

5 Python Scripts I Actually Use for Security Tasks

During my 6-month internship at Inhok Technologies, I wrote a lot of Python scripts. Not complex algorithms or fancy frameworks. Simple, practical scripts that solved actual problems we faced in the SOC (Security Operations Center):

  • Parsing Splunk logs that were formatted wrong
  • Analyzing alert patterns to find false positives
  • Extracting indicators of compromise from incident reports
  • Automating threat intelligence lookups
  • Processing network traffic data for investigation

Most SOC analysts use bash scripts or off-the-shelf tools. I used Python because I could write something in 30 minutes that would have taken 2 hours to do manually every single time it was needed.

This post shares 5 real scripts I used. Not "tutorial quality" code. Actual working code from actual SOC work. You can copy these, modify them for your environment, and use them today.

What you'll get: 5 working Python scripts from SOC/SIEM work. Real use cases. Real code. How to modify them. What I learned writing them. How they actually saved time at Inhok.

📚 Python Books That Made Security Automation Easier

These scripts were built from real SOC work, but the ideas came from learning Python for cybersecurity. If you want to write your own automation tools, these are the books I'd recommend.


🐍 Black Hat Python

One of the best books for learning practical Python in cybersecurity. It covers networking, automation, reconnaissance, and offensive security techniques that can inspire your own security tools.

📖 View on Amazon

⚡ Violent Python

Learn how Python can automate penetration testing, log analysis, forensics, and incident response tasks. Great for building practical cybersecurity scripts.

📖 View on Amazon

💻 Python Crash Course

If you're completely new to Python, start here first. It builds the programming foundation you'll need before creating security automation scripts.

📖 View on Amazon

Disclosure: As an Amazon Associate, I earn from qualifying purchases at no additional cost to you.

Script 1: Splunk Log Parser (Extract Key Fields From Messy Logs)

splunk_log_parser.py
Use case: Parsing Splunk raw events where fields are inconsistently formatted | Time saved: ~2 hours per day
Our Splunk environment had logs from 20+ different sources. Some used JSON, some used key=value, some used CSV. When I needed to extract a specific field across all sources, I had to manually parse each format. This script handles multiple formats and extracts fields consistently.
import json from datetime import datetime def parse_splunk_event(raw_event): # Try JSON first try: parsed = json.loads(raw_event) return parsed except: pass # Try key=value format (Splunk default) parsed = {} for pair in raw_event.split(): if '=' in pair: key, value = pair.split('=', 1) parsed[key] = value return parsed if parsed else {'raw': raw_event} def extract_field(events, field_name): # Extract specific field from multiple events extracted = [] for event in events: parsed = parse_splunk_event(event) if field_name in parsed: extracted.append({ 'timestamp': datetime.now().isoformat(), 'field': field_name, 'value': parsed[field_name] }) return extracted # Usage splunk_events = [ 'timestamp=2026-07-06T10:30:00 source_ip=192.168.1.100 dest_ip=8.8.8.8 action=blocked', '{\"timestamp\": \"2026-07-06T10:31:00\", \"source_ip\": \"10.0.0.50\", \"action\": \"allowed\"}' ] results = extract_field(splunk_events, 'source_ip') for result in results: print(result)
Why I wrote this: Splunk queries were slow when searching across multiple data sources with different formats. This script preprocessed raw logs, standardized the format, and made field extraction 10x faster. Saved ~2 hours per day of manual parsing.

Script 2: False Positive Detector (Find Recurring Low-Risk Alerts)

false_positive_detector.py
Use case: Identifying which alerts trigger repeatedly without actual security impact | Time saved: ~3 hours per day
We got ~2,000 alerts per day. Maybe 50 were actual security incidents. The rest were mostly false positives from misconfigured apps, legitimate admin activities, or known benign traffic. This script identifies which alerts trigger most frequently and clusters them to find patterns. We used this to tune alert thresholds and reduce noise by 70%.
import json from collections import Counter, defaultdict def analyze_alerts(alert_log_file, days=7): # Read alerts from file (JSON format) alerts = [] with open(alert_log_file, 'r') as f: for line in f: try: alerts.append(json.loads(line)) except: pass # Count alert types alert_types = Counter() alert_details = defaultdict(list) for alert in alerts: alert_name = alert.get('alert_name', 'unknown') alert_types[alert_name] += 1 alert_details[alert_name].append({ 'source_ip': alert.get('src_ip'), 'dest_ip': alert.get('dest_ip'), 'timestamp': alert.get('timestamp') }) # Find alerts that trigger >100 times (likely false positives) suspicious_patterns = {} for alert_name, count in alert_types.most_common(20): if count > 100: # Get most common source IPs for this alert sources = Counter() for detail in alert_details[alert_name]: if detail['source_ip']: sources[detail['source_ip']] += 1 suspicious_patterns[alert_name] = { 'total_count': count, 'top_sources': sources.most_common(5), 'severity': 'LIKELY_FP' } return suspicious_patterns # Usage fp_analysis = analyze_alerts('alerts.jsonl', days=7) for alert, details in fp_analysis.items(): print(f'{alert}: {details["total_count"]} times - {details["top_sources"]}')
Why I wrote this: Splunk dashboards show you alerts, but they don't automatically tell you which ones are noise. This script ran overnight on our alert logs and generated a report of "alerts that fire 100+ times" — which we then reviewed and tuned. Reduced alert volume by 70% and freed up analyst time for real incidents.

Script 3: IOC Extractor (Pull Indicators of Compromise From Reports)

ioc_extractor.py
Use case: Extracting IPs, domains, file hashes from incident reports | Time saved: ~1 hour per report
When we got incident reports from external security firms or threat intel feeds, they were usually PDFs or unstructured text. Extracting IP addresses, domains, and file hashes meant manual copy-pasting. This script uses regex to find indicators and outputs them in a format we could feed into Splunk threat intelligence lists.
import re import json def extract_indicators(text): # Extract different IOC types from text indicators = { 'ipv4': [], 'domains': [], 'md5': [], 'sha256': [], 'urls': [] } # IPv4 addresses ipv4_pattern = r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b' indicators['ipv4'] = list(set(re.findall(ipv4_pattern, text))) # Domains domain_pattern = r'\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}\b' indicators['domains'] = list(set(re.findall(domain_pattern, text, re.IGNORECASE))) # MD5 hashes md5_pattern = r'\b[a-f0-9]{32}\b' indicators['md5'] = list(set(re.findall(md5_pattern, text, re.IGNORECASE))) # SHA256 hashes sha256_pattern = r'\b[a-f0-9]{64}\b' indicators['sha256'] = list(set(re.findall(sha256_pattern, text, re.IGNORECASE))) # URLs url_pattern = r'https?://[^\s\)\"<>]+' indicators['urls'] = list(set(re.findall(url_pattern, text))) return indicators # Usage report_text = """ Incident Report: APT Activity Detected Source IPs: 192.168.1.50, 10.0.0.100 C2 Domains: evil.com, malware-panel.ru File Hashes: d41d8cd98f00b204e9800998ecf8427e, abc123... Malware URLs: https://evil.com/payload.exe """ iocs = extract_indicators(report_text) print(json.dumps(iocs, indent=2))
Why I wrote this: We received threat intel reports daily. Manually extracting indicators took 1 hour per report. This script did it in seconds. We piped the output directly into Splunk threat intelligence lists, enabling automatic detection of malware and C2 traffic.

Script 4: Threat Intelligence Lookup (Batch-Check IPs Against Multiple Feeds)

ti_lookup.py
Use case: Checking suspicious IPs against threat intelligence feeds | Time saved: ~30 minutes per investigation
During incident investigation, analysts need to know: is this IP known malicious? Is it from a datacenter? Is it on any blocklists? Manually checking VirusTotal, AbuseIPDB, and other services for each IP takes forever. This script queries multiple APIs and returns a risk score.
import requests import json def check_ip_reputation(ip_address, virustotal_key='your_api_key'): # Check VirusTotal vt_url = f'https://www.virustotal.com/api/v3/ip_addresses/{ip_address}' vt_headers = {'x-apikey': virustotal_key} try: vt_response = requests.get(vt_url, headers=vt_headers, timeout=5) vt_data = vt_response.json() vt_score = vt_data['data']['attributes']['last_analysis_stats']['malicious'] except: vt_score = 0 # Check AbuseIPDB (optional) abuse_url = 'https://api.abuseipdb.com/api/v2/check' abuse_params = {'ipAddress': ip_address, 'maxAgeInDays': 90} try: abuse_response = requests.get(abuse_url, params=abuse_params, timeout=5) abuse_data = abuse_response.json() abuse_score = abuse_data['data']['abuseConfidenceScore'] except: abuse_score = 0 # Calculate risk risk_level = 'LOW' if vt_score > 5 or abuse_score > 50: risk_level = 'HIGH' elif vt_score > 2 or abuse_score > 25: risk_level = 'MEDIUM' return { 'ip': ip_address, 'virustotal_detections': vt_score, 'abuseipdb_score': abuse_score, 'risk_level': risk_level } # Usage suspicious_ips = ['8.8.8.8', '192.168.1.1'] for ip in suspicious_ips: result = check_ip_reputation(ip) print(json.dumps(result, indent=2))
Why I wrote this: During incident investigation, analysts were spending 30 minutes checking IPs manually on different websites. This script does batch lookups and prioritizes suspicious IPs automatically. Massive time saver during active incidents.

Script 5: Firewall Log Analyzer (Find Unusual Outbound Traffic Patterns)

firewall_pattern_analyzer.py
Use case: Detecting data exfiltration by identifying unusual outbound traffic patterns | Time saved: ~2 hours per week
Firewall logs are one of the best ways to spot exfiltration attempts. I wrote this script to identify endpoints sending unusually large amounts of traffic to external IPs, especially after normal business hours. It helped us prioritize which hosts to investigate first.
import csv from collections import defaultdict def analyze_outbound_traffic(log_file): traffic = defaultdict(int) suspicious_hosts = [] with open(log_file, 'r') as f: reader = csv.DictReader(f) for row in reader: src = row.get('src_ip') dest = row.get('dest_ip') bytes_sent = int(row.get('bytes', '0')) action = row.get('action') if action == 'allow' and src and dest: traffic[src] += bytes_sent for host, total_bytes in traffic.items(): if total_bytes > 100000000: suspicious_hosts.append({ 'host': host, 'total_bytes': total_bytes, 'risk': 'HIGH' }) return sorted(suspicious_hosts, key=lambda x: x['total_bytes'], reverse=True) # Usage results = analyze_outbound_traffic('firewall.csv') for r in results: print(r)
Why I wrote this: We had to catch hosts sending too much traffic before escalation. This script flagged unusual hosts automatically and gave us a short list to review instead of combing through every firewall log line.

What These Scripts Taught Me

Every script above followed the same pattern: identify a repetitive SOC task, build the smallest useful automation, and make it easy to run from a terminal or notebook.

That sounds obvious, but it changed how I approached security work. I stopped thinking "how do I do this one time" and started thinking "how do I remove this manual step forever?"

  • Fast wins: The best script is the one you actually run every day.
  • Start messy: Perfect code is less useful than a script that saves time today.
  • Optimize later: First make it work, then make it pretty.
Internship reality check

During SOC work, the biggest problem wasn't lack of tools. It was time. Analysts had to move fast, and every repetitive step slowed down response. These scripts gave me a way to automate the boring parts so I could focus on the actual investigation.

If you're learning cybersecurity, don't just study theory. Find one annoying manual task and write a script for it. That's how you build real skill.

📖 Ready for More Advanced Security Automation?

Once you're comfortable writing small Python utilities, the next step is learning how security professionals automate penetration testing and exploit development.

Recommended next read: The Hacker Playbook 3 — packed with practical workflows that pair well with Python automation.

📚 View The Hacker Playbook 3

Frequently Asked Questions

Can I use these scripts in my own SOC environment?
Yes, but you should modify them for your log formats, field names, API keys, and internal workflows before using them in production.
Do these scripts require advanced Python knowledge?
No. They use basic Python concepts like functions, dictionaries, lists, regex, file I/O, and simple API calls.
What should I automate first as a beginner?
Start with the task you repeat most often, such as IOC extraction, log formatting, or alert triage.

About the Author

Amardeep Maroli

MCA (Master of Computer Applications) — PES University, Bengaluru
Cybersecurity Intern — Inhok Technologies (6-month SOC/SIEM experience)
SIEM Experience: Splunk (search processing language, dashboard creation, detection rule development), Wazuh (open-source deployment and configuration)
TryHackMe — Top 2% Globally | SOC Level 1 Certified

Currently targeting SOC L1 Analyst roles at MSSPs. Learning path focus: foundational concepts first, tool proficiency second, real-world application third.

Post a Comment

0 Comments