Welcome back to ZiTechurity! Building on our previous discussions about essential Python scripts for security analysts and their automation, today we’re sharing sample automation scripts and practical tips to help you streamline execution and integrate results with your SIEM platform.
Sample Automation Script: Scheduled IOC Scanner with Logging and Alerts
This Python script extends a simple IOC checker by adding:
- Scheduled execution (you can tie it with cron or Task Scheduler)
- Structured JSON logging for SIEM ingestion
- Email alerting for critical findings
python
import os
import json
import smtplib
from email.mime.text import MIMEText
import time
# Define IOCs
iocs = {
'ips': ['192.168.1.100', '10.0.0.5'],
'domains': ['malicious-domain.com', 'badactor.net'],
'hashes': ['5d41402abc4b2a76b9719d911017c592']
}
LOG_FILE = 'ioc_alerts.log'
EMAIL_TO = 'soc-team@zitechurity.com'
EMAIL_FROM = 'alerts@zitechurity.com'
SMTP_SERVER = 'smtp.example.com'
SMTP_USER = 'user'
SMTP_PASS = 'password'
def send_email_alert(subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO
try:
with smtplib.SMTP(SMTP_SERVER) as server:
server.login(SMTP_USER, SMTP_PASS)
server.send_message(msg)
print(f"Email alert sent: {subject}")
except Exception as e:
print(f"Failed to send email: {e}")
def log_ioc_alert(ioc_type, ioc_value, filepath):
alert = {
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"ioc_type": ioc_type,
"ioc_value": ioc_value,
"source": "Automated IOC Scanner"
}
with open(filepath, 'a') as f:
f.write(json.dumps(alert) + "\n")
def check_ioc_in_file(filepath):
found_any = False
try:
with open(filepath, 'r', errors='ignore') as file:
content = file.read()
for ip in iocs['ips']:
if ip in content:
log_ioc_alert('IP', ip, LOG_FILE)
send_email_alert('IOC Detected - IP', f'{ip} found in {filepath}')
found_any = True
for domain in iocs['domains']:
if domain in content:
log_ioc_alert('Domain', domain, LOG_FILE)
send_email_alert('IOC Detected - Domain', f'{domain} found in {filepath}')
found_any = True
for hsh in iocs['hashes']:
if hsh in content:
log_ioc_alert('Hash', hsh, LOG_FILE)
send_email_alert('IOC Detected - Hash', f'{hsh} found in {filepath}')
found_any = True
except Exception as e:
print(f"Error reading file {filepath}: {e}")
return found_any
def scan_directory(path):
print(f"Scanning 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')
Scheduling Your Script
- On Linux/macOS, set up a cron job (edit withÂ
crontab -e
):
bash0 3 * * * /usr/bin/python3 /path/to/automated_ioc_scanner.py >> /var/log/ioc_scanner.log 2>&1
- On Windows, create a Task Scheduler job to run daily at your preferred time.
Integrating with Your SIEM Platform
- Log Forwarding:Â Configure your SIEM agent to monitorÂ
ioc_alerts.log
. The JSON format allows your SIEM to parse and index alerts efficiently. - Custom Parsers:Â Define log parsing rules in your SIEM to extract IOC details (
ioc_type
,Âioc_value
, and timestamps). - Alerting & Dashboards:Â Use these fields to build alerts and dashboards that highlight IOC activity across your network.
- API Integration (Advanced):Â Some SIEM systems allow you to push logs via API for immediate ingestion.
Tips for Production Use
- Secure Credentials:Â Use environment variables or secured vaults to store SMTP and other sensitive credentials.
- Error Handling:Â Add robust logging and exception management to avoid silent failures.
- Scalability:Â Break large directories into batches or parallelize I/O for efficiency.
Next Steps
Automating your Python-based security tools transforms your monitoring from reactive to proactive. Paired with SIEM integration, it boosts visibility and speeds response times.
At ZiTechurity, we’re here to help you accelerate your security automation journey. If you want, we can create:
- Video walkthroughs of script deployment and integration
- Ready-to-use Docker containers for easier deployment
- Custom scripts tailored to your environment
Just let us know!
Stay secure, stay automated — only at ZiTechurity.