13c457acb3
问题原因: - calculate_total_ips 使用 network.num_addresses 计算总IP数量 - 该值包含网络地址(第一个IP)和广播地址(最后一个IP) - 而 _create_ip_addresses 使用 hosts() 生成IP列表,排除这两个地址 - 导致 total_ips 比实际存储的IP记录多2个 - 例: /24 显示 256 个IP,实际只有 254 条记录 解决方案: 1. calculate_total_ips 改为 num_addresses - 2(排除网络地址和广播地址) 2. 对于 /31 /32 等没有网络/广播地址的网段,特殊处理 3. 提供 fix_network_total_ips.py 迁移脚本修复已有数据
40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
"""
|
|
修复已有网段的 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()
|