理论看完,直接上实战。
目标:用 Python + telnetlib,自动登录华为设备,实现无人值守登录。
步骤 1:设备配置 Telnet
[Huawei] user-interface vty 0 4
[Huawei-ui-vty0-4] authentication-mode password
[Huawei-ui-vty0-4] set authentication password simple Huawei@123
[Huawei-ui-vty0-4] protocol inbound telnet
[Huawei-ui-vty0-4] user privilege level 15
[Huawei-ui-vty0-4] quit
[Huawei] telnet server enable
[Huawei] interface GE1/0/0
[Huawei-GE1/0/0] ip address 192.168.10.10 24
步骤 2:手动 Telnet 确认流程
telnet 192.168.10.10 → 提示 Password → 输入密码 → 进入<Huawei>视图。
步骤 3:编写 Python 代码
import telnetlib
host = '192.168.10.10'
password = 'Huawei@123'
tn = telnetlib.Telnet(host)
tn.read_until(b'Password:')
tn.write(password.encode('ascii') + b'\n')
print(tn.read_until(b'<Huawei>').decode('ascii'))
tn.close()
步骤 4:运行验证
代码执行结果,和手动登录完全一致。
这意味着:你已经实现了第一个网络自动化小工具。
在此基础上,你只需要加几行代码,就能实现自动创建 VLAN、批量配置接口、批量巡检等更强的功能。