ncclientでNETCONF設定を変更する2 / 4

IOS XE native hostnameの例

次はwritable-runningへ対応する機器でhostnameをBR1へ変更する例である。XMLをlibraryで生成し、read-backまで行う。接続先のknown_hostsとnative moduleの対応が必要になる。

import os
from xml.etree import ElementTree as ET
from ncclient import manager

NC = "urn:ietf:params:xml:ns:netconf:base:1.0"
NS = "http://cisco.com/ns/yang/Cisco-IOS-XE-native"
config = ET.Element(f"{{{NC}}}config")
native = ET.SubElement(config, f"{{{NS}}}native")
ET.SubElement(native, f"{{{NS}}}hostname").text = "BR1"
filter_xml = f'<native xmlns="{NS}"><hostname/></native>'
with manager.connect(
    host=os.environ["LAB_HOST"], port=830,
    username=os.environ["LAB_USER"], password=os.environ["LAB_PASSWORD"],
    hostkey_verify=True, look_for_keys=False, allow_agent=False, timeout=20,
) as m:
    if not any(":writable-running:" in cap for cap in m.server_capabilities):
        raise RuntimeError("Writable running is required")
    m.lock(target="running")
    try:
        m.edit_config(target="running", config=ET.tostring(config, encoding="unicode"), default_operation="merge")
        reply = m.get_config(source="running", filter=("subtree", filter_xml))
        node = ET.fromstring(reply.data_xml).find(f".//{{{NS}}}hostname")
        if node is None or node.text != "BR1":
            raise RuntimeError("Hostname read-back failed")
    finally:
        m.unlock(target="running")

lockが成功した後にtryへ入り、edit/read-backの失敗時もunlockする。context managerは接続を閉じる。lockは排他であり、editに失敗した変更全体のrollback、startup保存とは違う。

学習パスへ
参考資料