4-2 netmiko库获取设备节点信息
恢复上节课的状态
下载上节课做好的eNSP工程,因为软件的导入bug,需要重做部分内容和验证。
⏬下载地址: eNSP工程-unit4-一些节点开启lldp发现.zip
解压缩,双击.topo工程入口文件导入,提示“网卡丢失”点击确定。验证物理机与设备互通。
一方面重做Cloud设备的映射,因为192.168.56.1的虚拟网卡导入失败。
另一方面验证ipdis ip int br,ip没上去的概率也挺高。对应2-1内容。S0设备上验证与物理机互通,windows powershell中。
ping 192.168.56.100S0设备验证ssh服务
display ssh server status display ssh user-information zhangsan如果返回信息不正常重做3-1内容,命令多可以复制粘贴。(观察到极小概率有同学这两行命令状态正确但关于vty的几行命令失败。)
设备分别改名S0、S1、S2,与Cloud设备相连的是S0。
<huawei>sy [huawei]sysname S0 # 每个设备都需要操作 [S0]S0、S1、S2所有设备服务端llDP服务需要手动开启
[S0]lldp enable # 每个设备都需要操作S0查看邻居信息
display lldp neighbor brief
<Huawei>display ip interface brief
*down: administratively down
^down: standby
(l): loopback
(s): spoofing
The number of interface that is UP in Physical is 2
The number of interface that is DOWN in Physical is 1
The number of interface that is UP in Protocol is 2
The number of interface that is DOWN in Protocol is 1
Interface IP Address/Mask Physical Protocol
MEth0/0/1 unassigned down down
NULL0 unassigned up up(s)
Vlanif1 192.168.56.100/24 up up
<Huawei>display ssh server status
SSH version :1.99
SSH connection timeout :60 seconds
SSH server key generating interval :0 hours
SSH authentication retries :3 times
SFTP server :Disable
Stelnet server :Enable
Scp server :Disable
<Huawei>display ssh user-information zhangsan
User Name : zhangsan
Authentication-type : password
User-public-key-name : -
User-public-key-type : -
Sftp-directory : -
Service-type : stelnet
Authorization-cmd : No
<Huawei>ping 192.168.56.1
PING 192.168.56.1: 56 data bytes, press CTRL_C to break
Reply from 192.168.56.1: bytes=56 Sequence=1 ttl=128 time=30 ms
Reply from 192.168.56.1: bytes=56 Sequence=2 ttl=128 time=30 ms
Reply from 192.168.56.1: bytes=56 Sequence=3 ttl=128 time=10 ms
Reply from 192.168.56.1: bytes=56 Sequence=4 ttl=128 time=50 ms
Reply from 192.168.56.1: bytes=56 Sequence=5 ttl=128 time=30 ms
--- 192.168.56.1 ping statistics ---
5 packet(s) transmitted
5 packet(s) received
0.00% packet loss
round-trip min/avg/max = 10/30/50 ms
netmiko库
netmiko是paramiko的衍生模块,但更为完善。不需要time休眠,不需要命令后\n,自动提取打印回显内容。
安装
pip install netmiko
初步连接
import csv
import netmiko
device = {
'device_type': 'huawei',
'ip': '192.168.56.100',
'username': 'zhangsan',
'password': 'Huawei@123'
}
with netmiko.ConnectHandler(**device) as conn:
output = conn.send_command('display lldp neighbor brief')
print(output.splitlines())
# 处理数据,csv处理回显字符串为下节课所需格式,略。
输出结果,结果为列表,第一行表头,后面每行是一个节点数据。
D:\PycharmProjects\eNSP-connection\.venv\Scripts\python.exe D:\PycharmProjects\unit2\4.py
['Local Intf Neighbor Dev Neighbor Intf Exptime', 'GE0/0/1 - 0a00-2700-0009 3345 ', 'GE0/0/2 S1 GE0/0/1 109 ', 'GE0/0/3 S2 GE0/0/1 98 ']
Process finished with exit code 0
Python基础复习 字符串处理
# 字符串是可迭代序列
for c in 'hello':
print(c)
# Pycharm注释快捷键ctrl+/,选中上面的代码行,注释掉,以进行下面代码效果。
# 列表是可迭代序列
for i in ['he', 'll', 'o']:
print(i)
# 列表切片,索引从0开始左闭右开,比循环写法更简单
raw = [1, 2, 3, 4, 5]
new = raw[0:3]
print(new)
# 元祖tuple
跟列表非常像,支持循环和切片,但不可修改,值在声明时确定。用来存配置信息会比列表更好,以避免项目复杂时不小心修改了存配置信息的变量。
tup = ('小明', '男', 13)
print(tup)
# 很多数据是二维数组或列表套字典结构
ll = [
[1, 2, 3],
[a, b, c]
]
for l in ll:
print(l)
for i in l:
print(i)
students = [
{'name': '小明', 'age': 13, gender: '男'},
{'name': '小红', 'age': 14, gender: '女'},
{'name': '小李', 'age': 15, gender: '男'}
]
for stu in students:
print(stu)
print(stu['name'], end='')
print(stu['age'], end='')
print(stu['gender'], end='')
print()
# 三引号可以括住包含换行的多行字符串,而不需要\n拼接
long_string = """
select count(id) from tablename
where age=13
group by gender;
"""
字符串常用方法,可以在交互式命令行中测试
'abc-abc-abc'.split('-')
[1, 2, 3].join('-')
'abc'.upper()
'1'.isdigital()
处理一个列表,处理后的信息加入新列表,非常常用的操作
new_list = []
raw_list = ['小明', '小红']
for i in raw_list:
new_i = i.replace('小', '大')
new_list.append(new_i)
print(new_list)
处理节点连接信息
题目:已知得到的节点信息,为下节做准备
data = [
'Local Intf Neighbor Dev Neighbor Intf Exptime',
'GE0/0/1 - 0a00-2700-0009 3345 ',
'GE0/0/2 S1 GE0/0/1 109 ',
'GE0/0/3 S2 GE0/0/1 98 '
]
要求处理为下面的格式
data = {
('S0', 'GE0/0/1'): ('Cloud', 'GE0/0/1'),
('S0', 'GE0/0/2'): ('S1', 'GE0/0/1'),
('S0', 'GE0/0/3'): ('S2', 'GE0/0/1'),
}
output = """
Local Intf Neighbor Dev Neighbor Intf Exptime
GE0/0/1 - 0a00-2700-0009 3345
GE0/0/2 S1 GE0/0/1 109
GE0/0/3 S2 GE0/0/1 98
"""
import csv
from io import StringIO
reader = csv.reader(StringIO(output), delimiter=' ')
data = []
for row in reader:
# 去除任意个数空格,每段值返回为列表的一项
filtered_row = list(filter(None, row))
if len(filtered_row) < 4 or filtered_row[0] == "Local":
# 去除首行和空行
continue
else:
# 前两列
data.append(filtered_row[:3])
print(data) # [['GE0/0/1', '-', '0a00-2700-0009'], ['GE0/0/2', 'S1', 'GE0/0/1'], ['GE0/0/3', 'S2', 'GE0/0/1']]
new_data = []
for row in data:
tup1 = ('S0', row[0])
tup2 = (row[1], row[2])
dic = {
tup1,
tup2
}
new_data.append(dic)
print(new_data) # [{('S0', 'GE0/0/1'), ('-', '0a00-2700-0009')}, {('S1', 'GE0/0/1'), ('S0', 'GE0/0/2')}, {('S0', 'GE0/0/3'), ('S2', 'GE0/0/1')}]
26 五月 2025