diff --git a/backend/app/services/network_service.py b/backend/app/services/network_service.py index f72557c..5914752 100644 --- a/backend/app/services/network_service.py +++ b/backend/app/services/network_service.py @@ -14,9 +14,9 @@ class NetworkService: @staticmethod def calculate_total_ips(cidr: str) -> int: - """计算网段的总IP数量""" + """计算网段中实际分配的IP数量(排除网络地址和广播地址)""" network = ipaddress.ip_network(cidr, strict=False) - return network.num_addresses + return network.num_addresses - 2 if network.num_addresses > 2 else network.num_addresses @staticmethod def get_network_addresses(cidr: str) -> List[str]: diff --git a/backend/scripts/fix_network_total_ips.py b/backend/scripts/fix_network_total_ips.py new file mode 100644 index 0000000..8e579d6 --- /dev/null +++ b/backend/scripts/fix_network_total_ips.py @@ -0,0 +1,39 @@ +""" +修复已有网段的 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()