如何写Python脚本并且在网络设备上执行

Python简介

Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现了面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想的脚本语言,特别适用于快速的应用程序开发。

在Comware V7系统上可以采用如下方式使用Python:

  • 通过执行Python脚本进行自动化配置系统。
  • 进入Python shell,使用Python2.7版本的命令、标准API或扩展API对设备进行配置。其中,扩展API是Comware对Python进行的扩展,用来方便用户进行系统配置。

本文案例是以H3C厂商为例,其他厂商过程类似。

执行Python脚本文件

请在用户视图下执行本命令,执行Python脚本文件。

python filename

进入Python shell

请在用户视图下执行本命令,进入Python shell

python

导入Comware包以使用扩展API

用户如需使用扩展Python API,必须先导入Comware包。导入时,可选择导入整个Comware包或单个API。

导入整个Comware包并执行扩展API

1.配置步骤

(1)请在用户视图下执行本命令,进入Python shell。

python

(2)导入整个Comware包。

import comware

(3)=执行扩展API。

comware.api

2.配置举例

下例采用API Transfer将TFTP服务器(192.168.1.26)上的文件test.cfg下载到设备上。

<Sysname> python

Python 2.7.3 (default)

[GCC 4.4.1] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from comware import Transfer

>>> Transfer('tftp', '192.168.1.26', 'test.cfg', 'flash:/test.cfg', user='', password='')

<comware.Transfer object at 0xb7e5e0e0>

导入单个API函数并执行该函数

1.配置步骤

(1)请在用户视图下执行本命令,进入Python shell。

python

(2)导入单个API函数。

from comware import api-name

(3)执行扩展API函数。

api-function

2.配置举例

下例采用API Transfer将TFTP服务器(192.168.1.26)上的文件test.cfg下载到设备上。

<Sysname> python

Python 2.7.3 (default)

[GCC 4.4.1] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from comware import Transfer

>>> Transfer('tftp', '192.168.1.26', 'test.cfg', 'flash:/test.cfg', user='', password='')

<comware.Transfer object at 0xb7e5e0e0>

退出Python shell

请在Python shell下执行本命令,退出Python shell。

python0

Python典型配置举例

组网需求

使用Python脚本,下载main.cfg和backup.cfg两个配置文件到设备上,并设置为下次主用配置文件和备用配置文件。

组网图

Python典型配置举例组网图:

组网图

配置步骤

在PC上使用写字板编辑Python脚本文件test.py,内容如下:

python1

通过TFTP将test.py文件下载到设备上

python2

执行Python脚本文件

python3

验证结果

使用display startup命令查看下次启动文件已经变为main.cfg和backup.cfg。

python4
阅读剩余
THE END