npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
Overview
Security awareness training is the human layer of phishing defense. An effective anti-phishing training program combines regular simulations, interactive learning modules, metric tracking, and positive reinforcement to build a security-conscious culture. This skill covers designing, deploying, and measuring a comprehensive phishing awareness program using platforms like KnowBe4, Proofpoint Security Awareness, and open-source alternatives.
When to Use
- When deploying or configuring implementing anti phishing training program capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Management buy-in and budget approval
- Security awareness training platform (KnowBe4, Proofpoint SAT, Cofense)
- Employee email list and organizational structure
- Baseline phishing susceptibility data (from initial simulation)
- Learning management system (LMS) integration capability
Key Concepts
Training Program Pillars
- Baseline Assessment: Initial phishing simulation to measure current susceptibility
- Interactive Training: Role-based modules covering phishing identification
- Regular Simulations: Monthly/quarterly phishing tests with progressive difficulty
- Just-in-Time Learning: Immediate training after a user fails a simulation
- Positive Reinforcement: Recognition for reporting phishing correctly
- Metrics & Reporting: Track improvement over time by department and role
SANS Security Awareness Maturity Model
- Level 1: Non-existent - No program
- Level 2: Compliance-focused - Annual checkbox training
- Level 3: Promoting Awareness - Engaging, regular content
- Level 4: Long-term Sustainment - Continuous program with culture change
- Level 5: Metrics Framework - Risk-based measurement and optimization
Workflow
Step 1: Establish Baseline
- Run initial phishing simulation across all departments
- Measure click rate, submit rate, and report rate
- Identify high-risk departments and roles
Step 2: Design Curriculum
- General awareness: Phishing identification basics for all employees
- Role-specific: Finance (BEC/wire fraud), IT (credential phishing), Executives (whaling)
- Progressive difficulty: Beginner, intermediate, advanced modules
- Micro-learning: Short (3-5 minute) frequent sessions vs. annual marathon
Step 3: Deploy Training Platform
- Configure KnowBe4/Proofpoint SAT with organizational groups
- Set up automated enrollment workflows
- Integrate with LMS for completion tracking
- Configure reporting dashboards
Step 4: Run Continuous Simulations
- Monthly simulations with varied scenarios
- Increase difficulty based on organizational performance
- Include diverse attack types: links, attachments, QR codes, BEC
Step 5: Measure and Optimize
Use scripts/process.py to analyze training completion, simulation results, and program effectiveness over time.
Tools & Resources
- KnowBe4: https://www.knowbe4.com/
- Proofpoint Security Awareness: https://www.proofpoint.com/us/products/security-awareness-training
- Cofense PhishMe: https://cofense.com/
- SANS Security Awareness: https://www.sans.org/security-awareness-training/
- Terranova Security: https://terranovasecurity.com/
Validation
- 90%+ training completion rate across organization
- Measurable reduction in phishing click rate over 6 months
- Increase in user phishing report rate
- Department-level improvement tracking
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.8 KB
API Reference: Implementing Anti-Phishing Training Program
KnowBe4 API
import requests
headers = {"Authorization": "Bearer <API_KEY>"}
base = "https://us.api.knowbe4.com/v1"
# List users
users = requests.get(f"{base}/users", headers=headers).json()
# Get phishing campaign results
campaigns = requests.get(f"{base}/phishing/campaigns", headers=headers).json()
# Get training enrollments
enrollments = requests.get(f"{base}/training/enrollments", headers=headers).json()Key Metrics
| Metric | Target | Calculation |
|---|---|---|
| Click Rate | < 15% | Clicked / Total Recipients |
| Submit Rate | < 5% | Submitted Creds / Total |
| Report Rate | > 70% | Reported / Total Recipients |
| Completion Rate | > 90% | Completed / Enrolled |
pandas Simulation Analysis
import pandas as pd
df = pd.read_csv("simulation_results.csv", parse_dates=["timestamp"])
# Department click rates
dept = df.groupby("department").agg(
click_rate=("clicked", "mean"),
report_rate=("reported", "mean"),
)
# Monthly trend
monthly = df.set_index("timestamp").resample("M")["clicked"].mean()SANS Maturity Model Levels
| Level | Name | Description |
|---|---|---|
| 1 | Non-existent | No program |
| 2 | Compliance | Annual checkbox |
| 3 | Awareness | Engaging, regular |
| 4 | Sustainment | Culture change |
| 5 | Metrics | Risk-based optimization |
GoPhish (Open-Source Alternative)
# Launch campaign
curl -X POST https://gophish:3333/api/campaigns \
-H "Authorization: <API_KEY>" \
-d '{"name":"Q1-2025","template":{"name":"IT Alert"},"groups":[{"name":"All Staff"}]}'References
- KnowBe4 API: https://developer.knowbe4.com/
- GoPhish: https://getgophish.com/
- SANS Security Awareness: https://www.sans.org/security-awareness-training/
standards.md2.1 KB
Standards & References: Anti-Phishing Training Program
NIST Guidelines
- NIST SP 800-50: Building an Information Technology Security Awareness and Training Program
- NIST SP 800-16: Information Technology Security Training Requirements
- NIST SP 800-53 Rev.5: AT-1 through AT-6 - Awareness and Training family
Regulatory Requirements
- PCI DSS 4.0: Requirement 12.6 - Security awareness training for all personnel
- HIPAA: 45 CFR 164.308(a)(5) - Security awareness and training
- SOX: Section 404 - Internal controls requiring security awareness
- GDPR: Article 39(1)(b) - Data protection awareness training
- CMMC 2.0: AT.L2-3.2.1/2/3 - Awareness and training practices
- FFIEC: Information Security Handbook - Security awareness training
Industry Frameworks
- SANS Security Awareness Maturity Model: Five-level maturity assessment
- AISA Phishing Resilience Protocol: Australian standard for phishing testing
- CISA Cybersecurity Awareness Program: Federal awareness guidance
MITRE ATT&CK Techniques Addressed by Training
- T1566: Phishing (all sub-techniques)
- T1598: Phishing for Information
- T1204: User Execution
- T1534: Internal Spearphishing
Key Performance Indicators (KPIs)
| KPI | Description | Target |
|---|---|---|
| Phish-Prone Percentage | Users who click simulated phishing | < 5% |
| Training Completion Rate | Users completing assigned modules | > 95% |
| Report Rate | Users reporting simulated phishing | > 70% |
| Time to Report | Average time to report phishing | < 5 minutes |
| Repeat Offender Rate | Users failing multiple simulations | < 2% |
| Training Satisfaction | Post-training survey score | > 4/5 |
| Knowledge Assessment Score | Quiz/test average score | > 85% |
Training Content Categories
- Email phishing identification
- Business email compromise (BEC)
- Spearphishing and whaling
- Vishing (voice phishing)
- Smishing (SMS phishing)
- QR code phishing (quishing)
- Social media phishing
- Credential harvesting
- Malicious attachments
- USB/physical social engineering
workflows.md3.1 KB
Workflows: Anti-Phishing Training Program
Workflow 1: Annual Program Lifecycle
Q1: Baseline & Planning
+-- Run baseline phishing simulation
+-- Assess current awareness maturity level
+-- Define annual targets and KPIs
+-- Select/renew training platform
+-- Design curriculum by role and department
|
Q2: Foundation Training
+-- Deploy core phishing awareness modules
+-- Run monthly simulations (easy difficulty)
+-- Launch phishing report button
+-- Begin tracking metrics
|
Q3: Advanced Training
+-- Role-specific training (finance, IT, executives)
+-- Increase simulation difficulty
+-- Recognize security champions
+-- Mid-year metrics review
|
Q4: Assessment & Optimization
+-- Run year-end assessment simulation
+-- Compare against baseline
+-- Generate annual report
+-- Identify gaps for next year
+-- Present ROI to leadershipWorkflow 2: Just-in-Time Training Flow
User interacts with simulated phishing email
|
v
[Did user click the link?]
|
+-- NO (ignored or reported) --> Positive outcome tracked
| |
| +-- [Did user report it?]
| +-- YES --> Send congratulations, award points
| +-- NO --> No action (not a failure)
|
+-- YES (clicked link)
|
v
[Landing page shows "This was a test"]
|
v
[Immediate micro-training module (2-3 min)]
+-- What red flags were present
+-- How to identify similar emails
+-- How to report suspicious emails
|
v
[Auto-enroll in refresher course within 7 days]
|
v
[Manager receives aggregate report (not individual names)]
|
v
[User included in next simulation cycle]Workflow 3: Repeat Offender Escalation
User fails first simulation
|
+-- Standard just-in-time training
+-- Auto-enrolled in awareness module
|
User fails second simulation (within 6 months)
|
+-- Enhanced training assignment
+-- One-on-one coaching session offered
+-- Manager notification (private)
|
User fails third simulation
|
+-- Mandatory extended training
+-- Access restrictions considered (additional MFA, restricted permissions)
+-- HR involvement per policy
+-- Monthly targeted simulations
|
User passes subsequent simulation
|
+-- Return to normal simulation schedule
+-- Positive reinforcementWorkflow 4: Metrics-Driven Optimization
Monthly Data Collection
|
+-- Simulation results (click, submit, report rates)
+-- Training completion rates
+-- User-reported real phishing volume
+-- Help desk phishing tickets
|
v
[Analyze by dimensions]
+-- Department breakdown
+-- Role/seniority breakdown
+-- Location breakdown
+-- Trend over time
|
v
[Identify patterns]
+-- Which departments are improving?
+-- Which scenarios are most effective?
+-- Are repeat offenders decreasing?
+-- Is report rate increasing?
|
v
[Adjust program]
+-- Increase difficulty for high-performing groups
+-- More training for struggling departments
+-- New scenario types for common gaps
+-- Update content for new threat trendsScripts 2
agent.py6.8 KB
#!/usr/bin/env python3
"""Agent for managing and analyzing anti-phishing training program metrics."""
import json
import argparse
from datetime import datetime
import pandas as pd
import numpy as np
def load_simulation_results(csv_path):
"""Load phishing simulation results CSV."""
df = pd.read_csv(csv_path, parse_dates=["timestamp"])
return df
def calculate_department_metrics(df):
"""Calculate phishing susceptibility metrics per department."""
results = []
for dept, group in df.groupby("department"):
total = len(group)
clicked = group["clicked"].sum()
submitted = group["submitted_credentials"].sum() if "submitted_credentials" in group.columns else 0
reported = group["reported"].sum() if "reported" in group.columns else 0
results.append({
"department": dept,
"total_recipients": int(total),
"click_rate": round(clicked / total * 100, 1) if total > 0 else 0,
"submission_rate": round(submitted / total * 100, 1) if total > 0 else 0,
"report_rate": round(reported / total * 100, 1) if total > 0 else 0,
"risk_level": "HIGH" if clicked / total > 0.3 else "MEDIUM" if clicked / total > 0.15 else "LOW",
})
return sorted(results, key=lambda x: x["click_rate"], reverse=True)
def analyze_trend(df):
"""Analyze phishing simulation trends over time."""
df["month"] = df["timestamp"].dt.to_period("M")
monthly = df.groupby("month").agg(
total=("clicked", "count"),
clicks=("clicked", "sum"),
).reset_index()
monthly["click_rate"] = (monthly["clicks"] / monthly["total"] * 100).round(1)
monthly["month"] = monthly["month"].astype(str)
trend = monthly.to_dict(orient="records")
if len(trend) >= 2:
first_rate = trend[0]["click_rate"]
last_rate = trend[-1]["click_rate"]
improvement = round(first_rate - last_rate, 1)
else:
improvement = 0
return {"monthly_data": trend, "improvement_pct": improvement}
def identify_repeat_clickers(df):
"""Identify users who repeatedly click phishing links."""
clickers = df[df["clicked"] == True]
repeat = clickers.groupby("email").agg(
click_count=("clicked", "sum"),
department=("department", "first"),
name=("name", "first") if "name" in df.columns else ("email", "first"),
).reset_index()
repeat = repeat[repeat["click_count"] >= 2].sort_values("click_count", ascending=False)
return repeat.to_dict(orient="records")
def calculate_training_completion(training_df):
"""Calculate training module completion rates."""
results = []
for module, group in training_df.groupby("module_name"):
total = len(group)
completed = group["completed"].sum()
results.append({
"module": module,
"enrolled": int(total),
"completed": int(completed),
"completion_rate": round(completed / total * 100, 1) if total > 0 else 0,
})
return sorted(results, key=lambda x: x["completion_rate"])
def generate_risk_score(dept_metrics):
"""Generate overall organization risk score based on phishing metrics."""
if not dept_metrics:
return {"score": 0, "grade": "N/A"}
avg_click = np.mean([d["click_rate"] for d in dept_metrics])
avg_report = np.mean([d["report_rate"] for d in dept_metrics])
score = max(0, 100 - (avg_click * 2) + (avg_report * 0.5))
if score >= 85:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 55:
grade = "C"
elif score >= 40:
grade = "D"
else:
grade = "F"
return {
"score": round(score, 1),
"grade": grade,
"avg_click_rate": round(avg_click, 1),
"avg_report_rate": round(avg_report, 1),
}
def recommend_training(dept_metrics, repeat_clickers):
"""Generate training recommendations based on metrics."""
recommendations = []
high_risk_depts = [d for d in dept_metrics if d["risk_level"] == "HIGH"]
for dept in high_risk_depts:
recommendations.append({
"target": dept["department"],
"type": "department",
"action": "Mandatory phishing awareness training",
"priority": "HIGH",
"reason": f"Click rate {dept['click_rate']}% exceeds 30% threshold",
})
for user in repeat_clickers[:20]:
recommendations.append({
"target": user.get("email", ""),
"type": "individual",
"action": "One-on-one coaching session",
"priority": "CRITICAL",
"reason": f"Clicked {user['click_count']} times across simulations",
})
return recommendations
def main():
parser = argparse.ArgumentParser(description="Anti-Phishing Training Program Agent")
parser.add_argument("--simulation-csv", help="Phishing simulation results CSV")
parser.add_argument("--training-csv", help="Training completion CSV")
parser.add_argument("--output", default="phishing_training_report.json")
parser.add_argument("--action", choices=[
"departments", "trends", "repeaters", "completion", "full_analysis"
], default="full_analysis")
args = parser.parse_args()
report = {"generated_at": datetime.utcnow().isoformat(), "findings": {}}
if args.simulation_csv:
df = load_simulation_results(args.simulation_csv)
print(f"[+] Loaded {len(df)} simulation results")
if args.action in ("departments", "full_analysis"):
metrics = calculate_department_metrics(df)
report["findings"]["department_metrics"] = metrics
report["findings"]["risk_score"] = generate_risk_score(metrics)
print(f"[+] Departments analyzed: {len(metrics)}")
if args.action in ("trends", "full_analysis"):
trend = analyze_trend(df)
report["findings"]["trend_analysis"] = trend
print(f"[+] Improvement: {trend['improvement_pct']}%")
if args.action in ("repeaters", "full_analysis"):
repeaters = identify_repeat_clickers(df)
report["findings"]["repeat_clickers"] = repeaters
print(f"[+] Repeat clickers: {len(repeaters)}")
if args.action == "full_analysis":
metrics = report["findings"].get("department_metrics", [])
repeaters = report["findings"].get("repeat_clickers", [])
recs = recommend_training(metrics, repeaters)
report["findings"]["recommendations"] = recs
if args.training_csv:
tdf = pd.read_csv(args.training_csv)
completion = calculate_training_completion(tdf)
report["findings"]["training_completion"] = completion
print(f"[+] Training modules: {len(completion)}")
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
process.py13.9 KB
#!/usr/bin/env python3
"""
Anti-Phishing Training Program Analytics
Tracks training completion, simulation results, and program effectiveness
over time. Generates reports comparing departments, identifying repeat
offenders, and measuring ROI.
Usage:
python process.py dashboard --data program_data.json
python process.py trend --data program_data.json --months 12
python process.py repeat-offenders --data program_data.json
python process.py department-report --data program_data.json
"""
import argparse
import json
import sys
from datetime import datetime, timezone
from collections import defaultdict
from dataclasses import dataclass, field, asdict
@dataclass
class UserRecord:
"""Training and simulation record for a single user."""
email: str = ""
name: str = ""
department: str = ""
role: str = ""
simulations_sent: int = 0
simulations_clicked: int = 0
simulations_submitted: int = 0
simulations_reported: int = 0
trainings_assigned: int = 0
trainings_completed: int = 0
last_simulation_date: str = ""
last_training_date: str = ""
risk_level: str = "low"
@dataclass
class DepartmentMetrics:
"""Aggregated metrics for a department."""
name: str = ""
total_users: int = 0
avg_click_rate: float = 0.0
avg_submit_rate: float = 0.0
avg_report_rate: float = 0.0
training_completion: float = 0.0
repeat_offenders: int = 0
trend: str = "stable"
@dataclass
class ProgramDashboard:
"""Overall program dashboard metrics."""
total_users: int = 0
total_simulations_sent: int = 0
overall_click_rate: float = 0.0
overall_submit_rate: float = 0.0
overall_report_rate: float = 0.0
training_completion_rate: float = 0.0
repeat_offender_count: int = 0
repeat_offender_rate: float = 0.0
maturity_level: int = 1
departments: list = field(default_factory=list)
top_risks: list = field(default_factory=list)
monthly_trends: list = field(default_factory=list)
def calculate_risk_level(user: UserRecord) -> str:
"""Calculate risk level for a user based on simulation history."""
if user.simulations_sent == 0:
return "unknown"
click_rate = user.simulations_clicked / user.simulations_sent
submit_rate = user.simulations_submitted / user.simulations_sent
if submit_rate > 0.3 or user.simulations_submitted >= 3:
return "critical"
elif click_rate > 0.4 or user.simulations_clicked >= 3:
return "high"
elif click_rate > 0.2:
return "medium"
elif user.simulations_reported > 0:
return "low"
else:
return "low"
def assess_maturity(dashboard: ProgramDashboard) -> int:
"""Assess SANS Security Awareness Maturity level (1-5)."""
if dashboard.total_simulations_sent == 0:
return 1 # Non-existent
if dashboard.training_completion_rate < 50:
return 2 # Compliance-focused
if dashboard.overall_click_rate > 15:
return 2
if dashboard.overall_click_rate > 5:
return 3 # Promoting Awareness
if dashboard.overall_report_rate > 50 and dashboard.overall_click_rate < 5:
return 5 # Metrics Framework
return 4 # Long-term Sustainment
def process_program_data(data: dict) -> ProgramDashboard:
"""Process raw program data into dashboard metrics."""
dashboard = ProgramDashboard()
users_data = data.get("users", [])
simulations = data.get("simulations", [])
trainings = data.get("trainings", [])
# Build user records
user_records = {}
for u in users_data:
record = UserRecord(
email=u.get("email", ""),
name=u.get("name", ""),
department=u.get("department", "Unknown"),
role=u.get("role", ""),
)
user_records[record.email] = record
# Process simulation results
for sim in simulations:
for result in sim.get("results", []):
email = result.get("email", "")
if email in user_records:
user = user_records[email]
user.simulations_sent += 1
if result.get("clicked"):
user.simulations_clicked += 1
if result.get("submitted"):
user.simulations_submitted += 1
if result.get("reported"):
user.simulations_reported += 1
user.last_simulation_date = sim.get("date", "")
# Process training completions
for training in trainings:
for completion in training.get("completions", []):
email = completion.get("email", "")
if email in user_records:
user = user_records[email]
user.trainings_assigned += 1
if completion.get("completed"):
user.trainings_completed += 1
user.last_training_date = training.get("date", "")
# Calculate risk levels
for user in user_records.values():
user.risk_level = calculate_risk_level(user)
# Aggregate overall metrics
all_users = list(user_records.values())
dashboard.total_users = len(all_users)
total_sent = sum(u.simulations_sent for u in all_users)
total_clicked = sum(u.simulations_clicked for u in all_users)
total_submitted = sum(u.simulations_submitted for u in all_users)
total_reported = sum(u.simulations_reported for u in all_users)
total_assigned = sum(u.trainings_assigned for u in all_users)
total_completed = sum(u.trainings_completed for u in all_users)
dashboard.total_simulations_sent = total_sent
dashboard.overall_click_rate = round(total_clicked / max(total_sent, 1) * 100, 1)
dashboard.overall_submit_rate = round(total_submitted / max(total_sent, 1) * 100, 1)
dashboard.overall_report_rate = round(total_reported / max(total_sent, 1) * 100, 1)
dashboard.training_completion_rate = round(total_completed / max(total_assigned, 1) * 100, 1)
# Repeat offenders (clicked 2+ times)
repeat_offenders = [u for u in all_users if u.simulations_clicked >= 2]
dashboard.repeat_offender_count = len(repeat_offenders)
dashboard.repeat_offender_rate = round(
len(repeat_offenders) / max(len(all_users), 1) * 100, 1
)
# Department breakdown
dept_users = defaultdict(list)
for user in all_users:
dept_users[user.department].append(user)
for dept_name, users in sorted(dept_users.items()):
dept = DepartmentMetrics(name=dept_name, total_users=len(users))
d_sent = sum(u.simulations_sent for u in users)
d_clicked = sum(u.simulations_clicked for u in users)
d_submitted = sum(u.simulations_submitted for u in users)
d_reported = sum(u.simulations_reported for u in users)
d_assigned = sum(u.trainings_assigned for u in users)
d_completed = sum(u.trainings_completed for u in users)
dept.avg_click_rate = round(d_clicked / max(d_sent, 1) * 100, 1)
dept.avg_submit_rate = round(d_submitted / max(d_sent, 1) * 100, 1)
dept.avg_report_rate = round(d_reported / max(d_sent, 1) * 100, 1)
dept.training_completion = round(d_completed / max(d_assigned, 1) * 100, 1)
dept.repeat_offenders = sum(1 for u in users if u.simulations_clicked >= 2)
dashboard.departments.append(dept)
# Top risk users
risk_users = sorted(all_users, key=lambda u: u.simulations_submitted, reverse=True)
dashboard.top_risks = [
{"email": u.email, "name": u.name, "department": u.department,
"click_count": u.simulations_clicked, "submit_count": u.simulations_submitted,
"risk_level": u.risk_level}
for u in risk_users[:20] if u.simulations_clicked > 0
]
# Monthly trends from simulation data
monthly = defaultdict(lambda: {"sent": 0, "clicked": 0, "submitted": 0, "reported": 0})
for sim in simulations:
month = sim.get("date", "")[:7] # YYYY-MM
for result in sim.get("results", []):
monthly[month]["sent"] += 1
if result.get("clicked"):
monthly[month]["clicked"] += 1
if result.get("submitted"):
monthly[month]["submitted"] += 1
if result.get("reported"):
monthly[month]["reported"] += 1
for month in sorted(monthly.keys()):
m = monthly[month]
dashboard.monthly_trends.append({
"month": month,
"sent": m["sent"],
"click_rate": round(m["clicked"] / max(m["sent"], 1) * 100, 1),
"submit_rate": round(m["submitted"] / max(m["sent"], 1) * 100, 1),
"report_rate": round(m["reported"] / max(m["sent"], 1) * 100, 1),
})
dashboard.maturity_level = assess_maturity(dashboard)
return dashboard
def format_dashboard(dashboard: ProgramDashboard) -> str:
"""Format dashboard as text report."""
lines = []
lines.append("=" * 65)
lines.append(" ANTI-PHISHING TRAINING PROGRAM DASHBOARD")
lines.append("=" * 65)
lines.append(f" Generated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}")
lines.append(f" Maturity Level: {dashboard.maturity_level}/5 (SANS Model)")
lines.append("")
lines.append("[PROGRAM OVERVIEW]")
lines.append(f" Total Users: {dashboard.total_users}")
lines.append(f" Total Simulations Sent: {dashboard.total_simulations_sent}")
lines.append(f" Overall Click Rate: {dashboard.overall_click_rate}%")
lines.append(f" Overall Submit Rate: {dashboard.overall_submit_rate}%")
lines.append(f" Overall Report Rate: {dashboard.overall_report_rate}%")
lines.append(f" Training Completion: {dashboard.training_completion_rate}%")
lines.append(f" Repeat Offenders: {dashboard.repeat_offender_count} "
f"({dashboard.repeat_offender_rate}%)")
lines.append("")
lines.append("[DEPARTMENT BREAKDOWN]")
lines.append(f" {'Department':<20} {'Users':>6} {'Click%':>7} {'Submit%':>8} "
f"{'Report%':>8} {'Training%':>10} {'Repeat':>7}")
lines.append(" " + "-" * 66)
for dept in sorted(dashboard.departments, key=lambda d: d.avg_click_rate, reverse=True):
lines.append(f" {dept.name:<20} {dept.total_users:>6} {dept.avg_click_rate:>6.1f}% "
f"{dept.avg_submit_rate:>7.1f}% {dept.avg_report_rate:>7.1f}% "
f"{dept.training_completion:>9.1f}% {dept.repeat_offenders:>7}")
lines.append("")
if dashboard.top_risks:
lines.append("[TOP RISK USERS]")
for i, user in enumerate(dashboard.top_risks[:10], 1):
lines.append(f" {i}. {user['name']} ({user['department']}) - "
f"Clicked: {user['click_count']}, Submitted: {user['submit_count']} "
f"[{user['risk_level'].upper()}]")
lines.append("")
if dashboard.monthly_trends:
lines.append("[MONTHLY TRENDS]")
lines.append(f" {'Month':<10} {'Sent':>6} {'Click%':>7} {'Submit%':>8} {'Report%':>8}")
lines.append(" " + "-" * 39)
for trend in dashboard.monthly_trends[-12:]:
lines.append(f" {trend['month']:<10} {trend['sent']:>6} "
f"{trend['click_rate']:>6.1f}% {trend['submit_rate']:>7.1f}% "
f"{trend['report_rate']:>7.1f}%")
lines.append("")
lines.append("=" * 65)
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description="Anti-Phishing Training Program Analytics")
subparsers = parser.add_subparsers(dest="command")
dash_parser = subparsers.add_parser("dashboard", help="Generate program dashboard")
dash_parser.add_argument("--data", required=True, help="Program data JSON file")
dash_parser.add_argument("--output", "-o", help="Output file")
dept_parser = subparsers.add_parser("department-report", help="Department breakdown")
dept_parser.add_argument("--data", required=True)
repeat_parser = subparsers.add_parser("repeat-offenders", help="List repeat offenders")
repeat_parser.add_argument("--data", required=True)
repeat_parser.add_argument("--threshold", type=int, default=2, help="Minimum click count")
trend_parser = subparsers.add_parser("trend", help="Show monthly trends")
trend_parser.add_argument("--data", required=True)
trend_parser.add_argument("--months", type=int, default=12)
parser.add_argument("--json", action="store_true", help="Output as JSON")
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(1)
with open(args.data, "r") as f:
data = json.load(f)
dashboard = process_program_data(data)
if args.command == "dashboard":
if args.json:
output = json.dumps(asdict(dashboard), indent=2, default=str)
else:
output = format_dashboard(dashboard)
if args.output:
with open(args.output, "w") as f:
f.write(output)
print(f"Dashboard written to {args.output}")
else:
print(output)
elif args.command == "department-report":
for dept in sorted(dashboard.departments, key=lambda d: d.avg_click_rate, reverse=True):
if args.json:
print(json.dumps(asdict(dept), indent=2))
else:
print(f"{dept.name}: {dept.total_users} users, "
f"click={dept.avg_click_rate}%, report={dept.avg_report_rate}%, "
f"training={dept.training_completion}%")
elif args.command == "repeat-offenders":
for user in dashboard.top_risks:
if user["click_count"] >= args.threshold:
print(f" {user['name']} ({user['department']}): "
f"clicked {user['click_count']}x, submitted {user['submit_count']}x "
f"[{user['risk_level']}]")
elif args.command == "trend":
for trend in dashboard.monthly_trends[-args.months:]:
print(f" {trend['month']}: click={trend['click_rate']}%, "
f"submit={trend['submit_rate']}%, report={trend['report_rate']}%")
if __name__ == "__main__":
main()