Migrate data from legacy netkb.csv to SQLite database. Only runs if CSV exists and database is empty.
(self)
| 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)), |
no test coverage detected