Spaces:
Sleeping
Sleeping
removed temporary examples
Browse files
temporary_examples/extract_urls_from_sitemaps.py
DELETED
|
@@ -1,208 +0,0 @@
|
|
| 1 |
-
"""Extract URLs from legitimate domains using sitemaps and save to CSV."""
|
| 2 |
-
|
| 3 |
-
import logging
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import pandas as pd
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
import json
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
from src.phising_detection.data.sitemap_parser import get_urls_from_sitemap
|
| 11 |
-
|
| 12 |
-
# Configure logging
|
| 13 |
-
logging.basicConfig(
|
| 14 |
-
level=logging.INFO,
|
| 15 |
-
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 16 |
-
)
|
| 17 |
-
logger = logging.getLogger(__name__)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def get_already_processed_domains(csv_file: Path) -> set:
|
| 21 |
-
"""
|
| 22 |
-
Get set of domains that have already been processed.
|
| 23 |
-
|
| 24 |
-
Args:
|
| 25 |
-
csv_file: Path to the CSV file with processed results
|
| 26 |
-
|
| 27 |
-
Returns:
|
| 28 |
-
Set of domain names that have been processed
|
| 29 |
-
"""
|
| 30 |
-
if not csv_file.exists():
|
| 31 |
-
return set()
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
df = pd.read_csv(csv_file)
|
| 35 |
-
if 'domain' in df.columns:
|
| 36 |
-
return set(df['domain'].unique())
|
| 37 |
-
except Exception as e:
|
| 38 |
-
logger.warning(f"Error reading existing CSV: {e}")
|
| 39 |
-
|
| 40 |
-
return set()
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def save_batch_to_csv(batch_data: list, csv_file: Path):
|
| 44 |
-
"""
|
| 45 |
-
Save a batch of domain data to CSV.
|
| 46 |
-
|
| 47 |
-
Args:
|
| 48 |
-
batch_data: List of dictionaries with keys: domain, urls, time_updated
|
| 49 |
-
csv_file: Path to CSV file
|
| 50 |
-
"""
|
| 51 |
-
if not batch_data:
|
| 52 |
-
return
|
| 53 |
-
|
| 54 |
-
df = pd.DataFrame(batch_data)
|
| 55 |
-
|
| 56 |
-
# Convert URL lists to JSON strings for CSV storage
|
| 57 |
-
df['urls'] = df['urls'].apply(json.dumps)
|
| 58 |
-
|
| 59 |
-
# Write header only if creating new file
|
| 60 |
-
header = not csv_file.exists()
|
| 61 |
-
|
| 62 |
-
df.to_csv(csv_file, mode='a', header=header, index=False)
|
| 63 |
-
logger.info(f"Saved batch of {len(batch_data)} domains to {csv_file}")
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def main():
|
| 67 |
-
"""Extract URLs from legitimate domains and save to CSV incrementally."""
|
| 68 |
-
|
| 69 |
-
# Paths
|
| 70 |
-
data_dir = Path(__file__).parent.parent / "src" / "phising_detection" / "data" / "data_files"
|
| 71 |
-
domains_file = data_dir / "legitimate-urls.txt"
|
| 72 |
-
output_csv = data_dir / "legitimate-urls-extracted.csv"
|
| 73 |
-
|
| 74 |
-
# Read domains from file
|
| 75 |
-
logger.info(f"Reading domains from {domains_file}")
|
| 76 |
-
with open(domains_file, 'r', encoding='utf-8') as f:
|
| 77 |
-
all_domains = [line.strip() for line in f if line.strip()]
|
| 78 |
-
|
| 79 |
-
logger.info(f"Loaded {len(all_domains)} total domains")
|
| 80 |
-
|
| 81 |
-
# Check which domains have already been processed
|
| 82 |
-
processed_domains = get_already_processed_domains(output_csv)
|
| 83 |
-
logger.info(f"Already processed: {len(processed_domains)} domains")
|
| 84 |
-
|
| 85 |
-
# Filter out already processed domains
|
| 86 |
-
domains_to_process = [d for d in all_domains if d not in processed_domains]
|
| 87 |
-
logger.info(f"Remaining to process: {len(domains_to_process)} domains")
|
| 88 |
-
|
| 89 |
-
if not domains_to_process:
|
| 90 |
-
logger.info("All domains have already been processed!")
|
| 91 |
-
return
|
| 92 |
-
|
| 93 |
-
# Configuration
|
| 94 |
-
max_urls_per_domain = 10
|
| 95 |
-
batch_size = 50 # Save every 50 domains
|
| 96 |
-
timeout = 10
|
| 97 |
-
delay_between_domains = 0.5
|
| 98 |
-
|
| 99 |
-
# Process domains in batches
|
| 100 |
-
total_processed = 0
|
| 101 |
-
total_urls_extracted = 0
|
| 102 |
-
domains_with_urls = 0
|
| 103 |
-
batch_data = []
|
| 104 |
-
|
| 105 |
-
for i, domain in enumerate(domains_to_process):
|
| 106 |
-
logger.info(f"Processing {i+1}/{len(domains_to_process)}: {domain}")
|
| 107 |
-
|
| 108 |
-
try:
|
| 109 |
-
# Get current timestamp
|
| 110 |
-
time_updated = datetime.now().isoformat()
|
| 111 |
-
|
| 112 |
-
# Extract URLs from sitemap
|
| 113 |
-
urls = get_urls_from_sitemap(
|
| 114 |
-
domain,
|
| 115 |
-
max_urls=max_urls_per_domain,
|
| 116 |
-
timeout=timeout
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
logger.info(f" Found {len(urls)} URLs from {domain}")
|
| 120 |
-
|
| 121 |
-
# Add domain to batch data (even if no URLs found)
|
| 122 |
-
batch_data.append({
|
| 123 |
-
'domain': domain,
|
| 124 |
-
'urls': urls, # Will be converted to JSON in save function
|
| 125 |
-
'time_updated': time_updated
|
| 126 |
-
})
|
| 127 |
-
|
| 128 |
-
total_urls_extracted += len(urls)
|
| 129 |
-
if urls:
|
| 130 |
-
domains_with_urls += 1
|
| 131 |
-
total_processed += 1
|
| 132 |
-
|
| 133 |
-
# Save batch every N domains
|
| 134 |
-
if (i + 1) % batch_size == 0:
|
| 135 |
-
save_batch_to_csv(batch_data, output_csv)
|
| 136 |
-
logger.info(f"Checkpoint: Processed {total_processed} domains, {domains_with_urls} with URLs, {total_urls_extracted} total URLs")
|
| 137 |
-
batch_data = []
|
| 138 |
-
|
| 139 |
-
# Small delay to be polite
|
| 140 |
-
import time
|
| 141 |
-
time.sleep(delay_between_domains)
|
| 142 |
-
|
| 143 |
-
except KeyboardInterrupt:
|
| 144 |
-
logger.info("\nInterrupted by user. Saving current batch...")
|
| 145 |
-
if batch_data:
|
| 146 |
-
save_batch_to_csv(batch_data, output_csv)
|
| 147 |
-
logger.info(f"Saved progress. Processed {total_processed} domains so far.")
|
| 148 |
-
return
|
| 149 |
-
|
| 150 |
-
except Exception as e:
|
| 151 |
-
logger.error(f"Error processing {domain}: {e}")
|
| 152 |
-
# Still save the domain with empty URL list
|
| 153 |
-
batch_data.append({
|
| 154 |
-
'domain': domain,
|
| 155 |
-
'urls': [],
|
| 156 |
-
'time_updated': datetime.now().isoformat()
|
| 157 |
-
})
|
| 158 |
-
total_processed += 1
|
| 159 |
-
continue
|
| 160 |
-
|
| 161 |
-
# Save any remaining data
|
| 162 |
-
if batch_data:
|
| 163 |
-
save_batch_to_csv(batch_data, output_csv)
|
| 164 |
-
|
| 165 |
-
# Print final summary
|
| 166 |
-
logger.info("\n=== Final Summary ===")
|
| 167 |
-
logger.info(f"Domains processed this run: {total_processed}")
|
| 168 |
-
logger.info(f"Domains with URLs this run: {domains_with_urls}")
|
| 169 |
-
logger.info(f"Total URLs extracted this run: {total_urls_extracted}")
|
| 170 |
-
if total_processed > 0:
|
| 171 |
-
logger.info(f"Average URLs per domain: {total_urls_extracted / total_processed:.1f}")
|
| 172 |
-
|
| 173 |
-
# Show overall statistics from CSV
|
| 174 |
-
if output_csv.exists():
|
| 175 |
-
df = pd.read_csv(output_csv)
|
| 176 |
-
|
| 177 |
-
# Parse URL lists from JSON
|
| 178 |
-
df['urls_parsed'] = df['urls'].apply(json.loads)
|
| 179 |
-
df['url_count'] = df['urls_parsed'].apply(len)
|
| 180 |
-
|
| 181 |
-
total_urls = df['url_count'].sum()
|
| 182 |
-
domains_with_urls_total = (df['url_count'] > 0).sum()
|
| 183 |
-
|
| 184 |
-
logger.info(f"\n=== Overall Statistics ===")
|
| 185 |
-
logger.info(f"Total domains processed: {len(df)}")
|
| 186 |
-
logger.info(f"Domains with URLs: {domains_with_urls_total}")
|
| 187 |
-
logger.info(f"Domains without URLs: {len(df) - domains_with_urls_total}")
|
| 188 |
-
logger.info(f"Total URLs collected: {total_urls}")
|
| 189 |
-
if domains_with_urls_total > 0:
|
| 190 |
-
logger.info(f"Average URLs per domain (with URLs): {total_urls / domains_with_urls_total:.1f}")
|
| 191 |
-
|
| 192 |
-
logger.info(f"\n=== Sample Data ===")
|
| 193 |
-
for _, row in df.head(5).iterrows():
|
| 194 |
-
url_list = json.loads(row['urls'])
|
| 195 |
-
url_count = len(url_list)
|
| 196 |
-
logger.info(f"\n{row['domain']} (updated: {row['time_updated']})")
|
| 197 |
-
if url_count > 0:
|
| 198 |
-
logger.info(f" {url_count} URLs:")
|
| 199 |
-
for url in url_list[:3]:
|
| 200 |
-
logger.info(f" - {url}")
|
| 201 |
-
if url_count > 3:
|
| 202 |
-
logger.info(f" ... and {url_count - 3} more")
|
| 203 |
-
else:
|
| 204 |
-
logger.info(f" No URLs found (empty sitemap or no sitemap)")
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
if __name__ == "__main__":
|
| 208 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
temporary_examples/transform_legit_urls_to_hopsworks.py
DELETED
|
@@ -1,59 +0,0 @@
|
|
| 1 |
-
"""Script to retrieve legitimate URLs from Hopsworks, transform them to match phishing URL format, and upload."""
|
| 2 |
-
|
| 3 |
-
import sys
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import json
|
| 6 |
-
import argparse
|
| 7 |
-
|
| 8 |
-
import pandas as pd
|
| 9 |
-
|
| 10 |
-
project_root = Path(__file__).parent.parent
|
| 11 |
-
sys.path.insert(0, str(project_root / "src"))
|
| 12 |
-
|
| 13 |
-
from phising_detection.utils.hopsworks_utils import (
|
| 14 |
-
connect_to_hopsworks,
|
| 15 |
-
upload_dataframe_to_feature_group,
|
| 16 |
-
get_or_create_feature_group
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
import hopsworks
|
| 21 |
-
|
| 22 |
-
# Connect and read feature group
|
| 23 |
-
project = hopsworks.login()
|
| 24 |
-
fs = project.get_feature_store(name='simbe200_featurestore')
|
| 25 |
-
fg = fs.get_feature_group('scan_progress_legit_urls', version=4)
|
| 26 |
-
df = fg.read()
|
| 27 |
-
|
| 28 |
-
print("Original feature group data:")
|
| 29 |
-
print(df.head(5))
|
| 30 |
-
print(f"\nDataFrame shape: {df.shape}")
|
| 31 |
-
|
| 32 |
-
# Extract all URLs from the JSON-serialized 'urls' column
|
| 33 |
-
all_urls = []
|
| 34 |
-
for _, row in df.iterrows():
|
| 35 |
-
# Deserialize the JSON string to get the list of URLs
|
| 36 |
-
urls_list = json.loads(row['urls'])
|
| 37 |
-
all_urls.extend(urls_list)
|
| 38 |
-
|
| 39 |
-
print(f"\nTotal URLs extracted: {len(all_urls)}")
|
| 40 |
-
|
| 41 |
-
# Create new DataFrame matching phishing URL format
|
| 42 |
-
legit_urls_df = pd.DataFrame({
|
| 43 |
-
'url_id': range(len(all_urls)),
|
| 44 |
-
'url': all_urls,
|
| 45 |
-
'is_phishing': 0 # 0 for legitimate URLs
|
| 46 |
-
})
|
| 47 |
-
|
| 48 |
-
get_or_create_feature_group(project, 'legit_urls_before_scan', version=1)
|
| 49 |
-
upload_dataframe_to_feature_group(
|
| 50 |
-
project=project,
|
| 51 |
-
df=legit_urls_df,
|
| 52 |
-
feature_group_name='legit_urls_before_scan',
|
| 53 |
-
version=1,
|
| 54 |
-
description='Legitimate URLs formatted for phishing detection',
|
| 55 |
-
primary_key=['url_id'],
|
| 56 |
-
event_time=None,
|
| 57 |
-
online_enabled=False
|
| 58 |
-
)
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|