""" 修复已有网段的 total_ips 字段:将 num_addresses 改为 hosts 数量(排除网络地址和广播地址) 用法: cd /root/ipam/backend && source venv/bin/activate && python scripts/fix_network_total_ips.py """ import sys import os # 确保能找到 app 模块 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from app.core.database import SessionLocal from app.models.network import Network from app.services.network_service import NetworkService def fix_total_ips(): db = SessionLocal() try: networks = db.query(Network).all() fixed = 0 for net in networks: correct = NetworkService.calculate_total_ips(net.cidr) actual_hosts = len(list(NetworkService.get_network_addresses(net.cidr))) if net.total_ips != correct: print(f" [{net.cidr:20s}] {net.total_ips:>5} -> {correct:>5} (hosts={actual_hosts})") net.total_ips = correct fixed += 1 db.commit() print(f"\n✅ 已修复 {fixed} 个网段") except Exception as e: db.rollback() print(f"❌ 错误: {e}") finally: db.close() if __name__ == "__main__": fix_total_ips()