在开始华为CE系列交换机的自动化配置之前,我们需要先搭建好开发环境并理解几个关键概念。我刚开始接触这个领域时,最头疼的就是各种术语和工具的选择,这里我会用最直白的语言帮你理清楚。
首先说说NETCONF协议,你可以把它想象成网络设备的"遥控器"。传统的CLI命令行就像手动操作面板,而NETCONF提供了标准化的编程接口。华为CE系列交换机从V100R005版本开始就完整支持NETCONF 1.0/1.1协议,这也是我们选择它的原因。
开发环境需要准备:
安装依赖库很简单,用pip一行命令搞定:
bash复制pip install ncclient paramiko
这里有个坑我踩过:不同版本的ncclient对华为设备支持程度不同。经过多次测试,我发现0.6.13版本最稳定,建议指定安装这个版本:
bash复制pip install ncclient==0.6.13
在编写Python脚本前,我们需要先给交换机做些"热身运动"——配置SSH和NETCONF服务。这个过程就像给设备装驱动程序,不装好后面什么都做不了。
以CE12800为例,具体配置步骤如下:
bash复制<HUAWEI> system-view
[HUAWEI] sysname CE1
[CE1] interface Vlanif 1
[CE1-Vlanif1] ip address 172.16.1.2 24
[CE1-Vlanif1] quit
bash复制[CE1] aaa
[CE1-aaa] local-user python password cipher Huawei@123
[CE1-aaa] local-user python service-type ssh
[CE1-aaa] local-user python level 3
[CE1-aaa] quit
bash复制[CE1] ssh user python authentication-type password
[CE1] ssh user python service-type snetconf
[CE1] snetconf server enable
[CE1] netconf
[CE1-netconf] protocol inbound ssh port 830
这里有个细节要注意:华为设备默认使用830端口提供NETCONF服务,但需要先用SSH配置好用户权限。我遇到过因为漏掉snetconf server enable命令导致连接失败的坑,折腾了半天才发现。
现在进入最核心的部分——编写自动化脚本。我把整个过程拆解成几个关键步骤,每个步骤都会配上详细解释和实际代码。
首先用Paramiko库配置NETCONF服务用户,这部分相当于"准备工作":
python复制from paramiko import SSHClient, AutoAddPolicy
def ssh_config(host, username, password):
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy)
ssh.connect(host, username=username, password=password)
# 发送配置命令
channel = ssh.invoke_shell()
channel.send('system-view\n')
channel.send('aaa\n')
channel.send('local-user netconf password cipher Huawei@123\n')
channel.send('local-user netconf service-type ssh\n')
channel.send('local-user netconf level 3\n')
channel.send('quit\n')
channel.send('ssh user netconf authentication-type password\n')
channel.send('ssh user netconf service-type snetconf\n')
channel.send('snetconf server enable\n')
channel.send('netconf\n')
channel.send('protocol inbound ssh port 830\n')
time.sleep(3) # 等待命令执行
ssh.close()
这段代码做了三件事:
核心配置部分使用ncclient库,这是与交换机"对话"的关键:
python复制from ncclient import manager
def configure_interface(host, port, user, password):
with manager.connect(host=host, port=port, username=user,
password=password, hostkey_verify=False,
device_params={'name':'huawei'}) as m:
config = """
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp">
<interfaces>
<interface operation="merge">
<ifName>LoopBack0</ifName>
<ifDescr>Config by NETCONF</ifDescr>
<ifmAm4>
<am4CfgAddrs>
<am4CfgAddr operation="create">
<ifIpAddr>1.1.1.1</ifIpAddr>
<subnetMask>255.255.255.255</subnetMask>
</am4CfgAddr>
</am4CfgAddrs>
</ifmAm4>
</interface>
</interfaces>
</ifm>
</config>"""
m.edit_config(target='running', config=config)
这里有几个技术要点:
device_params必须指定为'huawei',这是华为设备的专用参数把前面两部分组合起来,加上异常处理:
python复制import time
from paramiko import SSHClient, AutoAddPolicy
from ncclient import manager
def main():
host = '172.16.1.2'
ssh_user = 'python'
ssh_pass = 'Huawei@123'
netconf_user = 'netconf'
netconf_pass = 'Huawei@123'
try:
# 初始化NETCONF环境
print("正在配置NETCONF服务...")
ssh_config(host, ssh_user, ssh_pass)
# 通过NETCONF配置接口
print("开始配置Loopback接口...")
configure_interface(host, 830, netconf_user, netconf_pass)
print("配置成功完成!")
except Exception as e:
print(f"配置失败: {str(e)}")
if __name__ == '__main__':
main()
在实际项目中,我遇到过各种稀奇古怪的问题,这里分享几个典型case和解决方法:
问题1:NETCONF连接被拒绝
snetconf server enable问题2:XML配置报错
问题3:权限不足
display this确认配置这里有个实用技巧:华为设备支持获取YANG模型,可以用来验证配置有效性:
python复制with manager.connect(...) as m:
print(m.get_schema('huawei-ifm'))
经过几个项目的实战,我总结出一些提升效率的方法:
批量配置技巧
使用模板引擎批量生成配置,比如Jinja2:
python复制from jinja2 import Template
template = Template('''
<config>
<ifm xmlns="http://www.huawei.com/netconf/vrp">
{% for interface in interfaces %}
<interface operation="merge">
<ifName>{{ interface.name }}</ifName>
<ifmAm4>
<am4CfgAddrs>
<am4CfgAddr operation="create">
<ifIpAddr>{{ interface.ip }}</ifIpAddr>
<subnetMask>{{ interface.mask }}</subnetMask>
</am4CfgAddr>
</am4CfgAddrs>
</ifmAm4>
</interface>
{% endfor %}
</ifm>
</config>
''')
interfaces = [
{'name': 'LoopBack0', 'ip': '1.1.1.1', 'mask': '255.255.255.255'},
{'name': 'LoopBack1', 'ip': '2.2.2.2', 'mask': '255.255.255.255'}
]
config = template.render(interfaces=interfaces)
配置验证机制
在推送配置前先做dry-run验证:
python复制try:
m.validate(source='running') # 验证当前配置
m.edit_config(...) # 执行真实配置
m.commit() # 提交配置
except Exception as e:
m.discard_changes() # 回滚配置
日志记录建议
添加详细日志记录,方便排查问题:
python复制import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='netconf.log'
)
logger = logging.getLogger('netconf')
logger.info('开始配置交换机 %s', host)
在实际项目中,我发现华为CE系列交换机对NETCONF的支持相当稳定,但XML配置的复杂度确实比CLI高。建议先从简单接口配置开始,逐步过渡到复杂业务配置。配置过程中多使用display netconf session命令查看会话状态,这对排查连接问题很有帮助。