使用netconf配置华为设备

实验目的:

公司有一台CE12800的设备,管理地址位172.16.1.2,现在需要编写自动化脚本,通过SSH登陆到设备上配置netconf协议的用户名,密码以及netconf服务,并且通过netconf协议将设备的loopback0接口IP地址配置为1.1.1.1/32。

实验拓扑:

实验步骤:

步骤1:将本地电脑和ensp的设备进行桥接,桥接配置如下图所示:

步骤2:配置交换机的IP地址。

<HUAWEI>system-view immediately

[HUAWEI]sysname CE1

[CE1]interface  Vlanif 1

[CE1-Vlanif1]ip address 172.16.1.2 24

[CE1-Vlanif1]quit

[CE1]interface  g1/0/0

[CE1-GE1/0/0]undo  shutdown

测试本地的cmd窗口与CE1设备的连通性。

C:\Users\xxx>ping 172.16.1.2

正在 Ping 172.16.1.2 具有 32 字节的数据:

来自 172.16.1.2 的回复: 字节=32 时间=19ms TTL=255

来自 172.16.1.2 的回复: 字节=32 时间=7ms TTL=255

来自 172.16.1.2 的回复: 字节=32 时间=5ms TTL=255

来自 172.16.1.2 的回复: 字节=32 时间=7ms TTL=255

172.16.1.2 的 Ping 统计信息:

    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),

往返行程的估计时间(以毫秒为单位):

最短 = 5ms,最长 = 19ms,平均 = 9ms

步骤3:配置CE1的SSH登陆。

(1)创建SSH登陆的账号

[CE1]aaa

[CE1-aaa]local-user python password cipher Huawei@123

[CE1-aaa]local-user python user-group manage-ug

[CE1-aaa]local-user python service-type ssh

[CE1-aaa]local-user python level 3

(2)在CE1设备配置SSH用户的认证方式和服务类型。

[CE1]ssh user python

[CE1]ssh user python authentication-type password

[CE1]ssh user python service-type stelnet

(3)配置vty用于的登陆方式,及开启stenet服务

[CE1]stelnet server  enable

Info: Succeeded in starting the STelnet server.

[CE1]user-interface vty 0 4

[CE1-ui-vty0-4]authentication-mode  aaa

[CE1-ui-vty0-4]protocol  inbound ssh

[CE1-ui-vty0-4]user  privilege level  3

[CE1-ui-vty0-4]q

步骤4:编写python代码

完整代码:

from paramiko import  SSHClient,AutoAddPolicy

from ncclient import manager

from ncclient import operations

from time import  sleep

service_ip = '172.16.1.2'

ssh_user = 'python'

ssh_pass = 'Huawei@123'

netconf_user = 'netconf'

netconf_pass = 'Huawei@123'

port = '830'

XMLS = '''<config>

      <ethernet xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">

        <ethernetIfs>

          <ethernetIf operation="merge">

            <ifName>GE1/0/2</ifName>

            <l2Enable>disable</l2Enable>

          </ethernetIf>

        </ethernetIfs>

      </ethernet>

      <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">

        <interfaces>

          <interface operation="merge">

            <ifName>Loopback0</ifName>

            <ifDescr>Config by NETCONF</ifDescr>

            <ifmAm4>

              <am4CfgAddrs>

                <am4CfgAddr operation="create">

                  <subnetMask>255.255.255.255</subnetMask>

                  <addrType>main</addrType>

                  <ifIpAddr>1.1.1.1</ifIpAddr>

                </am4CfgAddr>

              </am4CfgAddrs>

            </ifmAm4>

          </interface>

        </interfaces>

      </ifm>

    </config>'''

class datacom():

    def __init__(self,ip,username,password):

        self.ip = ip

        self.username = username

        self.password = password

        self.ssh = self.ssh_connect()

    def ssh_connect(self):

        ssh = SSHClient()

        ssh.set_missing_host_key_policy(AutoAddPolicy)

        ssh.connect(self.ip,username=self.username,password=self.password)

        return ssh

    def ssh_config(self):

        shell = self.ssh.invoke_shell()

        shell.send('n\n')

        f = open("config_netconf.txt")

        cmd = f.readlines()

        for i in cmd:

            shell.send(i)

            sleep(2)

        dis_this = shell.recv(999999).decode()

        print(dis_this)

        self.ssh.close()

def netconf_connect(host, port, user, password):

    return manager.connect(host=host,

                       port=port,

                       username=user,

                       password=password,

                       hostkey_verify = False,

                       device_params={'name': "huawei"},

                       allow_agent = False,

                       look_for_keys = False)

if __name__ == '__main__':

    joinlabs = datacom(service_ip,ssh_user,ssh_pass)

    joinlabs.ssh_config()

    netconf = netconf_connect(service_ip,port,netconf_user,netconf_pass)

    netconf.edit_config(target='running',config=XMLS)

步骤5: 编译器执行

步骤6:查看输出结果

Warning: The initial password poses security risks.

The password needs to be changed. Change now? [Y/N]:n

Info: The max number of VTY users is 5, the number of current VTY users online is 1, and total number of terminal users online is 1.

      The current login time is 2023-11-09 20:09:21.

      The last login time is 2023-11-09 19:40:14 from 172.16.1.1 through SSH.

<CE1>system-view immediately

Enter system view, return user view with return command.

[CE1]aaa

[CE1-aaa]local-user netconf password irreversible-cipher Huawei@123

Info: A new user is added.

[CE1-aaa]local-user netconf service-type ssh

[CE1-aaa]local-user netconf level 3

[CE1-aaa]quit

[CE1]ssh user netconf authentication-type password

Info: Succeeded in adding a new SSH user.

[CE1]ssh user netconf service-type snetconf

[CE1]snetconf server enable

Info: Succeeded in starting the SNETCONF server on SSH port 22.

[CE1]netconf

[CE1-netconf]protocol inbound ssh port 830

Info: Succeeded in starting the ssh port 830 service.

[CE1-netconf]quit

[CE1]

进程已结束,退出代码0

登陆CE1查看loopback0接口配置

[CE1]interface  LoopBack 0

[CE1-LoopBack0]dis this

interface LoopBack0

 description Config by NETCONF

 ip address 1.1.1.1 255.255.255.255

代码解析:

  1. 在pycharm的本项目的python文件的同一目录下创建txt文档,用于配置netconf服务。

配置文件如下:

system-view immediately

aaa

local-user netconf password irreversible-cipher Huawei@123

local-user netconf service-type ssh

local-user netconf level 3

quit

ssh user netconf authentication-type password

ssh user netconf service-type snetconf

snetconf server enable

netconf

protocol inbound ssh port 830

quit

  1. 导入库

from paramiko import  SSHClient,AutoAddPolicy

from ncclient import manager

from ncclient import operations

from time import  sleep

导入paramiko用于SSH远程登陆设备进行配置,导入ncclinet用于netconf的连接和配置。

  1. 定义变量

service_ip = '172.16.1.2'

ssh_user = 'python'

ssh_pass = 'Huawei@123'

netconf_user = 'netconf'

netconf_pass = 'Huawei@123'

port = '830'

将需要登陆设备的ip地址,ssh登陆用户名、密码以及netconf的用户名和密码定义为变量。

(4)构建XML配置文件

XMLS = '''<config>

      <ethernet xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">

        <ethernetIfs>

          <ethernetIf operation="merge">

            <ifName>GE1/0/2</ifName>

            <l2Enable>disable</l2Enable>

          </ethernetIf>

        </ethernetIfs>

      </ethernet>

      <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">

        <interfaces>

          <interface operation="merge">

            <ifName>Loopback0</ifName>

            <ifDescr>Config by NETCONF</ifDescr>

            <ifmAm4>

              <am4CfgAddrs>

                <am4CfgAddr operation="create">

                  <subnetMask>255.255.255.255</subnetMask>

                  <addrType>main</addrType>

                  <ifIpAddr>1.1.1.1</ifIpAddr>

                </am4CfgAddr>

              </am4CfgAddrs>

            </ifmAm4>

          </interface>

        </interfaces>

      </ifm>

    </config>'''

NETCONF通过XML文件传递配置信息。XML是一种非常常用的文本格式,可以<>不断嵌套展开数据。完整的NETCONF会话有传输层、消息层、操作层和内容层。在当前XML配置文件中传递的仅包含操作层和内容层。

本例中的XML文件意为将接口loopback 0接口IP地址改为1.1.1.1/32。

(5)定义构造函数

class datacom():

    def __init__(self,ip,username,password):

        self.ip = ip

        self.username = username

        self.password = password

        self.ssh = self.ssh_connect()

(6)定义def ssh_connect():方法,用于建立SSH连接,登陆网络设备

    def ssh_connect(self):

        ssh = SSHClient()

        ssh.set_missing_host_key_policy(AutoAddPolicy)

        ssh.connect(self.ip,username=self.username,password=self.password)

        return ssh

(7)定义def ssh_config():方法,用于登陆设备,进行配置

    def ssh_config(self):

        shell = self.ssh.invoke_shell()

        shell.send('n\n')

        f = open("config_netconf.txt")

        cmd = f.readlines()

        for i in cmd:

            shell.send(i)

            sleep(2)

        dis_this = shell.recv(999999).decode()

        print(dis_this)

        self.ssh.close()

f = open("config_netconf.txt")代表打开文件config_netconf.txt;

cmd = f.readlines() 代表对config_netconf.txt这个文件内容进行逐行的读取;

 for i in cmd:

    shell.send(i)

            sleep(2)

代表定义一个循环语句,将config_netconf.txt的内容输入在设备的命令行,即配置设备的netconf服务。

(8)定义netconf_connect():方法,用于建立netconf连接

def netconf_connect(host, port, user, password):

    return manager.connect(host=host,

                       port=port,

                       username=user,

                       password=password,

                       hostkey_verify = False,

                       device_params={'name': "huawei"},

                       allow_agent = False,

                       look_for_keys = False)

定义函数netconf_connect(host, port, user, password)。函数输入四个参数为NETCONF主机的IP、端口、NETCONF用户名和密码。函数返回ncclient的manager.connect的方法。

manager.connect的作用是建立netconf连接。

(9)运行主函数

if __name__ == '__main__':

    joinlabs = datacom(service_ip,ssh_user,ssh_pass)

    joinlabs.ssh_config()

    netconf = netconf_connect(service_ip,port,netconf_user,netconf_pass)

    netconf.edit_config(target='running',config=XMLS)

首先执行joinlabs.ssh_config(),即调用datacom()这个类下的ssh_config这个方法。并且输入ssh登陆的ip、用户名及密码。

然后再执行netconf = netconf_connect(service_ip,port,netconf_user,netconf_pass)赋值为netconf,输入netconf的参数,建立netconf连接。

最后执行netconf.edit_config(target='running',config=XMLS),将在变量中定义的XMLS这个文件通过edit_config这个方法发生到设备的running配置文件。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/201897.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

小航助学题库蓝桥杯题库c++选拔赛(22年1月)(含题库教师学生账号)

需要在线模拟训练的题库账号请点击 小航助学编程在线模拟试卷系统&#xff08;含题库答题软件账号&#xff09; 需要在线模拟训练的题库账号请点击 小航助学编程在线模拟试卷系统&#xff08;含题库答题软件账号&#xff09;

适用于 Windows 的最佳电脑数据恢复软件是什么?

数据丢失是数字世界中令人不快的一部分&#xff0c;它会在某一时刻影响许多计算机用户。很容易意外删除一些重要文件&#xff0c;这可能会在您努力恢复它们时带来不必要的压力。幸运的是&#xff0c;数据恢复软件可以帮助恢复已删除的文件&#xff0c;即使您没有备份它们。这是…

CONTROLLING VISION-LANGUAGE MODELS FOR MULTI-TASK IMAGE RESTORATION

CONTROLLING VISION-LANGUAGE MODELS FOR MULTI-TASK IMAGE RESTORATION (Paper reading) Ziwei Luo, Uppsala University, ICLR under review(6663), Cited:None, Stars: 350, Code, Paper. 1. 前言 像CLIP这样的视觉语言模型已经显示出对零样本或无标签预测的各种下游任务…

fastadmin 如何引入自己的js

在需要的界面中&#xff1a;如何实例说明&#xff1a; 中<script> function zhuruJs(url) { let temp document.createElement( script ); temp.setAttribute( type, text/javascript" );temp.src urL; document.head . appendChild(temp); zhuruJs(location…

智能优化算法应用:基于哈里斯鹰算法无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于哈里斯鹰算法无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于哈里斯鹰算法无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.哈里斯鹰算法4.实验参数设定5.算法结果6.参考…

【Hydro】SG滤波器纯numpy实现

目录 说明WIKI示例滑动平均卷积系数的推导第一点和最后点的处理scipy.signal中的savgol_filter纯numpy实现的savgol_filterCPP实现的savgol_filter参考文献说明 Savitzky-Golay滤波器(S-G滤波器)是一种在时域和频域上同时进行的滤波方法,它通过局部多项式拟合来平滑信号。这…

ExoPlayer - Failed to initialize OMX.qcom.video.decoder.avc

人莫鉴于流水而鉴于止水&#xff0c;唯止能止众止 1. 背景 使用ExoPlayer&#xff0c;我不信你没遇到过这个问题&#xff1a; java.lang.IllegalArgumentException: Failed to initialize OMX.qcom.video.decoder.avc 详细内容如下图所示&#xff1a; 2. MediaCodec(解码器) …

Android控件全解手册 - 多语言切换完美解决方案(兼容7.0以上版本)

Unity3D特效百例案例项目实战源码Android-Unity实战问题汇总游戏脚本-辅助自动化Android控件全解手册再战Android系列Scratch编程案例软考全系列Unity3D学习专栏蓝桥系列ChatGPT和AIGC &#x1f449;关于作者 专注于Android/Unity和各种游戏开发技巧&#xff0c;以及各种资源分…

MySQL-函数

一、统计函数 CREATE TABLE student (id INT NOT NULL DEFAULT 1,name varchar(20) not null default ,chinese float not null default 0.0,english float not null default 0.0,math float not null default 0.0 );insert into student values (1,曹操,77,89,85);insert int…

Python内置函数与标准库函数的详细解读

一、内置函数与标准库函数的区分 Python 解释器自带的函数叫做内置函数&#xff0c;这些函数可以直接使用&#xff0c;不需要导入某个模块。 Python 解释器也是一个程序&#xff0c;它给用户提供了一些常用功能&#xff0c;并给它们起了独一无二的名字&#xff0c;这些常用功能…

二叉树leetcode(求二叉树深度问题)

today我们来练习三道leetcode上的有关于二叉树的题目&#xff0c;都是一些基础的二叉树题目&#xff0c;那让我们一起来学习一下吧。 https://leetcode.cn/problems/maximum-depth-of-binary-tree/submissions/ 看题目描述是让我们来求出二叉树的深度&#xff0c;我们以第一个父…

【LeetCode刷题】--90.子集II

90.子集II class Solution {public List<List<Integer>> subsetsWithDup(int[] nums) {List<List<Integer>> ans new ArrayList<>();List<Integer> list new ArrayList<>();//排序后便于去重Arrays.sort(nums);dfs(0,nums,ans,lis…

Docker的数据持久化;Docker网络;Dockerfile编写

Docker的数据持久化&#xff1b;Docker网络&#xff1b;Dockerfile编写&#xff1b; 文章目录 Docker的数据持久化&#xff1b;Docker网络&#xff1b;Dockerfile编写&#xff1b;**Docker的数据持久化**1&#xff09;将本地目录映射到容器里2&#xff09;数据卷3&#xff09;将…

聚类分析例题 (多元统计分析期末复习)

例一 动态聚类&#xff0c;K-means法&#xff0c;随机选取凝聚点&#xff08;题目直接给出&#xff09; 已知5个样品的观测值为&#xff1a;1&#xff0c;4&#xff0c;5&#xff0c;7&#xff0c;11。试用K均值法分为两类(凝聚点分别取1&#xff0c;4与1&#xff0c;11) 解&…

JavaScript编程进阶 – Return语句

JavaScript编程进阶 – Return语句 JavaScript Programming Advanced – Return Statement By JacksonML 就像人们习惯的函数一样&#xff0c;总觉得在函数体最后需要一个return语句&#xff0c;标志着函数的结束,就像下面这个函数 theFunc() 那样。 function theFunc() { re…

【Openstack Train安装】八、placement安装

Placement 肩负着这样的历史使命&#xff0c;最早在 Newton 版本被引入到 openstack/nova repo&#xff0c;以 API 的形式进行孵化&#xff0c;所以也经常被称呼为 Placement API。它参与到 nova-scheduler 选择目标主机的调度流程中&#xff0c;负责跟踪记录 Resource Provide…

Vue diff 算法探秘:如何实现快速渲染

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

思维模型 达维多定律

本系列文章 主要是 分享 思维模型&#xff0c;涉及各个领域&#xff0c;重在提升认知。持续创新&#xff0c;引领市场潮流。 1 达维多定律的应用 1.1 达维多定律应用之吉列公司&#xff1a;不断创新的刀片领导者 吉列公司是一家以剃须刀片而闻名的公司。自 1901 年推出首款安…

高级IO—poll,epoll,reactor

高级IO—poll,epoll,reactor 文章目录 高级IO—poll,epoll,reactorpoll函数poll函数接口poll服务器 epollepoll的系统调用epoll_createepoll_ctlepoll_wait epoll的工作原理epoll的工作方式水平触发边缘触发 epoll服务器 reactor poll函数 poll函数是一个用于多路复用的系统调…

C++中的类型转换和异常

C类型转换 类型转换(cast) 是将一种数据类型转换成另一种数据类型。例如&#xff0c;如果将一个整型 值赋给一个浮点类型的变量&#xff0c;编译器会暗地里将其转换成浮点类型。 转换是非常有用的&#xff0c;但是它也会带来一些问题&#xff0c;比如在转换指针时&#xff0c…
最新文章