本文目录导读:

- 方法一:Linux Bash 脚本(生成服务器硬件/OS配置清单)
- 方法二:Python 脚本(更复杂、结构化的配置清单)
- 方法三:PowerShell 脚本(Windows 配置清单)
- 方法四:批量生成多个服务器的清单(Ansible + 模板)
- 总结建议
这里为您提供几种常用的脚本方法,用于快速生成配置清单,我会根据不同的场景(服务器、网络设备、项目文件)给出对应的脚本示例。
由于没有指定具体的配置对象,我假设最常见的需求是生成服务器/主机的配置清单(如IP、CPU、内存、磁盘)。
Linux Bash 脚本(生成服务器硬件/OS配置清单)
适用场景: 快速收集多台Linux服务器的CPU、内存、磁盘、IP等信息,输出为CSV或表格。
脚本示例: generate_server_inventory.sh
#!/bin/bash
# 配置清单文件
OUTPUT_FILE="server_inventory_$(date +%Y%m%d).csv"
# CSV表头
echo "Hostname,IP_Address,CPU_Cores,Memory_GB,Disk_Total_GB,Disk_Used_Percent,OS_Kernel" > "$OUTPUT_FILE"
# 获取本机信息(如果需要采集远程服务器,可结合ssh循环)
HOSTNAME=$(hostname)
IP=$(hostname -I | awk '{print $1}')
CPU=$(nproc)
MEM=$(free -h | awk '/^Mem:/ {print $2}')
DISK_TOTAL=$(df -h / | awk 'NR==2 {print $2}')
DISK_USED=$(df -h / | awk 'NR==2 {print $5}')
OS=$(uname -r)
# 写入CSV行
echo "$HOSTNAME,$IP,$CPU,$MEM,$DISK_TOTAL,$DISK_USED,$OS" >> "$OUTPUT_FILE"
echo "✅ 配置清单已生成:$OUTPUT_FILE"
如何使用:
- 在服务器上执行
bash generate_server_inventory.sh - 生成
server_inventory_20231027.csv文件,可用Excel直接打开。
Python 脚本(更复杂、结构化的配置清单)
适用场景: 需要将配置输出为JSON、YAML或Excel文件,或需要连接多个不同的设备/云API。
脚本示例: generate_config_inventory.py
import socket
import platform
import psutil
import json
import datetime
def get_system_info():
"""收集详细的系统配置"""
info = {
"timestamp": datetime.datetime.now().isoformat(),
"hostname": socket.gethostname(),
"os": platform.system(),
"os_version": platform.version(),
"cpu": {
"physical_cores": psutil.cpu_count(logical=False),
"total_cores": psutil.cpu_count(logical=True),
"max_frequency_mhz": psutil.cpu_freq().max if psutil.cpu_freq() else "N/A"
},
"memory": {
"total_gb": round(psutil.virtual_memory().total / (1024**3), 2),
"available_gb": round(psutil.virtual_memory().available / (1024**3), 2)
},
"disks": []
}
# 收集磁盘信息
for partition in psutil.disk_partitions():
try:
usage = psutil.disk_usage(partition.mountpoint)
info["disks"].append({
"device": partition.device,
"mountpoint": partition.mountpoint,
"total_gb": round(usage.total / (1024**3), 2),
"used_gb": round(usage.used / (1024**3), 2),
"free_gb": round(usage.free / (1024**3), 2)
})
except PermissionError:
continue
return info
def main():
# 生成JSON格式清单
config = get_system_info()
output_file = f"config_inventory_{datetime.date.today()}.json"
with open(output_file, 'w') as f:
json.dump(config, f, indent=2)
print(f"✅ JSON 配置清单已生成: {output_file}")
# 可选:生成Markdown格式的可读报告
with open(f"config_report_{datetime.date.today()}.md", 'w') as f:
f.write(f"# 配置清单 - {config['hostname']}\n\n")
f.write(f"**生成时间**: {config['timestamp']}\n\n")
f.write("## CPU 信息\n")
f.write(f"- 物理核心: {config['cpu']['physical_cores']}\n")
f.write(f"- 逻辑核心: {config['cpu']['total_cores']}\n\n")
f.write("## 内存信息\n")
f.write(f"- 总计: {config['memory']['total_gb']} GB\n")
f.write(f"- 可用: {config['memory']['available_gb']} GB\n\n")
f.write("## 磁盘信息\n")
for disk in config['disks']:
f.write(f"- {disk['device']} ({disk['mountpoint']}): {disk['total_gb']} GB\n")
print(f"✅ 可读报告已生成: config_report_{datetime.date.today()}.md")
if __name__ == "__main__":
main()
运行前需要安装: pip install psutil
PowerShell 脚本(Windows 配置清单)
适用场景: 生成Windows服务器的配置清单。
# generate_inventory.ps1
# 输出文件
$outputFile = "inventory_$(Get-Date -Format 'yyyyMMdd').csv"
# 获取系统信息
$computerInfo = Get-CimInstance Win32_ComputerSystem
$osInfo = Get-CimInstance Win32_OperatingSystem
$diskInfo = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"
# 创建自定义对象
$inventoryObject = [PSCustomObject]@{
HostName = $computerInfo.Name
Manufacturer = $computerInfo.Manufacturer
Model = $computerInfo.Model
TotalRAM_GB = [math]::Round($computerInfo.TotalPhysicalMemory / 1GB, 2)
OS = $osInfo.Caption
OSArchitecture = $osInfo.OSArchitecture
LastBootTime = $osInfo.LastBootUpTime
DiskC_Size_GB = [math]::Round(($diskInfo | Where-Object {$_.DeviceID -eq "C:"}).Size / 1GB, 2)
DiskC_Free_GB = [math]::Round(($diskInfo | Where-Object {$_.DeviceID -eq "C:"}).FreeSpace / 1GB, 2)
IPAddress = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -ne "Loopback"}).IPAddress -join ", "
}
# 导出到CSV
$inventoryObject | Export-Csv -Path $outputFile -NoTypeInformation
Write-Host "✅ 配置清单已生成: $outputFile"
使用方法:
- 以管理员身份打开PowerShell
- 执行
.\generate_inventory.ps1
批量生成多个服务器的清单(Ansible + 模板)
适用场景: 需要从CMDB或配置文件模板批量生成大量设备的配置。
示例: 使用Jinja2模板生成多台nginx服务器的配置清单
模板文件 server_config.j2:
# 服务器配置清单 - {{ server_name }}
# 生成时间: {{ ansible_date_time.iso8601 }}
--------------------------------------------------
主机名: {{ server_name }}
IP地址: {{ ip_address }}
角色: {{ role }}
操作系统: {{ os }}
CPU: {{ cpu_cores }} 核心
内存: {{ memory_gb }} GB
磁盘: {{ disk_gb }} GB
--------------------------------------------------
生成脚本 generate_from_template.sh:
#!/bin/bash
# 定义服务器列表 (也可以从 JSON/CSV 读取)
cat > servers_data.json << 'EOF'
[
{"server_name": "web01", "ip_address": "192.168.1.10", "role": "Web Server", "os": "Ubuntu 22.04", "cpu_cores": 4, "memory_gb": 16, "disk_gb": 100},
{"server_name": "db01", "ip_address": "192.168.1.20", "role": "Database", "os": "CentOS 7", "cpu_cores": 8, "memory_gb": 32, "disk_gb": 500},
{"server_name": "cache01", "ip_address": "192.168.1.30", "role": "Redis Cache", "os": "Alpine 3.18", "cpu_cores": 2, "memory_gb": 8, "disk_gb": 50}
]
EOF
# 使用Python解析JSON并生成清单
python3 -c "
import json
with open('servers_data.json') as f:
servers = json.load(f)
for server in servers:
filename = f\"{server['server_name']}_config.txt\"
with open(filename, 'w') as out:
out.write(f\"\"\"# 服务器配置清单 - {server['server_name']}
# 生成时间: $(date)
--------------------------------------------------
主机名: {server['server_name']}
IP地址: {server['ip_address']}
角色: {server['role']}
操作系统: {server['os']}
CPU: {server['cpu_cores']} 核心
内存: {server['memory_gb']} GB
磁盘: {server['disk_gb']} GB
--------------------------------------------------
\"\"\")
print(f'✅ 生成: {filename}')
"
总结建议
| 你的需求 | 推荐方法 |
|---|---|
| 快速查看当前服务器配置 | Linux Bash 或 PowerShell |
| 生成结构化数据供程序解析 | Python (JSON/YAML) |
| 批量生成多个设备的配置 | Ansible + Jinja2模板 |
| 生成网络设备(交换机/路由器) | Telnet/SSH + Expect/Paramiko |
| 生成云资源清单(AWS/Azure) | 各云厂商CLI工具 + 脚本封装 |
如果你告诉我具体需要生成什么设备/服务的配置清单(比如网络交换机、Docker容器、数据库、云资源),我可以提供更精准的脚本。