超級干貨:手把手教你如何寫Python腳本并且在網絡設備上執行,舉一反三!
VSole2023-02-03 10:03:40
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.
>>> import comware
>>> comware.Transfer('tftp', '192.168.1.26', 'test.cfg', 'flash:/test.cfg', user='', password='')
<comware.Transfer object at 0xb7eab0e0>
導入單個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。
exit()
Python典型配置舉例
組網需求
使用Python腳本,下載main.cfg和backup.cfg兩個配置文件到設備上,并設置為下次主用配置文件和備用配置文件。
組網圖
Python典型配置舉例組網圖:

配置步驟
在PC上使用寫字板編輯Python腳本文件test.py,內容如下:
#!usr/bin/python
import comware
comware.Transfer('tftp', '192.168.1.26', 'main.cfg', 'flash:/main.cfg')
comware.Transfer('tftp', '192.168.1.26', 'backup.cfg', 'flash:/backup.cfg')
comware.CLI('startup saved-configuration flash:/main.cfg main ;startup saved-configuration flash:/backup.cfg backup')
通過TFTP將test.py文件下載到設備上
<Sysname> tftp 192.168.1.26 get test.py
執行Python腳本文件
<Sysname> python flash:/test.py <Sysname>startup saved-configuration flash:/main.cfg main Please wait...... Done. <Sysname>startup saved-configuration flash:/backup.cfg backup Please wait...... Done.
驗證結果
使用display startup命令查看下次啟動文件已經變為main.cfg和backup.cfg。
<Sysname> display startup Current startup saved-configuration file: flash:/startup.cfg Next main startup saved-configuration file: flash:/main.cfg Next backup startup saved-configuration file: flash:/backup.cfg
VSole
網絡安全專家