Last active
October 20, 2022 18:56
-
-
Save qiuchengxuan/b0623417b2b2d6e5dddc7715a143e4df to your computer and use it in GitHub Desktop.
Access Huawei switch via NETCONF with python script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
import code | |
from lxml import etree | |
from lxml.builder import E | |
from ncclient import manager | |
_, ip, user, passwd = sys.argv | |
netconf = manager.connect(host=ip, port=830, username=user, password=passwd, | |
hostkey_verify=False, allow_agent=False, | |
look_for_keys=False, device_params={'name': 'huawei'}) | |
IETF_XMLNS_BASE = 'urn:ietf:params:xml:ns:netconf:base:1.0' | |
XMLNS_HUAWEI = 'http://www.huawei.com/netconf/vrp' | |
HUAWEI_NSMAP = {'xmlns': XMLNS_HUAWEI, 'format-version': '1.0', 'content-version': '1.0'} | |
def netconf_get(lxml_filter): | |
xml = etree.tostring(lxml_filter) | |
print xml | |
return netconf.get(('subtree', xml)).xml | |
def netconf_edit(*elements): | |
xml_config = etree.tostring(E.config(*elements, xmlns=IETF_XMLNS_BASE)) | |
print xml_config | |
return netconf.edit_config(target='running', config=xml_config) | |
def classifier_filter(name): | |
return E.qos(E.qosCbQos( | |
E.qosClassifiers(E.qosClassifier(E.classifierName(name))) | |
), HUAWEI_NSMAP) | |
def behavior_filter(name): | |
return E.qos(E.qosCbQos(E.qosBehaviors( | |
E.qosBehavior(E.behaviorName(name)) | |
)), HUAWEI_NSMAP) | |
def acl_filter(name): | |
return E.acl(E.aclGroups(E.aclGroup(E.aclNumOrName(name))), HUAWEI_NSMAP) | |
def qos_policy_filter(name): | |
return E.qos(E.qosCbQos(E.qosPolicys(E.qosPolicy(E.policyName(name)))), HUAWEI_NSMAP) | |
def fans_filter(): | |
return E.devm(E.fans(E.fan(E.position(), E.speed())), HUAWEI_NSMAP) | |
def applied_qos_policy_filter(ifname=None, name=None, direction=None): | |
elements = [] | |
if name: | |
elements.append(E.policyName(name)) | |
if ifname: | |
assert direction | |
return E.qos(E.qosIfQoss(E.qosIfPolicyApplys( | |
E.qosIfPolicyApply(E.ifName(ifname), E.direction(direction), *elements) | |
)), HUAWEI_NSMAP) | |
def interfaces_filter(): | |
return E.ifm(E.interfaces(E.interface(E.ifIndex(), E.ifName())), HUAWEI_NSMAP) | |
def used_classifier_filter(): | |
return E.qos(E.qosCbQos(E.qosPolicys(E.qosPolicy(E.qosPolicyNodes(E.qosPolicyNode(E.classifierName()))))), HUAWEI_NSMAP) | |
def netconf_cli(cmd): | |
if isinstance(cmd, str): | |
cmd = [cmd] | |
cmd_reqs = [] | |
for i in xrange(len(cmd)): | |
cmd_reqs.append(E.cmd(E.id(str(i)), E.cmdline(cmd[i]))) | |
xml_cli = etree.tostring(E('execute-cli', *cmd_reqs, xmlns=IETF_XMLNS_BASE)) | |
print xml_cli | |
code.interact(local=locals()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is much needed , thanks mate :)