

很多人学 Python:
但真正开始写自动化脚本时:
❌ 代码越来越乱
❌ 重复代码越来越多
❌ 无法管理设备信息
而真正的自动化核心:
技术 | 作用 |
|---|---|
函数 | 封装功能 |
列表 list | 批量处理 |
字典 dict | 管理设备数据 |
👉 本质:
函数 = 自动化能力数据结构 = 批量管理能力
👉 函数本质:
“把一段代码封装起来,重复调用”
print("正在检测 192.168.1.1")
print("正在检测 192.168.1.2")
print("正在检测 192.168.1.3")
👉 问题:
def check_ip(ip):
print(f"正在检测 {ip}")
check_ip("192.168.1.1")
check_ip("192.168.1.2")
👉 这就是:
自动化思想的开始
def 函数名():
代码
def hello():
print("Hello Network Engineer")
hello()
👉 参数:
让函数更灵活
def ping(ip):
print(f"正在 ping {ip}")
ping("192.168.1.1")
def connect(ip, port):
print(f"连接 {ip}:{port}")
connect("192.168.1.1", 22)
👉 return:
函数处理后的结果
def add(a, b):
return a + b
result = add(3, 5)
print(result)
👉 类似:
def ssh_connect(ip, port=22):
print(f"连接 {ip}:{port}")
👉 不写端口时默认22
def test():
ip = "192.168.1.1"
👉 只能函数内部使用
ip = "192.168.1.1"
👉 整个程序都能用
因为自动化脚本:
本质都是:
👉 “封装成函数后重复调用”
👉 列表:
存储多个数据
ips = [
"192.168.1.1",
"192.168.1.2",
"192.168.1.3"
]
for ip in ips:
print(ip)
👉 这就是:
批量处理设备的核心
ips.append("192.168.1.4")
ips.remove("192.168.1.2")
print(len(ips))
print(ips[0])
ips = [
"192.168.1.1",
"192.168.1.2",
"192.168.1.3"
]
for ip in ips:
print(f"正在检测 {ip}")
👉 字典:
键值对数据结构
类似:
设备名 -> IP
device = {
"name": "R1",
"ip": "192.168.1.1",
"port": 22
}
print(device["ip"])
device["port"] = 2222
device["vendor"] = "Huawei"
for key, value in device.items():
print(key, value)
字典非常适合:
数据 | 示例 |
|---|---|
设备信息 | IP / 用户名 |
接口状态 | up/down |
配置参数 | VLAN/OSPF |
👉 自动化脚本最常见结构:
devices = [
{
"name": "R1",
"ip": "192.168.1.1"
},
{
"name": "SW1",
"ip": "192.168.1.2"
}
]
for device in devices:
print(device["name"], device["ip"])
👉 这已经是:
真正自动化运维脚本的雏形
✔ 存储设备IP ✔ 批量检测 ✔ 输出状态
devices = [
{"name": "R1", "ip": "192.168.1.1"},
{"name": "SW1", "ip": "192.168.1.2"},
{"name": "FW1", "ip": "192.168.1.3"}
]
def check_device(device):
print(f"正在检测设备: {device['name']}")
print(f"IP地址: {device['ip']}")
print("状态: 在线")
print("-" * 30)
for device in devices:
check_device(device)
传统网工:
登录设备 → 查看状态 → 下一台
自动化思维:
设备列表 → 循环 → 函数处理
👉 本质:
“人操作” → “程序批量执行”
错误:
def test():
print(ip)
记忆方法:
类型 | 特点 |
|---|---|
list | 多个数据 |
dict | 键值关系 |
👉 多写:
for item in data:
✔ 会写函数
✔ 会传参数
✔ 会使用 return
✔ 会使用 list
✔ 会使用 dict
✔ 会遍历数据
| Flask | 运维平台开发 | | Requests | API调用 |