# =============== 主流程 ===============
def main():
file_path = "/global/python/app/ip/hp_server.txt" # 将路径存入变量
try:
with open(file_path, "r", encoding="utf-8") as f:
ips = [line.strip() for line in f if line.strip() and not line.startswith("#")]
except FileNotFoundError:
logging.info("❌ 文件 {file_path} 不存在")
sys.exit(1)
logging.info(f"📊 共读取到 {len(ips)} 个有效 IP 地址")
# 后续处理不变...
all_data = []
with requests.Session() as session:
for ip in ips:
logging.info(f"\n🔄 正在处理服务器:{ip}")
base_url = f"https://{ip}"
auth_token = login(session, base_url)
if not auth_token:
logging.info(f"❌ 无法登录 {ip}")
continue
time.sleep(1)
# 采集所有信息(新增 hba_info)
cpu_details = get_cpu_info(session, base_url, auth_token)
memory_details = get_memory_info(session, base_url, auth_token)
memory_summary = summarize_memory(memory_details) if memory_details else {}
bios_info = get_bios_info(session, base_url, auth_token)
serial_info = get_serial_number(session, base_url, auth_token)
power_info = get_power_info(session, base_url, auth_token)
ilo_info = get_ilo_info(session, base_url, auth_token)
raid_disk_map = get_raid_disk_mapping(session, base_url, auth_token)
hba_info = get_hba_info(session, base_url, auth_token)
array_info = get_array_controller_info(session, base_url, auth_token)
network_info = get_network_info(session, base_url, auth_token)
all_data.append({
"ip": ip,
"cpu_details": cpu_details,
"memory_summary": memory_summary,
"bios_info": bios_info,
"serial_info": serial_info,
"power_info": power_info,
"ilo_info": ilo_info,
"raid_disk_map": raid_disk_map,
"hba_info": hba_info,
"array_info": array_info,
"network_info": network_info
})
# 如果没有有效数据,直接退出
if not all_data:
logging.info("⚠️ 没有成功采集到任何服务器数据")
return
max_network_count = max((len(rec["network_info"]) for rec in all_data), default=0)
# ========== 分析 RAID 数据 ==========
RAID_ORDER = ["None", "RAID0", "RAID1", "RAID10", "RAID5", "RAID6"]
def sort_raid_items(raid_disk_map):
def key_func(item):
t = item[0]
if t in RAID_ORDER:
return (0, RAID_ORDER.index(t))
return (1, t)
return sorted(raid_disk_map.items(), key=key_func)
all_sorted_raids = [sort_raid_items(rec["raid_disk_map"]) for rec in all_data]
max_groups = max((len(x) for x in all_sorted_raids), default=0)
max_disks_per_group = {}
for items in all_sorted_raids:
for idx, (_, disks) in enumerate(items):
max_disks_per_group[idx] = max(max_disks_per_group.get(idx, 0), len(disks))
if max_groups == 0:
max_groups = 1
max_disks_per_group[0] = 0
# --- HBA: 计算最大 HBA 卡数量 ---
max_hba_count = max((len(rec["hba_info"]) for rec in all_data), default=0)
# ========== 构建中文表头(完全不变)==========
headers = [
"IP 地址", "型号", "CPU架构", "CPU核心数", "线程数", "CPU基本频率(MHz)", "CPU最大频率(MHz)", "CPU状态",
"CPU缓存1(KB)", "CPU缓存2(KB)", "CPU缓存3(KB)", "CPU数量",
"总内存插槽数", "已启用内存数", "内存总容量(GB)", "内存频率(MHz)", "内存类型", "可用内存插槽数",
"BIOS版本", "序列号", "电源数量", "总功率(W)", "单个电源功率(W)", "当前功耗(W)", "iLO固件版本","阵列卡名称"
]
# 阵列卡表头
# headers.append("阵列卡名称")
# HBA 表头
if max_hba_count > 0:
headers.append("HBA卡数量")
for i in range(1, max_hba_count + 1):
headers.append(f"hba{i}卡名")
else:
headers.append("HBA卡数量")
# 网卡表头
for i in range(1, max_network_count + 1):
headers.append(f"网卡{i}卡名")
# RAID 表头
for g in range(max_groups):
n = g + 1
headers.append(f"RAID组{n}类型")
headers.append(f"RAID组{n}磁盘数量")
for d in range(max_disks_per_group.get(g, 0)):
headers.append(f"RAID组{n}磁盘{d+1}序列号")
headers.append(f"RAID组{n}磁盘{d+1}容量(GB)")
headers.append(f"RAID组{n}磁盘{d+1}介质类型")
# ========== 写入 CSV(替换原 Excel 部分)==========
# 构建带时间戳的文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"/global/python/app/file/HPE_HW_info_{timestamp}.csv"
with open(output_file, "w", newline="", encoding="utf-8-sig") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
for record, sorted_items in zip(all_data, all_sorted_raids):
ip = record["ip"]
cpu_details = record["cpu_details"]
if not cpu_details:
logging.info(f"⚠️ {ip} 未获取到 CPU 信息,跳过")
continue
# === 基础硬件信息(完全不变)===
cpu_count = len(cpu_details)
models = set(get_nested(cpu, "Model") for cpu in cpu_details)
architectures = set(get_nested(cpu, "ProcessorArchitecture") for cpu in cpu_details)
total_cores = get_nested(cpu_details[0], "TotalCores")
total_threads = get_nested(cpu_details[0], "TotalThreads")
rated_speed = max([safe_int(get_nested(cpu, "Oem", "Hpe", "RatedSpeedMHz")) for cpu in cpu_details]) if cpu_details else 0
max_speed = max([safe_int(get_nested(cpu, "MaxSpeedMHz")) for cpu in cpu_details]) if cpu_details else 0
state = get_nested(cpu_details[0], "Status", "State")
caches = get_nested(cpu_details[0], "Oem", "Hpe", "Cache")
cache_values = ["未知"] * 3
if caches and isinstance(caches, list):
for i in range(min(3, len(caches))):
cache_values[i] = str(caches[i].get('MaximumSizeKB', '未知'))
row = [
ip,
", ".join(models) if models else "未知",
", ".join(architectures) if architectures else "未知",
total_cores or "未知",
total_threads or "未知",
rated_speed,
max_speed,
state or "未知",
cache_values[0],
cache_values[1],
cache_values[2],
cpu_count,
record["memory_summary"].get("total_slots", 0),
record["memory_summary"].get("total_enabled", 0),
record["memory_summary"].get("total_capacity_gb", 0),
record["memory_summary"].get("memory_speed_mhz", "未知"),
record["memory_summary"].get("memory_type", "未知"),
record["memory_summary"].get("total_slots", 0) - record["memory_summary"].get("total_enabled", 0),
record["bios_info"].get("BIOS Version", "未知"),
record["serial_info"].get("SerialNumber", "未知"),
record["power_info"].get("电源数量", "未知"),
record["power_info"].get("总功率(W)", "未知"),
record["power_info"].get("单个电源功率(W)", "未知"),
record["power_info"].get("当前功耗(W)", "未知"),
record["ilo_info"].get("Firmware Version", "未知")
]
# === 阵列卡数据 ===
array_list = record["array_info"]
if array_list:
first = array_list[0]
row.append(first["Name"])
else:
row.append("未知")
# === HBA 数据 ===
hba_list = record["hba_info"]
hba_count = len(hba_list)
row.append(hba_count)
for i in range(max_hba_count):
if i < hba_count:
row.append(hba_list[i]["Name"])
else:
row.append("")
# === 网卡数据 ===
network_list = record["network_info"]
for i in range(max_network_count):
if i < len(network_list):
row.append(network_list[i]["Name"])
else:
row.append("")
# === RAID 数据 ===
for g in range(max_groups):
if g < len(sorted_items):
raid_type, disks = sorted_items[g]
row.append(raid_type)
row.append(len(disks))
max_d = max_disks_per_group.get(g, 0)
for d in range(max_d):
if d < len(disks):
disk = disks[d]
cap_gb = round(disk["CapacityBytes"] / (1024**3), 0) if disk["CapacityBytes"] else 0
row.extend([disk["SerialNumber"], cap_gb, disk["MediaType"]])
else:
row.extend(["", "", ""])
else:
row.append("")
row.append("")
max_d = max_disks_per_group.get(g, 0)
for _ in range(max_d):
row.extend(["", "", ""])
writer.writerow(row)
logging.info(f"\n✅ 所有服务器信息已成功写入 CSV 文件:{output_file}")
我怎么把取到的数据直接放数据库,而不是execl表格中
最新发布