第302篇:Python 基础:网络工程师的第一行代码
关键词
Python 基础、网络工程师编程、Python 变量、循环、条件判断、函数、文件操作、文本解析
一、为什么要学 Python
Python 是网络工程师的第一编程语言:
┌──────────────────────────────────────────┐
│ 1. 语法简单,门槛低 │
│ ┌─ 类英语语法,易读易写 │
│ ├─ 不需要编译,交互式运行 │
│ └─ 适合非计算机专业的工程师 │
│ │
│ 2. 生态丰富 │
│ ┌─ Netmiko/NAPALM:网络设备操作 │
│ ├─ Jinja2:配置模板 │
│ ├─ Paramiko:SSH 库 │
│ ├─ requests:HTTP API │
│ ├─ textfsm/ntc-templates:回显解析 │
│ └─ Ansible(底层 Python 实现) │
│ │
│ 3. 跨平台 │
│ ┌─ Windows/Linux/Mac 都支持 │
│ ├─ 脚本可移植 │
│ └─ 与网络设备交互无缝 │
│ │
│ 学习目标:不需要学全 Python │
│ 只需要:能写脚本批量操作网络设备即可 │
└──────────────────────────────────────────┘
二、环境搭建
Python 开发环境搭建:
1. 安装 Python(https://python.org)
┌─ 下载 Python 3.9+(推荐 3.11 或 3.12)
├─ 安装时勾选 "Add Python to PATH"
└─ 验证:python --version
2. 安装 VS Code(推荐 IDE)
┌─ 下载 Visual Studio Code
├─ 安装 Python 扩展
└─ 安装 Remote SSH(可选,在 Linux 环境编码)
3. 虚拟环境(推荐)
┌─ 创建:python -m venv myenv
├─ 激活(Windows):myenv\Scripts\activate
├─ 激活(Mac/Linux):source myenv/bin/activate
└─ 安装包:pip install 包名
4. 安装常用库(一次性)
python -m pip install netmiko paramiko napalm
python -m pip install jinja2 textfsm
python -m pip install pyyaml requests
三、Python 基础语法
3.1 变量与数据类型
# ─── 变量赋值 ───
device_name = "Leaf-01" # 字符串
mgmt_ip = "192.168.1.1" # 字符串
port_count = 48 # 整数
bandwidth_gbps = 100.5 # 浮点数
is_online = True # 布尔值
vlan_list = [10, 20, 30, 40] # 列表
# ─── 字符串操作 ───
hostname = "Leaf-01"
print(f"设备名: {hostname}") # f-string,推荐
print("设备名: " + hostname) # 拼接
print("设备名: %s" % hostname) # %格式化(旧)
# ─── 列表操作 ───
vlans = [10, 20, 30]
vlans.append(40) # 添加元素:[10,20,30,40]
vlans.remove(10) # 删除元素:[20,30,40]
first_vlan = vlans[0] # 索引取值:20
last_vlan = vlans[-1] # 最后一个:40
# ─── 字典(键值对)───
device = {
"name": "Leaf-01",
"ip": "192.168.1.1",
"role": "leaf",
"vlans": [10, 20, 30],
"interfaces": {
"GE1/0/1": {"status": "up", "vlan": 10},
"GE1/0/2": {"status": "down", "vlan": 20}
}
}
print(device["name"]) # 取值:Leaf-01
print(device["interfaces"]["GE1/0/1"]["status"]) # up
device["role"] = "spine" # 修改值
3.2 条件判断
# ─── if/elif/else ───
interface_status = "up"
if interface_status == "up":
print("接口正常")
elif interface_status == "down":
print("接口故障,需要检查")
else:
print("接口状态未知")
# ─── 逻辑运算符 ───
vlan_id = 100
if vlan_id > 0 and vlan_id <= 4094:
print("VLAN ID 合法")
elif vlan_id == 0 or vlan_id > 4094:
print("VLAN ID 范围非法")
# ─── in 运算符(判断是否在列表内)───
allowed_vlans = [10, 20, 30, 100, 200]
if vlan_id in allowed_vlans:
print(f"VLAN {vlan_id} 允许创建")
else:
print(f"VLAN {vlan_id} 不在规划范围内")
3.3 循环
# ─── for 循环(遍历列表)───
vlans = [10, 20, 30, 100, 200]
for vlan in vlans:
print(f"创建 VLAN {vlan}")
# ─── range 循环(固定次数)───
for i in range(1, 5):
print(f"端口 10GE1/0/{i}")
# ─── while 循环(条件控制)───
retry_count = 0
success = False
while retry_count < 3 and not success:
print(f"第 {retry_count + 1} 次尝试连接...")
success = True # 模拟成功
retry_count += 1
# ─── 遍历字典 ───
interfaces = {"GE1/0/1": "up", "GE1/0/2": "down", "GE1/0/3": "up"}
for intf, status in interfaces.items():
print(f"{intf} 状态: {status}")
3.4 函数
# ─── 定义函数 ───
def get_interface_description(intf_name, vlan_id):
"""生成接口描述(函数注释)"""
description = f"Server-{intf_name}-VLAN{vlan_id}"
return description
# 调用函数
desc = get_interface_description("GE1/0/1", 100)
print(desc) # Server-GE1/0/1-VLAN100
# ─── 带默认参数的函数 ───
def configure_vlan(vlan_id, vlan_name="未命名", vlan_status="active"):
print(f"创建 VLAN {vlan_id}, 名称: {vlan_name}, 状态: {vlan_status}")
configure_vlan(100) # 使用默认参数
configure_vlan(200, "DATA_VLAN") # 部分覆盖
configure_vlan(300, "VOICE_VLAN", "suspend") # 全覆盖
# ─── 返回值 ───
def check_ip_format(ip):
"""简单检查 IP 格式"""
parts = ip.split(".")
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit() or int(part) > 255:
return False
return True
result = check_ip_format("192.168.1.1")
print(f"IP 格式 {'正确' if result else '错误'}")
3.5 文件操作
# ─── 读取文件 ───
with open("config.txt", "r") as f:
content = f.read() # 全部读取
# lines = f.readlines() # 逐行读取为列表
# for line in f: # 逐行遍历
# print(line.strip())
# ─── 写入文件 ───
config_lines = [
"vlan 100",
" name DATA_VLAN",
"vlan 200",
" name VOICE_VLAN"
]
with open("output.cfg", "w") as f:
for line in config_lines:
f.write(line + "\n")
# ─── 追加写入 ───
with open("output.cfg", "a") as f:
f.write("vlan 300\n")
f.write(" name MGMT_VLAN\n")
四、第一个网络脚本
# ─── connect_device.py:连接到网络设备 ───
from netmiko import ConnectHandler
# 设备信息
device = {
"device_type": "huawei",
"host": "192.168.1.1",
"username": "admin",
"password": "Huawei@123",
"port": 22,
}
def get_device_info(dev):
"""连接设备并获取基本信息"""
try:
# 连接设备
connection = ConnectHandler(**dev)
print(f"成功连接到 {dev['host']}")
# 执行命令
hostname = connection.send_command("display current-configuration | include sysname")
version = connection.send_command("display version | include version")
# 输出结果
print(f"设备名: {hostname.strip()}")
print(f"版本: {version.strip()}")
# 断开连接
connection.disconnect()
return True
except Exception as e:
print(f"连接失败: {e}")
return False
# 执行
if __name__ == "__main__":
get_device_info(device)
五、学习建议
Python 学习建议(针对网络工程师):
1. 不要学全 Python
┌─ 只学需要的 20%(语法+库使用)
├─ 不用学面向对象、多线程等高级特性
└─ 边用边学,做中学
2. 从模仿开始
┌─ 先复制别人的脚本(GitHub 开源项目)
├─ 理解后修改成自己的
└─ 逐步独立编写
3. 写脚本的黄金原则
┌─ 先手动执行一次(知道命令和结果)
├─ 写脚本时先处理正常情况
└─ 再加错误处理
4. 善用帮助
dir() # 查看对象的方法
help() # 查看函数/模块的帮助文档
官方文档 + Stack Overflow + ChatGPT
5. 虚拟环境是必须的
┌─ 不同项目用不同虚拟环境
├─ 避免包版本冲突
└─ requirements.txt 记录依赖
总结
| 关键点 | 说明 |
|---|---|
| Python 适合网工 | 语法简单、生态丰富、跨平台 |
| 基础必备 | 变量/字符串/列表/字典 |
| 条件循环 | if/for/while 控制程序流程 |
| 函数 | 封装重复操作,提高复用 |
| 文件操作 | 读写配置文件和日志 |
| 第一个脚本 | netmiko 连接设备执行命令 |
思考
- 安装 Python 后,如何验证安装成功?
- 列表和字典有什么区别?什么时候用列表什么时候用字典?
- f-string 相比字符串拼接有什么优势?
- with open() 语法有什么好处?
- 虚拟环境有什么作用?如何创建和激活?
下篇预告:第303篇 - Paramiko 库:SSH 连接网络设备,使用 Paramiko 库远程登录和执行命令。