1、需求
使用ncclient抓取juniper設備端口狀態。
2、操作環境
操作系統:Linux CentOS 7.4
python版本:python 3.8
網絡設備:Juniper mx204
編輯器:vscode
3、整體代碼
#!/usr/bin/env python
import sys
from ncclient import manager
def connect(host, port, user, password):
conn = manager.connect(host=host,
port=port,
username=user,
password=password,
timeout=60,
device_params={'name': 'junos'},
hostkey_verify=False)
rpc_command = "<get-interface-information><terse/></get-interface-information>"
response = conn.rpc(rpc_command)
interface_name = response.xpath('//physical-interface/name')
interface_status = response.xpath('//physical-interface/oper-status')
for name, status in zip(interface_name, interface_status):
name = name.text.split('\\n')[1]
status = status.text.split('\\n')[1]
print(name,status)
if __name__ == '__main__':
connect('172.26.3.169', 22, 'user', 'passwd')
執行結果
et-0/0/0 up
lc-0/0/0 up
pfe-0/0/0 up
pfh-0/0/0 up
et-0/0/1 up
et-0/0/2 down
et-0/0/3 down
xe-0/1/0 up
xe-0/1/1 up
xe-0/1/2 down
xe-0/1/3 up
xe-0/1/4 up
xe-0/1/5 up
xe-0/1/6 up
xe-0/1/7 up
4、代碼詳解
import sys
from ncclient import manager
導入ncclient的manager方法
def connect(host, port, user, password):
conn = manager.connect(host=host,
port=port,
username=user,
password=password,
timeout=60,
device_params={'name': 'junos'},
hostkey_verify=False)
創建connect函數,使用manager.connect連接juniper設備
需要把device_params={'name': 'junos'},改爲junos
rpc_command = "<get-interface-information><terse/></get-interface-information>"
juniper支持rpc command,不需要像華爲那樣找XML文檔,直接登陸設備輸入show命令加管道符和display xml rpc就能得到rpc command,如下所示:
show interfaces terse | display xml rpc
<rpc-reply xmlns:junos="<http://xml.juniper.net/junos/19.4R0/junos>">
<rpc>
<get-interface-information>
<terse/>
</get-interface-information>
</rpc>
<cli>
<banner></banner>
</cli>
</rpc-reply>
response = conn.rpc(rpc_command)
interface_name = response.xpath('//physical-interface/name')
interface_status = response.xpath('//physical-interface/oper-status')
response = conn.rpc(rpc_command)發起rpc請求,並接受response。
並用xpath將返回的內容解析,XPath 是一門在 XML 文檔中查找信息的語言,
基礎內容可直接查看https://www.runoob.com/xpath/xpath-intro.html
這倆我們主要使用2個表達式
interface_name = response.xpath('//physical-interface/name')
//physical-interface,不考慮節點位置,全量內容直接查找physical-interface對應的位置(箭頭一),/name查找下一層級(剪頭二)的<name>節點。
這時如果我們直接打印interface_name
print(interface_name)
print(type(interface_name))
結果是
[<Element name at 0x7f4502f44c08>]
<class 'list'>
返回的數據類型是list,這個很好理解,因爲返回的XML內容中同樣的標籤(比如接口名稱)其實有很多(比如1口、2口、3口),所以需要返回list給我們。
但是這個list內容無法直接就打印出來,因爲xpath抓取的是標籤屬性值,而非標籤內容,如果要打印標籤內容需要.text。
for name, status in zip(interface_name, interface_status):
name = name.text.split('\\n')[1]
status = status.text.split('\\n')[1]
print(name,status)
for循環將name和status提取出來,zip() 函數用於將可迭代的對象作爲參數,這裏需要將對象中對應的元素打包成一個個元組,讓每一個接口名稱==接口狀態對應上。
剛纔提過,想獲取標籤內容需要.text方法,
name = name.text返回的結果是類似(['', 'et-0/0/0', ''])的列表,這裏我們需要做下分片處理,並獲取索引[1]的內容。
if __name__ == '__main__':
connect('172.26.3.169', 22, 'user', 'passwd')
主程序就沒啥可說的了。
以上只是juniper-ncclient的簡單應用,實際生產環境還有更多的用處,每個環境場景不用,可以做不同的處理。