MCPcopy Create free account
hub / github.com/PierreGode/Ragnar / _migrate_from_csv

Method _migrate_from_csv

db_manager.py:450–533  ·  view source on GitHub ↗

Migrate data from legacy netkb.csv to SQLite database. Only runs if CSV exists and database is empty.

(self)

Source from the content-addressed store, hash-verified

448 # Clean up any duplicate entries (non-fatal if it fails)
449 try:
450 self.cleanup_duplicate_hosts()
451 except Exception as e:
452 logger.warning(f"Duplicate cleanup skipped: {e}")
453
454 # Ensure legacy hostnames are cleaned up once on startup (non-fatal)
455 try:
456 self.sanitize_all_hostnames()
457 except Exception as e:
458 logger.warning(f"Hostname sanitization skipped: {e}")
459
460 def _migrate_from_csv(self):
461 """
462 Migrate data from legacy netkb.csv to SQLite database.
463 Only runs if CSV exists and database is empty.
464 """
465 if not os.path.exists(self.netkb_csv):
466 logger.debug("No netkb.csv found - skipping migration")
467 return
468
469 # Check if database already has data
470 with self.get_connection() as conn:
471 cursor = conn.cursor()
472 # Verify hosts table exists before querying
473 cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='hosts'")
474 if not cursor.fetchone():
475 logger.warning("hosts table not found - skipping CSV migration")
476 return
477
478 cursor.execute("SELECT COUNT(*) FROM hosts")
479 count = cursor.fetchone()[0]
480
481 if count > 0:
482 logger.debug(f"Database already contains {count} hosts - skipping CSV migration")
483 return
484
485 logger.info(f"Migrating data from {self.netkb_csv} to SQLite...")
486
487 try:
488 with open(self.netkb_csv, 'r', encoding='utf-8') as csvfile:
489 reader = csv.DictReader(csvfile)
490 migrated_count = 0
491
492 for row in reader:
493 try:
494 mac = row.get('MAC', '').strip()
495 if not mac or mac.upper() == 'UNKNOWN':
496 continue
497
498 # Convert CSV row to database format
499 host_data = {
500 'mac': mac,
501 'ip': row.get('IP', '').strip(),
502 'hostname': row.get('Hostname', '').strip(),
503 'vendor': row.get('Vendor', '').strip(),
504 'ports': row.get('Ports', '').strip(),
505 'services': row.get('Services', '').strip() or row.get('Service', '').strip(),
506 'vulnerabilities': row.get('Nmap Vulnerabilities', '').strip(),
507 'alive_count': self._safe_int(row.get('Alive Count', 0)),

Callers 1

_init_databaseMethod · 0.95

Calls 11

get_connectionMethod · 0.95
_safe_intMethod · 0.95
upsert_hostMethod · 0.95
debugMethod · 0.80
cursorMethod · 0.80
warningMethod · 0.80
infoMethod · 0.80
errorMethod · 0.80
executeMethod · 0.45
fetchoneMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected