字典与集合
字典(dict)是键值映射,适合表示主机资产、服务配置、API 响应;集合(set)用于去重与集合运算,例如合并多来源 IP、找出异常主机交集。
字典:主机资产表
# 以主机名为 key,属性为嵌套 dict
inventory = {
"web-01": {"ip": "10.0.1.10", "role": "web", "env": "prod"},
"web-02": {"ip": "10.0.1.11", "role": "web", "env": "prod"},
"db-01": {"ip": "10.0.2.20", "role": "db", "env": "prod"},
}
# 读取与默认值
ip = inventory["web-01"]["ip"]
region = inventory["web-01"].get("region", "default") # key 不存在不报错
# 安全更新
inventory.setdefault("cache-01", {})["ip"] = "10.0.3.30"
遍历:
for hostname, meta in inventory.items():
print(f"{hostname} -> {meta['ip']} ({meta['role']})")
# 只要生产环境 web 节点
prod_web = [
h for h, m in inventory.items()
if m.get("role") == "web" and m.get("env") == "prod"
]
print(prod_web)
运维场景:端口 → 进程映射
# 模拟 netstat 解析结果:端口 -> 监听进程
port_process = {
22: "sshd",
80: "nginx",
443: "nginx",
6379: "redis-server",
}
def lookup_service(port: int) -> str:
return port_process.get(port, "unknown")
for port in [80, 8080, 443]:
print(f"端口 {port}: {lookup_service(port)}")
字典推导式
# 主机名 -> IP 的扁平映射
host_ip = {name: meta["ip"] for name, meta in inventory.items()}
# 过滤:只保留 db 角色
db_hosts = {k: v for k, v in inventory.items() if v["role"] == "db"}
print(host_ip)
print(db_hosts)
集合:去重与集合运算
# 三台机器上跑出的异常 IP(有重复)
from_web = {"10.0.0.5", "10.0.0.8", "10.0.0.5"}
from_lb = {"10.0.0.8", "10.0.0.12"}
# 去重合并
all_bad = from_web | from_lb # 并集
both = from_web & from_lb # 交集:两边都报
only_web = from_web - from_lb # 差集
print("全部异常:", sorted(all_bad))
print("共同异常:", sorted(both))
print("仅 web 发现:", sorted(only_web))
用集合判断成员(平均 O(1)),适合白名单/黑名单:
ALLOWED_CIDRS = {"10.0.0.0/8", "172.16.0.0/12"} # 简化示例用字符串
blocked_ips = {"192.168.1.100", "10.0.0.5"}
whitelist = {"10.0.0.5", "10.0.0.6"}
safe = blocked_ips - whitelist
print("需拦截:", safe)
嵌套结构:模拟 API 响应
# 类似 K8s / 监控 API 返回的 JSON 结构(Python 中已是 dict/list)
response = {
"code": 0,
"data": {
"items": [
{"name": "pod-a", "status": "Running", "restarts": 0},
{"name": "pod-b", "status": "CrashLoopBackOff", "restarts": 12},
]
},
}
items = response["data"]["items"]
unhealthy = [p["name"] for p in items if p["status"] != "Running"]
print("异常 Pod:", unhealthy)
访问深层 key 时,生产代码可用 .get() 链或专用库(后续 JSON 章节会展开)。
实战:合并多来源主机清单
ansible_hosts = {"web-01", "web-02", "db-01"}
cmdb_hosts = {"web-02", "db-01", "cache-01"}
in_ansible_not_cmdb = ansible_hosts - cmdb_hosts
in_cmdb_not_ansible = cmdb_hosts - ansible_hosts
print("Ansible 有、CMDB 无:", in_ansible_not_cmdb)
print("CMDB 有、Ansible 无:", in_cmdb_not_ansible)
小结
- dict:主机元数据、配置项、API 字段映射
- set:IP/主机名去重、白名单、多集合对比
- 大型嵌套 dict 注意用
.get()避免KeyError
下一章学习 条件判断与循环,实现告警分级与批量巡检逻辑。