From 9e4c6ee1cf0f249a798e26ccb00199e4a215cfc3 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Thu, 8 Feb 2018 15:29:34 +0800 Subject: [PATCH 1/9] blank --- README.md | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..436a0b1 --- /dev/null +++ b/README.md @@ -0,0 +1,120 @@ +# Forward + [![Build Status](http://192.168.182.52:8080/jenkins/job/Forward/job/forward.4.test.after/badge/icon)](http://192.168.182.52:8080/jenkins/job/Forward/job/forward.4.test.after/) + +--- + +## Introduce 介绍 + +* Forward是一个python模块,提供与目标设备之间的通道封装,基于指令行(Command Lines)的方式实现多数功能的封装,供开发者快速简便调用,屏蔽不同设备上指令差异。 +* 建议使用Forward用于多种(厂家、型号)网络设备的自动化管理场景,可以快速构建出运维场景脚本。 +* Forward is a python module, which provides channel encapsulation between target devices, and realizes most functions encapsulation based on Command Lines. It allows developers to invoke quickly and simply, and screen instructions on different devices. +* We recommend the use of Forward for a variety of (manufacturer, model) network equipment automation management scene, can quickly build the operation and maintenance scenario script. + +--- + +## Installation + +* Building virtual environment (optional) 构建虚拟环境 (可选) + + * 开发者用户推荐,使用pyenv和virtualenv构建纯净的python环境,基于python版本2.7.10 + * We recommend that developer users use pyenv and virtualenv to build a pure Python environment which is based on Python version 2.7.10. + + ```Bash + pyenv virtualenv 2.7.10 forward + pyenv activate forward + ``` + +* Pull 拉取当前版本 + + ```Bash + git clone http://192.168.182.51/promise/forward.git + cd forward + ``` + +* Dependency 安装依赖包 + + ```Bash + pip install -r requirements.txt + ``` + +* Setup 安装 + + ```Bash + python setup.py install + ``` + +--- + +## Getting Started + +* 下方代码段展示了一个简易的forward场景实现,批量连接到两台设备(思科Nexus7018),执行指令并获取结果。 +* The code section below shows a simple forward scenario implementation that is batch connected to two devices (CISCO Nexus7018), executes instructions and gets the results. + + ```Python + from forward import Forward + + new = Forward() + new.addTargets(['192.168.113.1-192.168.113.2'], 'n7018', 'username', 'password') + instances = new.getInstances() + + cisco1 = instances['192.168.113.1'] + cisco2 = instances['192.168.113.2'] + + result1 = cisco1.execute('show version') + result2 = cisco2.execute('show version') + + if result1['status']: + print '[%s] OS version info: %s' % ('cisco1', result1['content']) + if result2['status']: + print '[%s] OS version info: %s' % ('cisco2', result2['content']) + ``` + +* 上述代码段中出现的'cisco1'和'cisco2'就是Forward设备类实例(N7018),不同设备类实例包含的方法可能不同,具体请查阅[类库文档](/docs/class)。 +* The 'cisco1' and 'cisco2' appearing in the above code segment are Forward device class instances (N7018). Different device class instances contain different methods. Please consult the [detailed library documents](/docs/class). + +--- + +## Advanced Usage + +* [初始化 Initialize](/docs/advance/initialize.md) +* [预登陆 PreLogin](/docs/advance/prelogin.md) +* [自定义指令 command](/docs/advance/command.md) + +--- + +## Class + +* Forward目前包含40多种特定型号设备类库,查看详细的[类库文档](/docs/class)。 +* Forward currently contains more than 40 specific type of device class libraries, here to look at the [detailed library documents](/docs/class). + +--- + +## Authors + +* Forward由王喆(Headkarl: azrael-ex@139.com)创建,并且由张其川(cheung kei-chuen: qichuan.zhang@qq.com)、麦艺帆(Leann Mak:leannmak@139.com)、戴声(Shawn.T:shawntai.ds@gmail.com)等多位用户参与贡献,在此衷心感谢每一位。 +* Forward was created by Wang Zhe(Headkarl: azrael-ex@139.com) and contributed by many users, such as Zhang Qichuan(cheung kei-chuen: qichuan.zhang@qq.com), Mai Yi Fan(Leann Mak:leannmak@139.com) and Dai Sheng(Shawn.T:shawntai.ds@gmail.com), and sincerely thanks each one. + +--- + +## License + +* GNU General Public License v3.0 +* See [COPYING](COPYING) to see the full text. + +--- + +## Branch Info + +* RC,Releases和Stables分支都以版本号+各种鱼类命名。 +* devel分支对应正在开发的分支。 +* alpha分支对应一个早期的内部测试版本。 +* RC,Releases and Stables are named after the version number plus any kind of fish. +* The devel branch corresponds to the release actively under development. +* The alpha branch corresponds to a early release thich is used for In-House test. + +--- + +## Version Info + +* 在[版本记录](/docs/VersionInfo.md)中查看所有历史记录,开源前的版本更新仅可以看到记录。 +* Looking at all the history records in [Version Info](/docs/VersionInfo.md), the pre - source version updates can only see the records. From 37e59b4ef313dab8b365fda2bbfe964f0647805b Mon Sep 17 00:00:00 2001 From: Zhang Qi-chuan Date: Thu, 8 Feb 2018 15:33:34 +0800 Subject: [PATCH 2/9] test --- test | 1 + 1 file changed, 1 insertion(+) create mode 100644 test diff --git a/test b/test new file mode 100644 index 0000000..7898192 --- /dev/null +++ b/test @@ -0,0 +1 @@ +a From 6378770f028aefb5e3ccb793cf39e2bbb508349c Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Thu, 8 Feb 2018 15:46:18 +0800 Subject: [PATCH 3/9] init forward: rc_0.0.1_crownfish --- .gitignore | 45 ++ .python-version | 1 + .travis.yml | 23 + COPYING | 674 +++++++++++++++++++++++++ docs/Authors.md | 3 + docs/BranchInfo.md | 7 + docs/GettingStarted.md | 24 + docs/Installation.md | 21 + docs/License.md | 3 + docs/VersionInfo.md | 57 +++ docs/advance/command.md | 102 ++++ docs/advance/initialize.md | 30 ++ docs/advance/prelogin.md | 22 + docs/class/README.md | 64 +++ docs/class/sshv1/README.md | 0 docs/class/sshv1/maipu/README.md | 0 docs/class/sshv1/maipu/s3300.md | 0 docs/class/sshv2/README.md | 0 docs/class/sshv2/baer/README.md | 0 docs/class/sshv2/baer/sr7750.md | 0 docs/class/sshv2/baer/sr7950.md | 0 docs/class/sshv2/brocade/README.md | 0 docs/class/sshv2/brocade/vlb.md | 0 docs/class/sshv2/cisco/README.md | 0 docs/class/sshv2/cisco/adx03100.md | 0 docs/class/sshv2/cisco/asa.md | 0 docs/class/sshv2/cisco/asr1006.md | 0 docs/class/sshv2/cisco/c2960.md | 0 docs/class/sshv2/cisco/c4510.md | 0 docs/class/sshv2/cisco/c6506.md | 0 docs/class/sshv2/cisco/c6509.md | 0 docs/class/sshv2/cisco/n5548.md | 0 docs/class/sshv2/cisco/n5596.md | 0 docs/class/sshv2/cisco/n7010.md | 0 docs/class/sshv2/cisco/n7018.md | 0 docs/class/sshv2/cisco/n7710.md | 0 docs/class/sshv2/cisco/n7718.md | 0 docs/class/sshv2/depp/README.md | 0 docs/class/sshv2/depp/f1000.md | 0 docs/class/sshv2/f5/README.md | 0 docs/class/sshv2/f5/f510000.md | 0 docs/class/sshv2/fenghuo/README.md | 0 docs/class/sshv2/fenghuo/s5800.md | 0 docs/class/sshv2/fortinet/README.md | 0 docs/class/sshv2/fortinet/fg1240.md | 0 docs/class/sshv2/fortinet/fg3040.md | 0 docs/class/sshv2/fortinet/fg3950.md | 0 docs/class/sshv2/huawei/README.md | 0 docs/class/sshv2/huawei/e1000e.md | 0 docs/class/sshv2/huawei/e8000e.md | 0 docs/class/sshv2/huawei/e8160e.md | 0 docs/class/sshv2/huawei/ne40ex16.md | 0 docs/class/sshv2/huawei/ne40ex3.md | 0 docs/class/sshv2/huawei/s5328.md | 0 docs/class/sshv2/huawei/s5352.md | 0 docs/class/sshv2/huawei/s8512.md | 0 docs/class/sshv2/huawei/s9303.md | 0 docs/class/sshv2/huawei/s9306.md | 0 docs/class/sshv2/huawei/s9312.md | 0 docs/class/sshv2/linux/README.md | 0 docs/class/sshv2/linux/bclinux7.md | 0 docs/class/sshv2/raisecom/README.md | 0 docs/class/sshv2/raisecom/r3048g.md | 0 docs/class/sshv2/zte/README.md | 0 docs/class/sshv2/zte/m6000.md | 0 docs/class/sshv2/zte/zx5952.md | 0 docs/class/telnet/README.md | 0 docs/class/telnet/juniper/README.md | 0 docs/class/telnet/juniper/mx960.md | 0 docs/class/telnet/juniper/srx3400.md | 0 docs/class/telnet/venustech/README.md | 0 docs/class/telnet/venustech/usg1000.md | 0 lib/forward/__init__.py | 75 +++ lib/forward/devclass/__init__.py | 0 lib/forward/devclass/adx03100.py | 17 + lib/forward/devclass/asa.py | 49 ++ lib/forward/devclass/asr1006.py | 29 ++ lib/forward/devclass/baseBaer.py | 16 + lib/forward/devclass/baseBrocade.py | 16 + lib/forward/devclass/baseCisco.py | 317 ++++++++++++ lib/forward/devclass/baseDepp.py | 16 + lib/forward/devclass/baseF5.py | 16 + lib/forward/devclass/baseFenghuo.py | 191 +++++++ lib/forward/devclass/baseFortinet.py | 16 + lib/forward/devclass/baseHuawei.py | 388 ++++++++++++++ lib/forward/devclass/baseJuniper.py | 270 ++++++++++ lib/forward/devclass/baseLinux.py | 134 +++++ lib/forward/devclass/baseMaipu.py | 16 + lib/forward/devclass/baseRaisecom.py | 16 + lib/forward/devclass/baseRuijie.py | 34 ++ lib/forward/devclass/baseSSHV1.py | 316 ++++++++++++ lib/forward/devclass/baseSSHV2.py | 244 +++++++++ lib/forward/devclass/baseTELNET.py | 275 ++++++++++ lib/forward/devclass/baseVenustech.py | 16 + lib/forward/devclass/baseZte.py | 15 + lib/forward/devclass/bclinux7.py | 19 + lib/forward/devclass/c2960.py | 34 ++ lib/forward/devclass/c4510.py | 33 ++ lib/forward/devclass/c6506.py | 17 + lib/forward/devclass/c6509.py | 34 ++ lib/forward/devclass/e1000e.py | 14 + lib/forward/devclass/e8000e.py | 15 + lib/forward/devclass/e8160e.py | 15 + lib/forward/devclass/f1000.py | 15 + lib/forward/devclass/f510000.py | 31 ++ lib/forward/devclass/fg1240.py | 15 + lib/forward/devclass/fg3040.py | 15 + lib/forward/devclass/fg3950.py | 15 + lib/forward/devclass/m6000.py | 14 + lib/forward/devclass/mx960.py | 12 + lib/forward/devclass/n5548.py | 47 ++ lib/forward/devclass/n5596.py | 47 ++ lib/forward/devclass/n7010.py | 47 ++ lib/forward/devclass/n7018.py | 47 ++ lib/forward/devclass/n7710.py | 47 ++ lib/forward/devclass/n7718.py | 47 ++ lib/forward/devclass/ne40ex16.py | 87 ++++ lib/forward/devclass/ne40ex3.py | 15 + lib/forward/devclass/r3048g.py | 94 ++++ lib/forward/devclass/rg5510.py | 20 + lib/forward/devclass/s3300.py | 254 ++++++++++ lib/forward/devclass/s5328.py | 16 + lib/forward/devclass/s5352.py | 14 + lib/forward/devclass/s5800.py | 301 +++++++++++ lib/forward/devclass/s8512.py | 15 + lib/forward/devclass/s9303.py | 15 + lib/forward/devclass/s9306.py | 15 + lib/forward/devclass/s9312.py | 285 +++++++++++ lib/forward/devclass/sr7750.py | 14 + lib/forward/devclass/sr7950.py | 15 + lib/forward/devclass/srx3400.py | 15 + lib/forward/devclass/usg1000.py | 219 ++++++++ lib/forward/devclass/vlb.py | 88 ++++ lib/forward/devclass/vyoslinux.py | 74 +++ lib/forward/devclass/zx5952.py | 15 + lib/forward/release.py | 8 + lib/forward/utils/__init__.py | 0 lib/forward/utils/deviceListSplit.py | 41 ++ lib/forward/utils/forwardError.py | 11 + lib/forward/utils/loginThread.py | 18 + lib/forward/utils/paraCheck.py | 40 ++ lib/forward/utils/sshv1.py | 79 +++ lib/forward/utils/sshv2.py | 31 ++ lib/forward/utils/telnet.py | 80 +++ nosetests.ini | 11 + protocol/flake8 | 4 + protocol/pre-commit | 14 + requirements.txt | 3 + setup.py | 114 +++++ test | 1 - unittests/__init__.py | 0 unittests/baseBaseBrocade.py | 51 ++ unittests/testAdx03100.py | 66 +++ unittests/testAsa.py | 66 +++ unittests/testAsr1006.py | 66 +++ unittests/testBaseBaer.py | 51 ++ unittests/testBaseCisco.py | 66 +++ unittests/testBaseDepp.py | 51 ++ unittests/testBaseF5.py | 51 ++ unittests/testBaseFenghuo.py | 51 ++ unittests/testBaseFortinet.py | 51 ++ unittests/testBaseHuawei.py | 66 +++ unittests/testBaseJuniper.py | 65 +++ unittests/testBaseLinux.py | 60 +++ unittests/testBaseMaipu.py | 51 ++ unittests/testBaseRaisecom.py | 65 +++ unittests/testBaseSSHV1.py | 50 ++ unittests/testBaseSSHV2.py | 50 ++ unittests/testBaseTELNET.py | 50 ++ unittests/testBaseVenustech.py | 51 ++ unittests/testBaseZte.py | 51 ++ unittests/testC2960.py | 66 +++ unittests/testC4510.py | 66 +++ unittests/testC6506.py | 66 +++ unittests/testC6509.py | 66 +++ unittests/testDevclassInit.py | 90 ++++ unittests/testE1000e.py | 59 +++ unittests/testE8000e.py | 51 ++ unittests/testE8160e.py | 51 ++ unittests/testF1000.py | 51 ++ unittests/testF510000.py | 51 ++ unittests/testFg1240.py | 51 ++ unittests/testFg3040.py | 51 ++ unittests/testFg3950.py | 51 ++ unittests/testM6000.py | 51 ++ unittests/testMainClass.py | 85 ++++ unittests/testMx960.py | 51 ++ unittests/testN5548.py | 66 +++ unittests/testN5596.py | 66 +++ unittests/testN7010.py | 66 +++ unittests/testN7018.py | 66 +++ unittests/testN7710.py | 66 +++ unittests/testN7718.py | 66 +++ unittests/testNe40ex16.py | 66 +++ unittests/testNe40ex3.py | 66 +++ unittests/testR3048g.py | 65 +++ unittests/testRg5510.py | 59 +++ unittests/testS3300.py | 51 ++ unittests/testS5328.py | 66 +++ unittests/testS5352.py | 66 +++ unittests/testS5800.py | 62 +++ unittests/testS8512.py | 66 +++ unittests/testS9303.py | 66 +++ unittests/testS9306.py | 66 +++ unittests/testS9312.py | 66 +++ unittests/testSr7750.py | 65 +++ unittests/testSr7950.py | 51 ++ unittests/testSrx3400.py | 64 +++ unittests/testUsg1000.py | 66 +++ unittests/testVlb.py | 52 ++ unittests/testVyoslinux.py | 58 +++ unittests/testZx5952.py | 51 ++ 212 files changed, 9817 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 .python-version create mode 100644 .travis.yml create mode 100644 COPYING create mode 100644 docs/Authors.md create mode 100644 docs/BranchInfo.md create mode 100644 docs/GettingStarted.md create mode 100644 docs/Installation.md create mode 100644 docs/License.md create mode 100644 docs/VersionInfo.md create mode 100644 docs/advance/command.md create mode 100644 docs/advance/initialize.md create mode 100644 docs/advance/prelogin.md create mode 100644 docs/class/README.md create mode 100644 docs/class/sshv1/README.md create mode 100644 docs/class/sshv1/maipu/README.md create mode 100644 docs/class/sshv1/maipu/s3300.md create mode 100644 docs/class/sshv2/README.md create mode 100644 docs/class/sshv2/baer/README.md create mode 100644 docs/class/sshv2/baer/sr7750.md create mode 100644 docs/class/sshv2/baer/sr7950.md create mode 100644 docs/class/sshv2/brocade/README.md create mode 100644 docs/class/sshv2/brocade/vlb.md create mode 100644 docs/class/sshv2/cisco/README.md create mode 100644 docs/class/sshv2/cisco/adx03100.md create mode 100644 docs/class/sshv2/cisco/asa.md create mode 100644 docs/class/sshv2/cisco/asr1006.md create mode 100644 docs/class/sshv2/cisco/c2960.md create mode 100644 docs/class/sshv2/cisco/c4510.md create mode 100644 docs/class/sshv2/cisco/c6506.md create mode 100644 docs/class/sshv2/cisco/c6509.md create mode 100644 docs/class/sshv2/cisco/n5548.md create mode 100644 docs/class/sshv2/cisco/n5596.md create mode 100644 docs/class/sshv2/cisco/n7010.md create mode 100644 docs/class/sshv2/cisco/n7018.md create mode 100644 docs/class/sshv2/cisco/n7710.md create mode 100644 docs/class/sshv2/cisco/n7718.md create mode 100644 docs/class/sshv2/depp/README.md create mode 100644 docs/class/sshv2/depp/f1000.md create mode 100644 docs/class/sshv2/f5/README.md create mode 100644 docs/class/sshv2/f5/f510000.md create mode 100644 docs/class/sshv2/fenghuo/README.md create mode 100644 docs/class/sshv2/fenghuo/s5800.md create mode 100644 docs/class/sshv2/fortinet/README.md create mode 100644 docs/class/sshv2/fortinet/fg1240.md create mode 100644 docs/class/sshv2/fortinet/fg3040.md create mode 100644 docs/class/sshv2/fortinet/fg3950.md create mode 100644 docs/class/sshv2/huawei/README.md create mode 100644 docs/class/sshv2/huawei/e1000e.md create mode 100644 docs/class/sshv2/huawei/e8000e.md create mode 100644 docs/class/sshv2/huawei/e8160e.md create mode 100644 docs/class/sshv2/huawei/ne40ex16.md create mode 100644 docs/class/sshv2/huawei/ne40ex3.md create mode 100644 docs/class/sshv2/huawei/s5328.md create mode 100644 docs/class/sshv2/huawei/s5352.md create mode 100644 docs/class/sshv2/huawei/s8512.md create mode 100644 docs/class/sshv2/huawei/s9303.md create mode 100644 docs/class/sshv2/huawei/s9306.md create mode 100644 docs/class/sshv2/huawei/s9312.md create mode 100644 docs/class/sshv2/linux/README.md create mode 100644 docs/class/sshv2/linux/bclinux7.md create mode 100644 docs/class/sshv2/raisecom/README.md create mode 100644 docs/class/sshv2/raisecom/r3048g.md create mode 100644 docs/class/sshv2/zte/README.md create mode 100644 docs/class/sshv2/zte/m6000.md create mode 100644 docs/class/sshv2/zte/zx5952.md create mode 100644 docs/class/telnet/README.md create mode 100644 docs/class/telnet/juniper/README.md create mode 100644 docs/class/telnet/juniper/mx960.md create mode 100644 docs/class/telnet/juniper/srx3400.md create mode 100644 docs/class/telnet/venustech/README.md create mode 100644 docs/class/telnet/venustech/usg1000.md create mode 100644 lib/forward/__init__.py create mode 100644 lib/forward/devclass/__init__.py create mode 100644 lib/forward/devclass/adx03100.py create mode 100644 lib/forward/devclass/asa.py create mode 100644 lib/forward/devclass/asr1006.py create mode 100644 lib/forward/devclass/baseBaer.py create mode 100644 lib/forward/devclass/baseBrocade.py create mode 100644 lib/forward/devclass/baseCisco.py create mode 100644 lib/forward/devclass/baseDepp.py create mode 100644 lib/forward/devclass/baseF5.py create mode 100644 lib/forward/devclass/baseFenghuo.py create mode 100644 lib/forward/devclass/baseFortinet.py create mode 100644 lib/forward/devclass/baseHuawei.py create mode 100644 lib/forward/devclass/baseJuniper.py create mode 100644 lib/forward/devclass/baseLinux.py create mode 100644 lib/forward/devclass/baseMaipu.py create mode 100644 lib/forward/devclass/baseRaisecom.py create mode 100644 lib/forward/devclass/baseRuijie.py create mode 100644 lib/forward/devclass/baseSSHV1.py create mode 100644 lib/forward/devclass/baseSSHV2.py create mode 100644 lib/forward/devclass/baseTELNET.py create mode 100644 lib/forward/devclass/baseVenustech.py create mode 100644 lib/forward/devclass/baseZte.py create mode 100644 lib/forward/devclass/bclinux7.py create mode 100644 lib/forward/devclass/c2960.py create mode 100644 lib/forward/devclass/c4510.py create mode 100644 lib/forward/devclass/c6506.py create mode 100644 lib/forward/devclass/c6509.py create mode 100644 lib/forward/devclass/e1000e.py create mode 100644 lib/forward/devclass/e8000e.py create mode 100644 lib/forward/devclass/e8160e.py create mode 100644 lib/forward/devclass/f1000.py create mode 100644 lib/forward/devclass/f510000.py create mode 100644 lib/forward/devclass/fg1240.py create mode 100644 lib/forward/devclass/fg3040.py create mode 100644 lib/forward/devclass/fg3950.py create mode 100644 lib/forward/devclass/m6000.py create mode 100644 lib/forward/devclass/mx960.py create mode 100644 lib/forward/devclass/n5548.py create mode 100644 lib/forward/devclass/n5596.py create mode 100644 lib/forward/devclass/n7010.py create mode 100644 lib/forward/devclass/n7018.py create mode 100644 lib/forward/devclass/n7710.py create mode 100644 lib/forward/devclass/n7718.py create mode 100644 lib/forward/devclass/ne40ex16.py create mode 100644 lib/forward/devclass/ne40ex3.py create mode 100644 lib/forward/devclass/r3048g.py create mode 100644 lib/forward/devclass/rg5510.py create mode 100644 lib/forward/devclass/s3300.py create mode 100644 lib/forward/devclass/s5328.py create mode 100644 lib/forward/devclass/s5352.py create mode 100644 lib/forward/devclass/s5800.py create mode 100644 lib/forward/devclass/s8512.py create mode 100644 lib/forward/devclass/s9303.py create mode 100644 lib/forward/devclass/s9306.py create mode 100644 lib/forward/devclass/s9312.py create mode 100644 lib/forward/devclass/sr7750.py create mode 100644 lib/forward/devclass/sr7950.py create mode 100644 lib/forward/devclass/srx3400.py create mode 100644 lib/forward/devclass/usg1000.py create mode 100644 lib/forward/devclass/vlb.py create mode 100644 lib/forward/devclass/vyoslinux.py create mode 100644 lib/forward/devclass/zx5952.py create mode 100644 lib/forward/release.py create mode 100644 lib/forward/utils/__init__.py create mode 100644 lib/forward/utils/deviceListSplit.py create mode 100644 lib/forward/utils/forwardError.py create mode 100644 lib/forward/utils/loginThread.py create mode 100644 lib/forward/utils/paraCheck.py create mode 100644 lib/forward/utils/sshv1.py create mode 100644 lib/forward/utils/sshv2.py create mode 100644 lib/forward/utils/telnet.py create mode 100644 nosetests.ini create mode 100644 protocol/flake8 create mode 100644 protocol/pre-commit create mode 100644 requirements.txt create mode 100644 setup.py delete mode 100644 test create mode 100644 unittests/__init__.py create mode 100644 unittests/baseBaseBrocade.py create mode 100644 unittests/testAdx03100.py create mode 100644 unittests/testAsa.py create mode 100644 unittests/testAsr1006.py create mode 100644 unittests/testBaseBaer.py create mode 100644 unittests/testBaseCisco.py create mode 100644 unittests/testBaseDepp.py create mode 100644 unittests/testBaseF5.py create mode 100644 unittests/testBaseFenghuo.py create mode 100644 unittests/testBaseFortinet.py create mode 100644 unittests/testBaseHuawei.py create mode 100644 unittests/testBaseJuniper.py create mode 100644 unittests/testBaseLinux.py create mode 100644 unittests/testBaseMaipu.py create mode 100644 unittests/testBaseRaisecom.py create mode 100644 unittests/testBaseSSHV1.py create mode 100644 unittests/testBaseSSHV2.py create mode 100644 unittests/testBaseTELNET.py create mode 100644 unittests/testBaseVenustech.py create mode 100644 unittests/testBaseZte.py create mode 100644 unittests/testC2960.py create mode 100644 unittests/testC4510.py create mode 100644 unittests/testC6506.py create mode 100644 unittests/testC6509.py create mode 100644 unittests/testDevclassInit.py create mode 100644 unittests/testE1000e.py create mode 100644 unittests/testE8000e.py create mode 100644 unittests/testE8160e.py create mode 100644 unittests/testF1000.py create mode 100644 unittests/testF510000.py create mode 100644 unittests/testFg1240.py create mode 100644 unittests/testFg3040.py create mode 100644 unittests/testFg3950.py create mode 100644 unittests/testM6000.py create mode 100644 unittests/testMainClass.py create mode 100644 unittests/testMx960.py create mode 100644 unittests/testN5548.py create mode 100644 unittests/testN5596.py create mode 100644 unittests/testN7010.py create mode 100644 unittests/testN7018.py create mode 100644 unittests/testN7710.py create mode 100644 unittests/testN7718.py create mode 100644 unittests/testNe40ex16.py create mode 100644 unittests/testNe40ex3.py create mode 100644 unittests/testR3048g.py create mode 100644 unittests/testRg5510.py create mode 100644 unittests/testS3300.py create mode 100644 unittests/testS5328.py create mode 100644 unittests/testS5352.py create mode 100644 unittests/testS5800.py create mode 100644 unittests/testS8512.py create mode 100644 unittests/testS9303.py create mode 100644 unittests/testS9306.py create mode 100644 unittests/testS9312.py create mode 100644 unittests/testSr7750.py create mode 100644 unittests/testSr7950.py create mode 100644 unittests/testSrx3400.py create mode 100644 unittests/testUsg1000.py create mode 100644 unittests/testVlb.py create mode 100644 unittests/testVyoslinux.py create mode 100644 unittests/testZx5952.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6c47330 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib64/ +parts/ +sdist/ +*.egg-info/ +.installed.cfg +*.egg + +# Custom +conf/ +data/ +log/ +.tmp/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..dfa275f --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +forward diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..fb00e30 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,23 @@ +language: python +python: + - "2.7.10" + +install: + - pip install -r requirements.txt +script: + - nosetests -v test/ --exe + +notifications: + email: + recipients: + - azrael-ex@139.com + on_success: always + on_failure: always + +branches: + only: + - master + - forward + +after_success: +- coveralls diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..92b370f --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/Authors.md b/docs/Authors.md new file mode 100644 index 0000000..d604cae --- /dev/null +++ b/docs/Authors.md @@ -0,0 +1,3 @@ +## Authors 作者 +*   Forward由王喆(Headkarl: azrael-ex@139.com)创建,并且由张其川(cheung kei-chuen: qichuan.zhang@qq.com)、麦艺帆(Leann Mak:leannmak@139.com)、戴声(Shawn.T:shawntai.ds@gmail.com)等多位用户参与贡献,在此衷心感谢每一位。 +*   Forward was created by Wang Zhe(Headkarl: azrael-ex@139.com) and contributed by many users, such as Zhang Qichuan(cheung kei-chuen: qichuan.zhang@qq.com), Mai Yi Fan(Leann Mak:leannmak@139.com) and Dai Sheng(Shawn.T:shawntai.ds@gmail.com), and sincerely thanks each one. diff --git a/docs/BranchInfo.md b/docs/BranchInfo.md new file mode 100644 index 0000000..ff82a0b --- /dev/null +++ b/docs/BranchInfo.md @@ -0,0 +1,7 @@ +## Brance Info 分支信息 +*   RC,Releases和Stables分支都以版本号+各种鱼类命名。 +*   devel分支对应正在开发的分支。 +*   alpha分支对应一个早期的内部测试版本。 +*   RC,Releases and Stables are named after the version number plus any kind of fish. +*   The devel branch corresponds to the release actively under development. +*   The alpha branch corresponds to a early release thich is used for In-House test. diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md new file mode 100644 index 0000000..0fd0eba --- /dev/null +++ b/docs/GettingStarted.md @@ -0,0 +1,24 @@ +## Getting Started +*   下方代码段展示了一个简易的forward场景实现,批量连接到两台设备(思科Nexus7018),执行指令并获取结果。 +*   The code section below shows a simple forward scenario implementation that is batch connected to two devices (CISCO Nexus7018), executes instructions and gets the results. + + ```Python + from forward import Forward + + new = Forward() + new.addTargets(['192.168.113.1-192.168.113.2'],'n7018','username','password') + instances = new.getInstances() + + cisco1 = instances['192.168.113.1'] + cisco2 = instances['192.168.113.2'] + + result1 = cisco1.execute('show version') + result2 = cisco2.execute('show version') + + if result1['status']: + print '[%s] OS version info: %s' % ('cisco1', result1['content']) + if result2['status']: + print '[%s] OS version info: %s' % ('cisco2', result2['content']) + ``` +*   上述代码段中出现的'cisco1'和'cisco2'就是Forward设备类实例(N7018),不同设备类实例包含的方法可能不同,具体请查阅类库文档。 +*   The 'cisco1' and 'cisco2' appearing in the above code segment are Forward device class instances (N7018). Different device class instances contain different methods. Please consult the class library document. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..a5c0495 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,21 @@ +## Installation +1. Building virtual environment (optional) 构建虚拟环境 (可选) + *   开发者用户推荐,使用pyenv和virtualenv构建纯净的python环境,推荐python版本2.7.10 + *   We recommend that developer users use pyenv and virtualenv to build a pure Python environment, and recommend Python version 2.7.10. + ```Bash + pyenv virtualenv 2.7.10 forward + pyenv activate forward + ``` +2. Pull 拉取当前版本 + ```Bash + git clone http://192.168.182.51/promise/forward.git + cd forward + ``` +3. Dependency 安装依赖包 + ```Bash + pip install -r requirements.txt + ``` +4. Setup 安装 + ```Bash + python setup.py install + ``` diff --git a/docs/License.md b/docs/License.md new file mode 100644 index 0000000..41036c1 --- /dev/null +++ b/docs/License.md @@ -0,0 +1,3 @@ +## License +*   GNU General Public License v3.0 +*   See [COPYING](COPYING) to see the full text. diff --git a/docs/VersionInfo.md b/docs/VersionInfo.md new file mode 100644 index 0000000..ea53473 --- /dev/null +++ b/docs/VersionInfo.md @@ -0,0 +1,57 @@ +## Version Update Record 版本更新记录 +### V3.0.8 +1. 新增sshv1和telnet通道标准类的command命令模式。 + +### V3.0.7 +1. 新增sshv2通道标准类的command命令模式,通过高度自定义用法来实现网络设备配置模式。 +2. 新增baseFenghuo标准类库。 +3. 修复S9312,S5800,NE40EX16,S9300,S9312类库中的部分bug。 + +### V3.0.6 +1. 新增vyoslinux类的zcli命令模式 +2. 修复vyoslinux执行命令返回状态不正确的缺陷和特别字符问题。 +3. 新增S5800类支持创建VLan、设置Vlan接口、设置Trunk接口。 +4. 新增S9312类支持创建VLan、设置VLan接口。 +5. 修复baseTELNET参数不一致问题。 + +### V3.0.5 +1. 修复bug: + * 修复了USG设备的privilege模式。 + * 修复了vyos设备的部分指令返回卡死的问题。 + * 添加了bclinux7设备的zcli模式。 + +### V3.0.4 +1. 修复bug: + * telnet与sshv1分支系列设备不能成功初始化的问题已经修复。 + * cisco系列设备的二次认证问题已经修复。 + +### V3.0.3 +1. 新增类库: 目前所有1.0版本中的类库已经重构完毕,可以使用,但未经过测试。 + * 根级基础类:baseTELNET,baseSSHV1 + * 厂家级基础类:baseJuniper,baseBear,baseDepp,baseF5,baseFortinet,baseRaisecom,baseZte + * 华为类:s3300,e1000e + * Juniper类:mx960,srx3400 + * 启明星辰类:usg1000 +2. 修复继承关系: + * f510000,fg1240,fg3040,fg3950,m6000,r3048g,s5800,sr7750,zx5952:这些类库目前正确地继承了厂家基础类。 + +### V3.0.2 +1. 新增类库: + * 华为类:e8000e,s9306,s9312,e8160e,ne40ex3,ne40ex16,s5328,s5352,s8512 + * 思科类:adx03100,asa,asr1006,f1000,f510000 + * linux类:bclinux7 + * 其他类:sr7750,zx5952,fg1240,fg3040,fg3950,m6000,r3048g,s5800,vlb + +### V3.0.1 +1. 新增类库: + * 厂家级基础类:baseHuawei + * 华为类:s9303 +2. 修正bug: n7018类现在可以被正确的调用了。 + +### V3.0.0 +1. 版本重构,欢迎体验精简的Forward3.0,参考快速入门。 +2. 当前支持的类库: + * 根级基础类:basesshv2 + * 厂家级基础类:basecisco,baselinux + * 思科类:c2960,c4510,c6506,c6509,n5548,n5596,n7010,n7018,n7710,n7718 +3. 添加预登陆模式: 默认所有类实例将会在用户调用getInstances方法时批量登陆,如果你不需要预先登陆所有机器,可以指定preLogin属性,例如:Forward.getInstances(preLogin=False),然后在单独的实例中调用login()方法进行登陆。 diff --git a/docs/advance/command.md b/docs/advance/command.md new file mode 100644 index 0000000..6add678 --- /dev/null +++ b/docs/advance/command.md @@ -0,0 +1,102 @@ +## 自定义指令 Command + +##### Description + +* 自定义指令Command是一个通用方法,所有继承于ssh和telnet类的节点类实例都具备该方法,接受"命令行"和"判断依据"两个参数,执行"命令行"之后按照"判断依据"的定义来判断结果,并返回结果。 + +##### Options + +| parameter | required | default | choices | comments | +|:--:|:--:|:--:|:--:|:--:| +| cmd | yes | none | | The command line you want to execute. | +| prompt | yes | none | | The prompt dict which will decide the type of CMD execution result. | + +* command会在执行cmd之后依次匹配prompt中定义的正则表达式,匹配后中断后续匹配并返回状态结果。 + +##### Return + +* command指令返回一个字典结构 + +| attr | type | example | comments | +|:--:|:--:|:--:|:--:| +| status | boolean | True | CMD execution status. | +| state | string | 'state_you_defined' | CMD execution result type. | +| content | boolean | True | CMD execution console output. | +| errLog | boolean | True | CMD execution error log(when status is False). | + +##### Example + +* 使用centos cp 指令场景作为样例,首先列出手工执行cp指令可能遇到的情况: + +* 直接成功情况: + +```Bash +[admin@SOMEHOST ~]$ cp -i file_a file_b +[admin@SOMEHOST ~]$ +``` + +* 询问覆盖情况: + +```Bash +[admin@SOMEHOST ~]$ cp -i file_a file_b +cp: overwrite "file_b"? y +[admin@SOMEHOST ~]$ +``` + +* 权限不够情况: + +```Bash +[admin@SOMEHOST ~]$ cp -i file_c file_d +cp: can not open "file_c" : permission denied +[admin@SOMEHOST ~]$ +``` + +* 使用Forward command方法构建一个小型cp函数,一次性实现所有场景 + +```Python +from forward import Forward +fw = Forward() +fw.addTargets(['192.168.10.10'], 'baseLinux', 'username', 'password') +linux = fw.getInstances()['192.168.10.10'] + +def cp(from_path, to_path, overwrite): + cmd = 'cp -i %s %s' % (from_path, to_path) + prompt = [ + { 'exist': ['overwrite'] }, + { 'denied': ['permission denied'] }, + { 'success': ['COREVM60 \~\]\$', '\$'] } + ] + + def call_exist(): + confirm_cmd = overwrite + confirm_prompt = [ + { 'error': ['error'] }, + { 'success': ['COREVM60 \~\]\$', '\$'] } + ] + confirm_result = linux.command(cmd=confirm_cmd, prompt=confirm_prompt) + if confirm_result['status'] == True and confirm_result['state'] == 'success': + print 'copy complete! overwrite: %s' % overwrite + else: + print 'error: %s\r\nerror:%s' % (confirm_result['content'], confirm_result['errLog']) + + def call_denied(): + print 'Permission denied' + + def call_success(): + print 'Success' + + call_function = { + 'exist': call_exist, + 'denied': call_denied, + 'success': call_success + } + + result = linux.command(cmd=cmd, prompt=prompt) + if result['status'] == True: + call_function[result['state']]() +``` + +##### Command VS Execute: + +* execute适用于简单的查询场景,要求在指令执行之后提示符不会发生变化。 +* command适用于复杂的配置场景,由用户自己指定返回值匹配规则,适合用于构建复杂功能操作。 diff --git a/docs/advance/initialize.md b/docs/advance/initialize.md new file mode 100644 index 0000000..3078ade --- /dev/null +++ b/docs/advance/initialize.md @@ -0,0 +1,30 @@ +## 初始化 Initialize + +##### Forward初始化过程可以简单分为三步: + +```Python +# import +from forward import Forward +fw = Forward() + +# add targets +fw.addTargets(['192.168.1.10', '192.168.1.21-192.168.1.30'], 'n7018', 'username', 'password') +fw.addTargets(['192.168.2.10'], 'mx960', 'username2', 'password2') +fw.addTargets(['192.168.3.10', '192.168.3.11-192.168.3.20'], 's5328', 'username3', 'password3') + +# get instances +instances = fw.getInstances() +``` + +* 在这个代码段中,forward接受到了11台cisco n7018、1台juniper mx960和11台huawei s5328,共计23台设备信息作为目标,完成初始化并返回一个包含23台设备forward类实例的字典结构,用户可以通过下面的方法拿到其中任何一个实例,每一种设备类实例包含的属性和方法可能是不一样的,请参考详细的[类库文档](/docs/class): + +```Python +cisco1 = instances['192.168.1.10'] +``` + +* 这些类实例已经完成登陆,可以直接调用execute和command方法执行指令,如果你不需要在初始化环节进行登陆而希望自己控制登陆行为,请在第三步设置一个简单参数即可(例子中关闭了预登陆,并且代码控制只登陆了其中一台设备),更多关于预登陆的信息请参考[预登陆](/docs/advance/prelogin): + +```Python +instances = fw.getInstances(preLogin=False) +instances['192.168.1.21'].login() +``` diff --git a/docs/advance/prelogin.md b/docs/advance/prelogin.md new file mode 100644 index 0000000..52ff525 --- /dev/null +++ b/docs/advance/prelogin.md @@ -0,0 +1,22 @@ +## 预登陆 Prelogin + +* 预登陆模式(默认),获取实例同时完成自动登录,可直接执行指令。 + +```Python +# get instances that have logined +instances = fw.getInstances() +``` + +* 非登陆模式,获取实例时只做初始化操作,不执行自动登陆,可后续代码控制登陆。 + +```Python +# get instances that haven't logined +instances = fw.getInstances(preLogin=False) +# manual login +instances['192.168.1.10'].login() +``` + +* 非登陆模式主要用于应对以下场景: + * 目标节点数量巨大,且不需要全部登陆,例如在庞大组网结构中逐跳定位路径场景。 + * 设备执行指令耗时巨大,可能导致其他等待节点自动断开连接,从而影响场景执行,例如核查分析全量配置场景。 + * 其他类似场景。 diff --git a/docs/class/README.md b/docs/class/README.md new file mode 100644 index 0000000..47f9af1 --- /dev/null +++ b/docs/class/README.md @@ -0,0 +1,64 @@ +## Forward Class Library Documents 类库文档 +*   Forward按照 '连接协议' -> '厂家' -> '型号' 的形式建立通用类库继承顺序。 +*   Forward establishes the inheritance order of the general class library in the form which like 'Protocol' -> 'Manufacturers' -> 'Model'. + +--- + +* [baseSSHV1](/docs/class/sshv1) + * [baseMaipu](/docs/class/sshv1/maipu) + * [s3300](/docs/class/sshv1/maipu/s3300.md) +* [baseTELNET](/docs/class/telnet) + * [baseJuniper](/docs/class/telnet/juniper) + * [mx960](/docs/class/telnet/juniper/mx960.md) + * [srx3400](/docs/class/telnet/juniper/srx3400.md) + * [baseVenustech](/docs/class/telnet/venustech) + * [usg1000](/docs/class/telnet/venustech/usg1000.md) +* [baseSSHV2](/docs/class/sshv2) + * [baseCisco](/docs/class/sshv2/cisco) + * [adx03100](/docs/class/sshv2/cisco/adx03100.md) + * [asa](/docs/class/sshv2/cisco/asa.md) + * [asr1006](/docs/class/sshv2/cisco/asr1006.md) + * [c2960](/docs/class/sshv2/cisco/c2960.md) + * [c4510](/docs/class/sshv2/cisco/c4510.md) + * [c6506](/docs/class/sshv2/cisco/c6506.md) + * [c6509](/docs/class/sshv2/cisco/c6509.md) + * [n5548](/docs/class/sshv2/cisco/n5548.md) + * [n5596](/docs/class/sshv2/cisco/n5596.md) + * [n7010](/docs/class/sshv2/cisco/n7010.md) + * [n7018](/docs/class/sshv2/cisco/n7018.md) + * [n7710](/docs/class/sshv2/cisco/n7710.md) + * [n7718](/docs/class/sshv2/cisco/n7718.md) + * [baseHuawei](/docs/class/sshv2/huawei) + * [e1000e](/docs/class/sshv2/huawei/e1000e.md) + * [e8000e](/docs/class/sshv2/huawei/e8000e.md) + * [e8160e](/docs/class/sshv2/huawei/e8160e.md) + * [ne40ex16](/docs/class/sshv2/huawei/ne40ex16.md) + * [ne40ex3](/docs/class/sshv2/huawei/ne40ex3.md) + * [s5328](/docs/class/sshv2/huawei/s5328.md) + * [s5352](/docs/class/sshv2/huawei/s5352.md) + * [s8512](/docs/class/sshv2/huawei/s8512.md) + * [s9303](/docs/class/sshv2/huawei/s9303.md) + * [s9306](/docs/class/sshv2/huawei/s9306.md) + * [s9312](/docs/class/sshv2/huawei/s9312.md) + * [baseLinux](/docs/class/sshv2/linux) + * [bclinux7](/docs/class/sshv2/linux/bclinux7.md) + * [baseDepp](/docs/class/sshv2/depp) + * [f1000](/docs/class/sshv2/depp/f1000.md) + * [baseF5](/docs/class/sshv2/f5) + * [f510000](/docs/class/sshv2/f5/f510000.md) + * [baseFenghuo](/docs/class/sshv2/fenghuo) + * [s5800](/docs/class/sshv2/fenghuo/s5800.md) + * [baseFortinet](/docs/class/sshv2/fortinet) + * [fg1240](/docs/class/sshv2/fortinet/fg1240.md) + * [fg3040](/docs/class/sshv2/fortinet/fg3040.md) + * [fg3950](/docs/class/sshv2/fortinet/fg3950.md) + * [baseBaer](/docs/class/sshv2/baer) + * [sr7750](/docs/class/sshv2/baer/sr7750.md) + * [sr7950](/docs/class/sshv2/baer/sr7950.md) + * [baseRaisecom](/docs/class/sshv2/raisecom) + * [r3048g](/docs/class/sshv2/raisecom/r3048g.md) + * [baseZte](/docs/class/sshv2/zte) + * [m6000](/docs/class/sshv2/zte/m6000.md) + * [zx5952](/docs/class/sshv2/zte/zx5952.md) + * [baseBrocade](/docs/class/sshv2/brocade) + * [vlb](/docs/class/sshv2/brocade/vlb.md) diff --git a/docs/class/sshv1/README.md b/docs/class/sshv1/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv1/maipu/README.md b/docs/class/sshv1/maipu/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv1/maipu/s3300.md b/docs/class/sshv1/maipu/s3300.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/README.md b/docs/class/sshv2/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/baer/README.md b/docs/class/sshv2/baer/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/baer/sr7750.md b/docs/class/sshv2/baer/sr7750.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/baer/sr7950.md b/docs/class/sshv2/baer/sr7950.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/brocade/README.md b/docs/class/sshv2/brocade/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/brocade/vlb.md b/docs/class/sshv2/brocade/vlb.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/README.md b/docs/class/sshv2/cisco/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/adx03100.md b/docs/class/sshv2/cisco/adx03100.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/asa.md b/docs/class/sshv2/cisco/asa.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/asr1006.md b/docs/class/sshv2/cisco/asr1006.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/c2960.md b/docs/class/sshv2/cisco/c2960.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/c4510.md b/docs/class/sshv2/cisco/c4510.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/c6506.md b/docs/class/sshv2/cisco/c6506.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/c6509.md b/docs/class/sshv2/cisco/c6509.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n5548.md b/docs/class/sshv2/cisco/n5548.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n5596.md b/docs/class/sshv2/cisco/n5596.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n7010.md b/docs/class/sshv2/cisco/n7010.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n7018.md b/docs/class/sshv2/cisco/n7018.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n7710.md b/docs/class/sshv2/cisco/n7710.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/cisco/n7718.md b/docs/class/sshv2/cisco/n7718.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/depp/README.md b/docs/class/sshv2/depp/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/depp/f1000.md b/docs/class/sshv2/depp/f1000.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/f5/README.md b/docs/class/sshv2/f5/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/f5/f510000.md b/docs/class/sshv2/f5/f510000.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fenghuo/README.md b/docs/class/sshv2/fenghuo/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fenghuo/s5800.md b/docs/class/sshv2/fenghuo/s5800.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fortinet/README.md b/docs/class/sshv2/fortinet/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fortinet/fg1240.md b/docs/class/sshv2/fortinet/fg1240.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fortinet/fg3040.md b/docs/class/sshv2/fortinet/fg3040.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/fortinet/fg3950.md b/docs/class/sshv2/fortinet/fg3950.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/README.md b/docs/class/sshv2/huawei/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/e1000e.md b/docs/class/sshv2/huawei/e1000e.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/e8000e.md b/docs/class/sshv2/huawei/e8000e.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/e8160e.md b/docs/class/sshv2/huawei/e8160e.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/ne40ex16.md b/docs/class/sshv2/huawei/ne40ex16.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/ne40ex3.md b/docs/class/sshv2/huawei/ne40ex3.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s5328.md b/docs/class/sshv2/huawei/s5328.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s5352.md b/docs/class/sshv2/huawei/s5352.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s8512.md b/docs/class/sshv2/huawei/s8512.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s9303.md b/docs/class/sshv2/huawei/s9303.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s9306.md b/docs/class/sshv2/huawei/s9306.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/huawei/s9312.md b/docs/class/sshv2/huawei/s9312.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/linux/README.md b/docs/class/sshv2/linux/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/linux/bclinux7.md b/docs/class/sshv2/linux/bclinux7.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/raisecom/README.md b/docs/class/sshv2/raisecom/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/raisecom/r3048g.md b/docs/class/sshv2/raisecom/r3048g.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/zte/README.md b/docs/class/sshv2/zte/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/zte/m6000.md b/docs/class/sshv2/zte/m6000.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/sshv2/zte/zx5952.md b/docs/class/sshv2/zte/zx5952.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/README.md b/docs/class/telnet/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/juniper/README.md b/docs/class/telnet/juniper/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/juniper/mx960.md b/docs/class/telnet/juniper/mx960.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/juniper/srx3400.md b/docs/class/telnet/juniper/srx3400.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/venustech/README.md b/docs/class/telnet/venustech/README.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/class/telnet/venustech/usg1000.md b/docs/class/telnet/venustech/usg1000.md new file mode 100644 index 0000000..e69de29 diff --git a/lib/forward/__init__.py b/lib/forward/__init__.py new file mode 100644 index 0000000..afed61b --- /dev/null +++ b/lib/forward/__init__.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +import threading +import importlib +import forward.release +from forward.utils.forwardError import ForwardError +from forward.utils.loginThread import loginThread +from forward.utils.paraCheck import paraCheck +from forward.utils.deviceListSplit import DEVICELIST + +__version__ = forward.release.__version__ +__author__ = forward.release.__author__ + + +class Forward(object): + """Forward Module Main Class""" + def __init__(self, targets=None): + # target: [[ip,model,user,pw,{port},{timeout}],...] + super(Forward, self).__init__() + self.instances = {} + if (targets is None): + self.targets = [] + elif paraCheck(targets): + self.targets = targets + else: + raise ForwardError('[Forward Init Failed]: parameters type error') + + def addTargets(self, iplist, model, username, password, **kwargs): + # iplist,model,username,password,port=??,timeout=?? + ipAdds = DEVICELIST(iplist).getIpList() + targetList = [] + + for ip in ipAdds: + if paraCheck([[ip, model, username, password, kwargs]]): + targetList.append([ip, model, username, password, kwargs]) + else: + print "[Add Targets Error]: %s parameters type error, please check." % ip + + self.targets.extend(targetList) + + def getInstances(self, preLogin=True): + # thread init + threads = [] + + # init instances + if preLogin: + for target in self.targets: + model = target[1] + className = model.upper() + self.instances[target[0]] = getattr( + importlib.import_module('forward.devclass.%s' % (model)), + className + )(target[0], target[2], target[3], **target[4]) + + threadNode = threading.Thread(target=loginThread, args=(self.instances[target[0]],)) + threadNode.start() + threads.append(threadNode) + else: + for target in self.targets: + model = target[1] + className = model.upper() + self.instances[target[0]] = getattr( + importlib.import_module('forward.devclass.%s' % (model)), + className + )(target[0], target[2], target[3], **target[4]) + + # pre login thread join + if preLogin: + for t in threads: + t.join() + + return self.instances diff --git a/lib/forward/devclass/__init__.py b/lib/forward/devclass/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lib/forward/devclass/adx03100.py b/lib/forward/devclass/adx03100.py new file mode 100644 index 0000000..606b400 --- /dev/null +++ b/lib/forward/devclass/adx03100.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for ADX03100. +Author: Cheung Kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class ADX03100(BASECISCO): + """The device model belongs to the cisco series + so the attributes and methods of BASECISCO are inherited. + """ + pass diff --git a/lib/forward/devclass/asa.py b/lib/forward/devclass/asa.py new file mode 100644 index 0000000..981647b --- /dev/null +++ b/lib/forward/devclass/asa.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for asa. +Author: Cheung Kei-chuen +""" + +import re +from forward.devclass.baseCisco import BASECISCO +from forward.utils.forwardError import ForwardError + + +class ASA(BASECISCO): + """The device model belongs to the cisco series + so the attributes and methods of BASECISCO are inherited. + """ + def cleanBuffer(self): + """Since the device is inconsistent with the details + of the other Cisco series, the method needs to be rewritten + to fit the device of this type. + """ + if self.shell.recv_ready(): + self.shell.recv(4096) + self.shell.send('\r\n') + buff = '' + """ When after switching mode, the prompt will change, + it should be based on basePromptto check and at last line""" + while not re.search(self.basePrompt, buff.split('\n')[-1]): + try: + # Cumulative return result + buff += self.shell.recv(1024) + except Exception: + raise ForwardError('Receive timeout [%s]' % (buff)) + + def addUser(self, username, password): + # Overriding methods + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} password {password}\n') + + def changePassword(self, username, password): + # Overriding methods + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} password {password}\n') diff --git a/lib/forward/devclass/asr1006.py b/lib/forward/devclass/asr1006.py new file mode 100644 index 0000000..17c11cc --- /dev/null +++ b/lib/forward/devclass/asr1006.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for ASR1006. +Author: Cheung Kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class ASR1006(BASECISCO): + """The device model belongs to the cisco series + so the attributes and methods of BASECISCO are inherited. + """ + def addUser(self, username, password): + # Overriding methods + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') + + def changePassword(self, username, password): + # Overriding methods + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') diff --git a/lib/forward/devclass/baseBaer.py b/lib/forward/devclass/baseBaer.py new file mode 100644 index 0000000..4bf26a0 --- /dev/null +++ b/lib/forward/devclass/baseBaer.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Baer. +Author: zhangqichuan +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEBAER(BASESSHV2): + """This is a manufacturer of baer, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseBrocade.py b/lib/forward/devclass/baseBrocade.py new file mode 100644 index 0000000..f9fdab2 --- /dev/null +++ b/lib/forward/devclass/baseBrocade.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Brocade. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEBROCADE(BASESSHV2): + """This is a manufacturer of brocade, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseCisco.py b/lib/forward/devclass/baseCisco.py new file mode 100644 index 0000000..10f7c24 --- /dev/null +++ b/lib/forward/devclass/baseCisco.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Base device class for cisco basic device method, by using paramiko module. +Author: Cheung Kei-Chuen, Wangzhe +""" + +import re +from forward.devclass.baseSSHV2 import BASESSHV2 +from forward.utils.forwardError import ForwardError + + +class BASECISCO(BASESSHV2): + """This is a manufacturer of cisco, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + def privilegeMode(self): + """Used to switch from normal mode to privileged mode for command line mode. + Does not apply to other modes to switch to privileged mode. + """ + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + # Clean buffer. + self.cleanBuffer() + if self.isLogin and (len(self.privilegePw) > 0): + """This can only be performed when the device + has been successfully logged in and the privilege mode password is specified.""" + # (login succeed status) and (self.privilegePw exist) + self.privilegeModeCommand = 'enable' + self.cleanBuffer() + self.shell.send('%s\n' % (self.privilegeModeCommand)) + enableResult = '' + while True: + """It's not until you have a password prompt or when you switch successfully + that you stop popping out of the loop.""" + """ + etc: + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ + + or + + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + Password: + """ + """ + fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' + """ + # need password + passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand + promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( + command=self.privilegeModeCommand, + basePrompt=self.basePrompt + ) + + # Second layers of judgment, Privileged command char 'super/enable' must be received. + # otherwise recv continue... important! + if re.search(passwordChar, enableResult): + # if received 'password' + break + # no password + elif re.search(promptChar, enableResult): + # if no password + break + else: + # not finished,continue + enableResult += self.shell.recv(1024) + + if re.search('assword', enableResult): + # need password + self.shell.send("%s\n" % self.privilegePw) + _data = '' + while not re.search(self.basePrompt, _data) and (not re.search('assword|denied|Denied', _data)): + _data += self.shell.recv(1024) + if re.search('assword|denied|Denied', _data): + # When send the self.privilegePw, once again encountered a password hint password wrong. + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Password incorrect' + elif re.search(self.basePrompt, _data): + # Switch mode succeed + self.getPrompt() + result['status'] = True + + # Check the error information in advance + elif re.search('\%|Invalid|\^', enableResult): + # bad enable command + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' + elif re.search(self.basePrompt, enableResult): + # Switch mode succeed, don't need password + self.getPrompt() + result['status'] = True + else: + result['stauts'] = False + result['errLog'] = '[Switch Mode Failed]: Unknown device status' + + elif not self.isLogin: + # login failed + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Not login yet' + + elif len(self.privilegePw) == 0: + # self.privilegePw dosen't exist, do nothing + pass + + return result + + def _commit(self, saveCommand='write', exitCommand='end'): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if self.isConfigMode: + # Exit from configuration mode to privileged mode. + self._exitConfigMode(exitCommand) + # save setup to system + self.shell.send('%s\n' % (saveCommand)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + """ + If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. + in the received information, it indicates that the save configuration is successful. + """ + if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): + result['status'] = True + else: + raise ForwardError('[Commit Config Error]: The current state is not configuration mode') + except ForwardError, e: + result['errLog'] = str(e) + result['status'] = False + return result + + def addUser(self, username, password, addCommand='username {username} password {password}\n'): + """Create a user on the device. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if not addCommand: + raise ForwardError("Please specify the add user's command") + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # check terminal status + if self.isConfigMode: + self.cleanBuffer() + # adduser + self.shell.send(addCommand.format(username=username, password=password)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + """If the program is in the received message, it searches for character + information such as error and inavalid, indicating that the account creation failed. + """ + if re.search('error|invalid', result['content'], flags=re.IGNORECASE): + result['content'] = '' + raise ForwardError(result['content']) + else: + # set password is successed. + result = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result + + def deleteUser(self, username=''): + """Delete a user on the device + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if not username: + raise ForwardError("Please specify a username") + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # check terminal status + if self.isConfigMode: + self.cleanBuffer() + # delete username + self.shell.send("no username {username}\n".format(username=username)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + if re.search('error|invalid', result['content'], flags=re.IGNORECASE): + raise ForwardError(result['content']) + else: + # deleted username + result = self._commit() + result['status'] = True + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result + + def getUser(self, command="show running-config | in username"): + """Gets the list of users on the device. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # [{"username":"zhang-qichuan","secret":5},{}....] + userList = [] + # execute query command + info = self.execute(command) + if not info["status"]: + raise ForwardError("Error:get user list failed: %s" % info["errLog"]) + # process result + result = info["content"] + for line in result.split('\n'): + # Each line + index = 0 + # ['username' , 'test-user' , 'secret', '5','$.........'] + segments = line.split() + for segment in segments: + if index <= 1: + index += 1 + # Check after second fields username my-username secret/password ..... + continue + else: + if segment == "secret" or segment == "password": + # get secret level + userData = {"username": segments[1], "secret": segments[index + 1]} + userList.append(userData) + break + index += 1 + result["content"] = userList + result["status"] = True + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result + + def _configMode(self, cmd='conf term'): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # Flag isCOnfigMode is False + self.isConfigMode = False + result = { + "status": False, + "content": "", + "errLog": "" + } + self.cleanBuffer() + self.shell.send("%s\n" % (cmd)) + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Flag config mode is True + self.isConfigMode = True + result['status'] = True + return result + + def _exitConfigMode(self, cmd='end'): + """Exit from configuration mode to privileged mode. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # Check current status + if self.isConfigMode: + self.shell.send("%s\n" % (cmd)) + """Because the mode is switched, it is only based on basePrompt + to determine whether the message is returned when the message is received. + """ + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # Flag isCOnfigMode is False + self.isConfigMode = False + result["status"] = True + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + result["status"] = False + result['errLog'] = str(e) + # release host prompt + self.getPrompt() + return result + + def changePassword(self, username, password, addCommand='username {username} password {password}\n'): + """Modify the password for the device account. + Because the password command to modify the account on the device is consistent with the creation + of the user's command, the interface to create the account is called. + """ + self.addUser(self, username=username, password=password, addCommand=addCommand) diff --git a/lib/forward/devclass/baseDepp.py b/lib/forward/devclass/baseDepp.py new file mode 100644 index 0000000..4a1b301 --- /dev/null +++ b/lib/forward/devclass/baseDepp.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Depp. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEDEPP(BASESSHV2): + """This is a manufacturer of depp, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseF5.py b/lib/forward/devclass/baseF5.py new file mode 100644 index 0000000..d21ddd3 --- /dev/null +++ b/lib/forward/devclass/baseF5.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for F5. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEF5(BASESSHV2): + """This is a manufacturer of F5, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseFenghuo.py b/lib/forward/devclass/baseFenghuo.py new file mode 100644 index 0000000..5fc286c --- /dev/null +++ b/lib/forward/devclass/baseFenghuo.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Fenghuo. +Author: Cheung Kei-Chuen +""" +import re +from forward.devclass.baseSSHV2 import BASESSHV2 +from forward.utils.forwardError import ForwardError + + +class BASEFENGHUO(BASESSHV2): + """This is a manufacturer of fenghuo, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + def privilegeMode(self): + """Used to switch from normal mode to privileged mode for command line mode. + Does not apply to other modes to switch to privileged mode. + """ + self.privilegeModeCommand = 'enable' + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + self.cleanBuffer() + if self.isLogin and (len(self.privilegePw) > 0): + """This can only be performed when the device + has been successfully logged in and the privilege mode password is specified.""" + # (login succeed status) and (self.privilegePw exist) + self.cleanBuffer() + self.shell.send('%s\n' % (self.privilegeModeCommand)) + enableResult = '' + while True: + """ + etc: + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ + + or + + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + Password: + """ + """ + fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' + """ + # need password + passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand + promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( + command=self.privilegeModeCommand, + basePrompt=self.basePrompt + ) + + # Second layers of judgment, Privileged command char 'super/enable' must be received. + # otherwise recv continue... important! + if re.search(passwordChar, enableResult): + # if received 'password' + break + # no password + elif re.search(promptChar, enableResult): + # if no password + break + else: + # not finished,continue + enableResult += self.shell.recv(1024) + + if re.search('assword', enableResult): + # need password + self.shell.send("%s\n" % self.privilegePw) + result = '' + while not re.search(self.basePrompt, result) and (not re.search('assword|denied|Denied', result)): + result += self.shell.recv(1024) + if re.search('assword|denied|Denied', result): + # When send the self.privilegePw, once again encountered a password hint password wrong. + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Password incorrect' + elif re.search(self.basePrompt, result): + # Switch mode succeed + self.getPrompt() + result['status'] = True + + # Check the error information in advance + elif re.search('\%|Invalid|\^', enableResult): + # bad enable command + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' + elif re.search(self.basePrompt, enableResult): + # Switch mode succeed, don't need password + self.getPrompt() + result['status'] = True + else: + result['stauts'] = False + result['errLog'] = '[Switch Mode Failed]: Unknown device status' + + elif not self.isLogin: + # login failed + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Not login yet' + + elif len(self.privilegePw) == 0: + # self.privilegePw dosen't exist, do nothing + pass + return result + + def _commit(self, saveCommand='write file', exitCommand='quit'): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if self.isConfigMode: + self._exitConfigMode(exitCommand) + # save setup to system + self.shell.send('%s\n' % (saveCommand)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # When prompted, reply Y,Search range at last line + if re.search(re.escape("Are you sure?(y/n) [y]"), result['content'].split('\n')[-1]): + self.shell.send("y\n") + continue + """ + If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. + in the received information, it indicates that the save configuration is successful. + """ + if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): + result['status'] = True + # Clean buffer + self.cleanBuffer() + else: + raise ForwardError('[Commit Config Error]: The current state is not configuration mode') + except ForwardError, e: + result['errLog'] = str(e) + result['status'] = False + return result + + def _configMode(self, cmd='configure'): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # Flag isCOnfigMode is False + self.isConfigMode = False + result = { + "status": False, + "content": "", + "errLog": "" + } + self.cleanBuffer() + self.shell.send("%s\n" % (cmd)) + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Flag isCOnfigMode is True + self.isConfigMode = True + result['status'] = True + return result + + def _exitConfigMode(self, cmd='quit'): + """Exit from configuration mode to privileged mode. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # Check current status + if self.isConfigMode: + self.shell.send("%s\n" % (cmd)) + """Exit from configuration mode to privileged mode. + """ + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # Flag isCOnfigMode is False + self.isConfigMode = False + result["status"] = True + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + result["status"] = False + result['errLog'] = str(e) + # release host prompt + self.getPrompt() + return result diff --git a/lib/forward/devclass/baseFortinet.py b/lib/forward/devclass/baseFortinet.py new file mode 100644 index 0000000..0605df1 --- /dev/null +++ b/lib/forward/devclass/baseFortinet.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Fortinet. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEFORTINET(BASESSHV2): + """This is a manufacturer of foritinet, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseHuawei.py b/lib/forward/devclass/baseHuawei.py new file mode 100644 index 0000000..b62f2e4 --- /dev/null +++ b/lib/forward/devclass/baseHuawei.py @@ -0,0 +1,388 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# + +""" +-----Introduction----- +[Core][forward] Base device class for huawei basic device method, by using paramiko module. +Author: Cheung Kei-Chuen, Wangzhe +""" + +import re +from forward.devclass.baseSSHV2 import BASESSHV2 +from forward.utils.forwardError import ForwardError + + +class BASEHUAWEI(BASESSHV2): + """This is a manufacturer of huawei, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + def privilegeMode(self): + """Used to switch from normal mode to privileged mode for command line mode. + Does not apply to other modes to switch to privileged mode. + """ + self.privilegeModeCommand = 'super' + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + self.cleanBuffer() + if self.isLogin and (len(self.privilegePw) > 0): + # (login succeed status) and (self.privilegePw exist) + self.cleanBuffer() + self.shell.send('%s\n' % (self.privilegeModeCommand)) + enableResult = '' + while True: + """ + etc: + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ + + or + + [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super + Password: + """ + """ + fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' + """ + # need password + passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand + promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( + command=self.privilegeModeCommand, + basePrompt=self.basePrompt + ) + + # Second layers of judgment, Privileged command char 'super/enable' must be received. + # otherwise recv continue... important! + if re.search(passwordChar, enableResult): + # if received 'password' + break + # no password + elif re.search(promptChar, enableResult): + # if no password + break + else: + # not finished,continue + enableResult += self.shell.recv(1024) + + if re.search('assword', enableResult): + # need password + self.shell.send("%s\n" % self.privilegePw) + result = '' + while not re.search(self.basePrompt, result) and (not re.search('assword|denied|Denied', result)): + result += self.shell.recv(1024) + if re.search('assword|denied|Denied', result): + # When send the self.privilegePw, once again encountered a password hint password wrong. + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Password incorrect' + elif re.search(self.basePrompt, result): + # Switch mode succeed + self.getPrompt() + result['status'] = True + + # Check the error information in advance + elif re.search('\%|Invalid|\^', enableResult): + # bad enable command + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' + elif re.search(self.basePrompt, enableResult): + # Switch mode succeed, don't need password + self.getPrompt() + result['status'] = True + else: + result['stauts'] = False + result['errLog'] = '[Switch Mode Failed]: Unknown device status' + + elif not self.isLogin: + # login failed + result['status'] = False + result['errLog'] = '[Switch Mode Failed]: Not login yet' + + elif len(self.privilegePw) == 0: + # self.privilegePw dosen't exist, do nothing + pass + + return result + + def _commit(self, saveCommand='save', exitCommand='return'): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if self.isConfigMode: + # Exit from configuration mode to privileged mode. + self._exitConfigMode(exitCommand) + # save setup to system + self.shell.send('%s\n' % (saveCommand)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # When prompted, reply Y,Search range at last line + if re.search(re.escape("Are you sure to continue?[Y/N]"), result["content"].split("\n")[-1]): + self.shell.send("Y\n") + """ + If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. + in the received information, it indicates that the save configuration is successful. + """ + if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): + result['status'] = True + else: + raise ForwardError('[Commit Config Error]: The current state is not configuration mode') + except ForwardError, e: + result['errLog'] = str(e) + result['status'] = False + return result + + def addUser(self, username, password, userLevel=1): + """Create a user on the device. + """ + # user leve default 1 + data = {"status": False, + "content": "", + "errLog": ""} + try: + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + checkPermission = self._configMode(cmd='sys\naaa') + # swith to config terminal mode. + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + if self.isConfigMode: + # check terminal status + self.shell.send('local-user {username} password cipher {password}\n'.format(username=username, + password=password)) + while True: + # Check that the user is created. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and\ + (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + # Set the user level for the new user. + self.shell.send('local-user {username} privilege level {userLevel}\n'.format(username=username, + userLevel=userLevel)) + data['content'] = '' + while True: + # Check whether the user level Settings are complete. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and\ + (re.search('local-user .* privilege level[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + # Set the user terminal parameters. + self.shell.send("local-user {username} service-type terminal ssh\n".format(username=username)) + data['content'] = '' + while True: + # Check whether the user terminal parameters are set. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ + (re.search('local-user .* service-type terminal ssh[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + self.shell.send("quit\n") + data['content'] = '' + while True: + # Exit create user mode. + if (re.search(self.basePrompt, data['content'].split('\n')[-1])) and \ + (re.search('quit.*[\s\S]+%s' % self.basePrompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + self.getPrompt() + # Set the password for the new user. + self.shell.send("ssh user {username} authentication-type password\n".format(username=username)) + data['content'] = '' + while True: + # Check that the password is set. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ + (re.search('ssh user .* authentication-type password[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + # Set the user terminal parameters. + self.shell.send("ssh user {username} service-type all\n".format(username=username)) + data['content'] = '' + while True: + # # Check whether the user terminal parameters are set. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ + (re.search('ssh user .* service-type all[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + # Save the configuration + data = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['status'] = False + data['errLog'] = str(e) + return data + + def getUser(self, command="show running-config | in username"): + """Gets the list of users on the device. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # [{"username":"zhang-qichuan","secret":5},{}....] + userList = [] + # execute query command + info = self.execute(command) + if not info["status"]: + raise ForwardError("Error:get user list failed: %s" % info["errLog"]) + # process result + result = info["content"] + for line in result.split('\n'): + # Each line + index = 0 + # ['username' , 'test-user' , 'secret', '5','$.........'] + segments = line.split() + for segment in segments: + if index <= 1: + index += 1 + # Check after second fields username my-username secret/password ..... + continue + else: + if segment == "secret" or segment == "password": + # get secret level + userData = {"username": segments[1], "secret": segments[index + 1]} + userList.append(userData) + break + index += 1 + result["content"] = userList + result["status"] = True + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result + + def _configMode(self, cmd='sys'): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # cmd = 'sys\naaa' if addUser + # Flag config mode is False + self.isConfigMode = False + result = { + "status": False, + "content": "", + "errLog": "" + } + self.cleanBuffer() + self.shell.send("%s\n" % (cmd)) + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Flag config mode is True + self.isConfigMode = True + result['status'] = True + return result + + def _exitConfigMode(self, cmd='return'): + """Exit from configuration mode to privileged mode. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + self.getPrompt() + # Check current status + if self.isConfigMode: + self.shell.send("%s\n" % (cmd)) + """Because the mode is switched, it is only based on basePrompt + to determine whether the message is returned when the message is received. + """ + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # Flag isCOnfigMode is False + self.isConfigMode = False + result["status"] = True + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + result["status"] = False + result['errLog'] = str(e) + # release host prompt + self.getPrompt() + return result + + def changePassword(self, username, password, userLevel=1): + """Modify the password for the device account. + """ + # user leve default 1 + data = {"status": False, + "content": "", + "errLog": ""} + try: + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + checkPermission = self._configMode() + # swith to config terminal mode. + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + if self.isConfigMode: + # check terminal status + self.shell.send('local-user {username} password cipher {password}\n'.format(username=username, + password=password)) + while True: + # Check that the password has been modified + if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ + (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + data = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['status'] = False + data['errLog'] = str(e) + return data + + def deleteUser(self, username): + """Delete a user on the device + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + if self.isConfigMode: + # check terminal status + self.cleanBuffer() + self.shell.send('undo local-user {username}\n'.format(username=username)) + while True: + # Check whether the user has been deleted. + if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ + (re.search('undo local-user[\s\S]+%s' % self.prompt, data['content'])): + break + else: + data['content'] += self.shell.recv(1024) + # When prompted, reply Y,Search range at last line + if re.search('error|invalid', data['content'], flags=re.IGNORECASE): + raise ForwardError(data['content']) + # Save the configuration + data = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['status'] = False + data['errLog'] = str(e) + return data diff --git a/lib/forward/devclass/baseJuniper.py b/lib/forward/devclass/baseJuniper.py new file mode 100644 index 0000000..13cc52c --- /dev/null +++ b/lib/forward/devclass/baseJuniper.py @@ -0,0 +1,270 @@ +#!/usr/bin/evn python +# coding:utf-8 +""" It applies only to models of network equipment mx960 + See the detailed comments mx960.py +""" +import re +from forward.devclass.baseTELNET import BASETELNET +from forward.utils.forwardError import ForwardError + + +class BASEJUNIPER(BASETELNET): + """This is a manufacturer of juniper, using the + telnet version of the protocol, so it is integrated with BASELTELNET library. + """ + def _recv(self, _prompt): + """The user receives the message returned by the device. + """ + data = {"status": False, + "content": "", + "errLog": ""} + # If the host prompt is received, the message is stopped. + i = self.channel.expect([r"%s" % _prompt], timeout=self.timeout) + try: + if i[0] == -1: + raise ForwardError('Error: receive timeout') + data['status'] = True + # Get result + data['content'] = i[-1] + except ForwardError, e: + data['errLog'] = str(e) + return data + + def _configMode(self): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # Flag isCOnfigMode is False + self.isConfigMode = False + data = {"status": False, + "content": "", + "errLog": ""} + self.cleanBuffer() + self.channel.write("configure\n") + # Get result + data = self._recv(self.basePrompt) + if data['status']: + self.isConfigMode = True + self.getPrompt() + return data + + def _exitConfigMode(self): + """Exit from configuration mode to privileged mode. + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # Check current status + if self.isConfigMode: + self.channel.write("exit\n") + # Get result + data = self._recv(self.basePrompt) + if data['status']: + self.isConfigMode = False + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + self.getPrompt() + return data + + def _commit(self): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # Check status + if self.isConfigMode: + self.channel.write('commit\n') + result = self._recv(self.prompt) + # If the success character is found, it is successful. + if re.search('succeeds', result['content'], flags=re.IGNORECASE): + data['status'] = True + else: + data['content'] = result['content'] + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def addUser(self, username, password, admin=False): + """Create a user on the device. + """ + # Separate commands to create administrator accounts and common accounts. + if admin: + command = "set system login user {username} class read-only\n".format(username=username) + else: + command = "set system login user {username} class ABC\n".format(username=username) + data = {"status": False, + "content": "", + "errLog": ""} + try: + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + checkPermission = self._configMode() # swith to config terminal mode. + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # check terminal status + if self.isConfigMode: + # adduser + self.channel.write(command) + # recv result + data = self._recv(self.prompt) + if not data['status']: + # break + raise ForwardError(data['errLog']) + # execute useradd command + self.channel.write('set system login user {username} \ + authentication plain-text-password\n'.format(username=username)) + i = self.channel.expect([r"New password:", r"%s" % self.prompt], timeout=self.timeout) + result = i[-1] + if re.search('error|invalid', result, flags=re.IGNORECASE): + # command failure + raise ForwardError(result) + # Enter password + self.channel.write("{password}\n".format(password=password)) + # check password + i = self.channel.expect([r"Retype new password:", r"%s" % self.prompt], timeout=self.timeout) + # repassword + if i[0] == 0: + self.channel.write("{password}\n".format(password=password)) + # check password + i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) + if i[0] == 0: + result = i[-1] + if re.search('error|invalid', result, flags=re.IGNORECASE): + raise ForwardError(result) + else: + # set password is successed. + data = self._commit() + # exit config terminal mode. + self._exitConfigMode() + elif i[0] == -1: + raise ForwardError('Error: receive timeout') + elif i[0] == 1: + # password wrong + raise ForwardError(i[-1]) + elif i[0] == -1: + # timeout + raise ForwardError('Error: receive timeout') + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def deleteUser(self, username): + """Delete a user on the device + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + if not username: + raise ForwardError('Please specify a username') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # check terminal status + if self.isConfigMode: + # delete user + self.channel.write('delete system login user {username}\n'.format(username=username)) + i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) + result = i[-1] + if re.search('error|invalid', result, flags=re.IGNORECASE): + # command failure + raise ForwardError(result) + else: + # Save + data = self._commit() + # exit config terminal mode. + self._exitConfigMode() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def changePassword(self, username, password): + """Modify the password for the device account. + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # check terminal status + if self.isConfigMode: + # execute useradd command + self.channel.write('set system login user {username} \ + authentication plain-text-password\n'.format(username=username)) + i = self.channel.expect([r"New password:", r"%s" % self.prompt], timeout=self.timeout) + result = i[-1] + if re.search('error|invalid', result, flags=re.IGNORECASE): + # command failure + raise ForwardError(result) + # Enter password + self.channel.write("{password}\n".format(password=password)) + # check password + i = self.channel.expect([r"Retype new password:", r"%s" % self.prompt], timeout=self.timeout) + if i[0] == 0: + # repassword + self.channel.write("{password}\n".format(password=password)) + # check password + i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) + if i[0] == 0: + # Get result. + result = i[-1] + if re.search('error|invalid', result, flags=re.IGNORECASE): + raise ForwardError(result) + else: + # change password is successed. + data = self._commit() + # exit config terminal mode. + self._exitConfigMode() + elif i[0] == -1: + raise ForwardError('Error: receive timeout') + elif i[0] == 1: + # password wrong + raise ForwardError(i[-1]) + elif i[0] == -1: + # timeout + raise ForwardError('Error: receive timeout') + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + # def bindBandwidth(self, ip='', bandwidth=''): + # njInfo = {"status": False, + # "content": "", + # "errLog": ""} + # mx960Bandwidth = Bandwidth(ip=ip, bandwidth=bandwidth, shell=self) + # njInfo = mx960Bandwidth.bindBandwidth() + # return njInfo + # + # def deleteBindIPAndBandwidth(self, ip='', bandwidth=''): + # njInfo = {"status": False, + # "content": "", + # "errLog": ""} + # mx960Bandwidth = Bandwidth(ip=ip, bandwidth=bandwidth, shell=self) + # njInfo = mx960Bandwidth.deleteBindIPAndBandwidth() + # return njInfo diff --git a/lib/forward/devclass/baseLinux.py b/lib/forward/devclass/baseLinux.py new file mode 100644 index 0000000..53f2c47 --- /dev/null +++ b/lib/forward/devclass/baseLinux.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Base device class for sshv2 method, by using paramiko module. +Author: Wangzhe +""" + +import re +from forward.devclass.baseSSHV2 import BASESSHV2 +from forward.utils.forwardError import ForwardError + + +class BASELINUX(BASESSHV2): + """This is a manufacturer of linux, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + def privilegeMode(self): + """Used to switch from normal mode to privileged mode for command line mode. + Does not apply to other modes to switch to privileged mode. + """ + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + return result + + def addUser(self, username, password, **kwargs): + """Create a user on the device. + """ + # Extra parameters + group = kwargs['group'] if 'group' in kwargs else username + commandAdduser = 'adduser %s' % username if group == username else 'adduser --gid %s %s' % (group, username) + commandPw = 'passwd %s\n' % username + + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # legal check + if not group: + raise ForwardError("[Add User Error]: %s: Group could NOT be blank." % self.ip) + if not username or not password: + raise ForwardError("[Add User Error]: %s: Username or Password could NOT be blank." % self.ip) + + if self.isLogin: + # execute adduser + addUserResult = self.execute(commandAdduser) + if addUserResult['status']: + dirExtPattern = '(目录已经存在|home directory already exists)' + + if not addUserResult['content']: + # success + pass + elif re.search(dirExtPattern, addUserResult['content']): + # success, but homedir already exist + pass + else: + # other errors + raise ForwardError("[Add User Error]: %s: %s" % (self.ip, addUserResult['content'])) + + # set passwd + self.shell.send(commandPw) + buff = '' + while not (re.search(self.basePrompt, buff) or re.search('New password:', buff)): + buff += self.shell.recv(256) + if re.search('New password:', buff): + # send password + self.shell.send(password + '\n') + buff = '' + while not (re.search(self.basePrompt, buff) or re.search('Retype new password:', buff)): + buff += self.shell.recv(256) + if re.search('Retype new password:', buff): + # Confirm password + self.shell.send(password + '\n') + buff = '' + while not re.search(self.prompt, buff): + buff += self.shell.recv(256) + # successed. + if re.search('updated successfully', buff): + result['status'] = True + return result + + # error somewhere, raise + raise ForwardError("[Set Password Error]: %s: %s" % (self.ip, buff)) + else: + raise ForwardError("[Add User Error]: %s: %s" % (self.ip, addUserResult['errLog'])) + else: + raise ForwardError("[Add User Error]: %s: Not login yet." % self.ip) + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result + + def deleteUser(self, username): + """Delete a user on the device + """ + # set command + commandDelUser = 'userdel %s' % username + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + if not username: + raise ForwardError("[Delete User Error]: %s: Username could NOT be blank." % self.ip) + # Login status check. + if self.isLogin: + # send command. + delUserResult = self.execute(commandDelUser) + if delUserResult['status']: + if not delUserResult['content']: + # success + pass + else: + # failed. + raise ForwardError("[Delete User Error]: %s: %s" % (self.ip, delUserResult['content'])) + result['status'] = True + return result + else: + raise ForwardError("[Delete User Error]: %s: %s" % (self.ip, delUserResult['errLog'])) + else: + raise ForwardError("[Delete User Error]: %s: Not login yet." % self.ip) + except ForwardError, e: + result['status'] = False + result['errLog'] = str(e) + return result diff --git a/lib/forward/devclass/baseMaipu.py b/lib/forward/devclass/baseMaipu.py new file mode 100644 index 0000000..a84df35 --- /dev/null +++ b/lib/forward/devclass/baseMaipu.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Maipu. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseSSHV1 import BASESSHV1 + + +class BASEMAIPU(BASESSHV1): + """This is a manufacturer of maipu, using the + SSHV1 version of the protocol, so it is integrated with BASESSHV1 library. + """ + pass diff --git a/lib/forward/devclass/baseRaisecom.py b/lib/forward/devclass/baseRaisecom.py new file mode 100644 index 0000000..8b230e6 --- /dev/null +++ b/lib/forward/devclass/baseRaisecom.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Raisecom. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASERAISECOM(BASESSHV2): + """This is a manufacturer of raisecom, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/baseRuijie.py b/lib/forward/devclass/baseRuijie.py new file mode 100644 index 0000000..7ec92b4 --- /dev/null +++ b/lib/forward/devclass/baseRuijie.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Ruijie. +Author: Cheung Kei-Chuen +""" +import re +from forward.devclass.baseSSHV2 import BASESSHV2 +from forward.utils.forwardError import ForwardError + + +class BASERUIJIE(BASESSHV2): + """This is a manufacturer of maipu, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + + def cleanBuffer(self): + """Because the device USES the cleanBuffer method in different details, + it can be rewritten to modify the function. + """ + if self.shell.recv_ready(): + self.shell.recv(4096) + # Ruijie equipment does not support sending line, must be sent to some characters + self.shell.send(' \n') + buff = '' + # When after switching mode, the prompt will change, it should be based on basePrompt to check and at last line + while not re.search(self.basePrompt, buff.split('\n')[-1]): + try: + # Accumulative results + buff += self.shell.recv(1024) + except Exception: + raise ForwardError('[Clean Buffer Error]: %s: Receive timeout [%s]' % (self.ip, buff)) diff --git a/lib/forward/devclass/baseSSHV1.py b/lib/forward/devclass/baseSSHV1.py new file mode 100644 index 0000000..d43d6ef --- /dev/null +++ b/lib/forward/devclass/baseSSHV1.py @@ -0,0 +1,316 @@ +#!/usr/bin/evn python +# coding:utf-8 +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Base device class for sshv1 method, by using pexpect module. +Author: Azrael, Cheung Kei-Chuen +""" +import re +from forward.utils.sshv1 import sshv1 +from forward.utils.forwardError import ForwardError +import pexpect + + +class BASESSHV1(object): + def __init__(self, ip, username, password, **kwargs): + """Init a sshv1-like class instance, accept port/timeout/privilegePw as extra parameters + """ + self.ip = ip + self.username = username + self.password = password + + self.port = kwargs['port'] if 'port' in kwargs else 22 + self.timeout = kwargs['timeout'] if 'timeout' in kwargs else 30 + self.privilegePw = kwargs['privilegePw'] if 'privilegePw' in kwargs else '' + + self.isLogin = False + self.isEnable = False + + self.channel = '' + self.shell = '' + self.basePrompt = r'(>|#|\]|\$|\)) *$' + self.prompt = '' + self.moreFlag = '(\-)+( |\()?[Mm]ore.*(\)| )?(\-)+' + + """ + - parameter ip: device's ip + - parameter port : device's port + - parameter timeout : device's timeout(Only for login,not for execute) + - parameter channel: storage device connection channel session + - parameter shell: paramiko shell, used to send(cmd) and recv(result) + - parameter prompt: [ex][wangzhe@cloudlab100 ~]$ + - parameter njInfo : return interactive data's format + """ + + def login(self): + """Loging method + Creates a login session for the program to send commands to the target device. + """ + result = { + 'status': False, + 'errLog': '' + } + # sshv1(ip,username,password,tport=22,timeout,) + sshChannel = sshv1(ip=self.ip, + username=self.username, + password=self.password, + port=self.port, + timeout=self.timeout) + if sshChannel['status']: + # Login succeed, init shell + result['status'] = True + self.channel = sshChannel['content'] + # Record login status to True. + self.isLogin = True + # Get host prompt. + self.getPrompt() + # Clear legacy characters + self.cleanBuffer() + else: + # Login failed. + self.isLogin = False + result['errLog'] = sshChannel['errLog'] + return result + + def __del__(self): + # Logout after the program leaves. + self.logout() + + def logout(self): + """Login method + A session used to log out of a target device + """ + result = { + 'status': False, + 'errLog': '' + } + try: + # Close SSH + self.channel.close() + # Modify login status to False. + self.isLogin = False + result['status'] = True + except Exception, e: + # If the close fails, set the login status to False and record the failure message + result['status'] = False + result['errLog'] = str(e) + return result + + def enable(self, password): + """No use. + """ + pass + + def execute(self, cmd): + """execute a command line, only suitable for the scene when + the prompt is equal before and after execution + """ + # Remove legacy data from the SSH before executing the command. + self.cleanBuffer() + # dataPattern = re.escape(cmd)+'.*\r\n([\s\S]*)\r\n'+self.prompt + dataPattern = '[\r\n]+([\s\S]*)[\r\n]+' + # SSHV1 pexpect not have self.prompt end + data = {'status': False, + 'content': '', + 'errLog': ''} + if self.isLogin: + # check login status + # [ex] when send('ls\r'),get 'ls\r\nroot base etc \r\n[wangzhe@cloudlab100 ~]$ ' + # [ex] data should be 'root base etc ' + self.channel.send(cmd + '\n') + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.prompt, pexpect.TIMEOUT], timeout=self.timeout) + result = '' + if i == 0: + """If the data received by the program contains the last line of information + similar to the More type-ending message, it indicates that the command needs + to send a space for More messages. + """ + result = self.channel.before + # Get more result + result += self.getMore() + elif i == 2: + # Execute timeout + data['errLog'] = 'Error: receive timeout ' + else: + # Execute successed. + result = self.channel.before + data['content'] += result + data["status"] = True + try: + tmp = re.search(dataPattern, data['content']).group(1) + # Delete special characters caused by More split screen. + tmp = re.sub("<--- More --->\\r +\\r", "", tmp) + data['content'] = tmp + except Exception, e: + # Unable to find the host prompt, command execution failed. + data['status'] = False + data['errLog'] = data['errLog'] + "not fond host prompt:Error(%s)" % str(e) + else: + data['status'] = False + data['errLog'] = 'ERROR:device not login' + return data + + def getMore(self): + # Applies to the execute method + """Automatically get the current system prompt by sending a carriage return + """ + result = '' + while True: + # The return message is received until there is no More character like More. + self.channel.send(' ') + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.prompt, pexpect.TIMEOUT], timeout=self.timeout) + if i == 0: + result += self.channel.before + # After the encounter `moreFlag`, need to get the message + elif i == 1: + result += self.channel.before + # After the encounter prompt, need to get the result + break + else: + break + return result + + def newGetMore(self, prompt, timeout): + # Applies to the command method + # The return message is received until there is no More character like More. + result = '' + state = None + continueRecv = False + while True: + if not continueRecv: + self.channel.send('\r') + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.basePrompt, pexpect.TIMEOUT], timeout=timeout) + if i == 0: + result += self.channel.before + # After the encounter `moreFlag`, need to get the message + elif i == 1: + result += self.channel.before + result += self.channel.after + # After the encounter prompt, need to get the result + for section in prompt: + # section.values() is : [ [p1,p2,p3] ] + for _prompt in section.values()[0]: + if re.search(_prompt, result.split("\n")[-1]): + state = section.keys()[0] + break + # Find the specified state type + if state is not None: + break + # Find the specified state type,exit + if state is not None: + break + else: + # Not found,Continue to receive + continueRecv = True + else: + raise ForwardError("function: getMore recv timeout") + return (result, state) + + def getPrompt(self): + """Automatically get the current system prompt by sending a carriage return + """ + if self.isLogin: + # login status True + self.channel.send('\n') + """The host base prompt is the end of the received flag, and if the data is + not received at the set time, the timeout is exceeded. + """ + self.channel.expect([r"%s" % self.basePrompt, pexpect.TIMEOUT], timeout=self.timeout) + # select last line character,[ex]' >[localhost@labstill019~]$ ' + # [ex]'>[localhost@labstill019~]$' + # self.prompt=self.prompt.split()[0] + # [ex]'[localhost@labstill019~]' + # self.prompt=self.prompt[1:-1] + # [ex]'\\[localhost\\@labstill019\\~\\]$' + self.prompt = self.channel.before.split('\n')[-1] + "(>|#|\$|\]|\)) *$" + else: + raise ForwardError('[Get Prompt Error]: %s: Not login yet.' % self.ip) + return self.prompt + + def cleanBuffer(self): + """Clean the shell buffer whatever they are, by sending a carriage return + """ + self.channel.send('\n') + try: + """When after switching mode, the prompt will change, it should be based + on basePrompt to check and at last line + """ + return self.channel.expect(self.prompt, timeout=self.timeout) + except pexpect.TIMEOUT: + # No legacy data. + return '' + + def command(self, cmd=None, prompt=None, timeout=30): + """execute a command line, powerful and suitable for any scene, + but need to define whole prompt dict list + """ + result = { + 'status': True, + 'content': '', + 'errLog': '', + "state": None + } + # Parameters check + if (cmd is None) or (not isinstance(prompt, list)) or (not isinstance(timeout, int)): + raise ForwardError("""You should pass such a form of argument: \ +CMD = 'Your command', prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}] ,\ +timeout=30""") + for section in prompt: + if not isinstance(section.values(), list): + raise ForwardError("""you should pass such a form of argument:\ +prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]""") + try: + self.channel.send("{cmd}\r".format(cmd=cmd)) + try: + info = '' + while True: + """ First, the program accepts the return message based on the base prompt, and if program + accept it directly from the specified prompt, there will be many times out of time in the + middle,resulting in reduced efficiency""" + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.basePrompt, + pexpect.TIMEOUT], timeout=timeout) + if i == 2: + """The host prompt is not finished with the traditional # $ > + and you need to set it like that. + """ + raise ForwardError('Error: base prompt receive timeout') + if i == 0: + info += self.channel.before + # Get More then result + tmp = self.newGetMore(prompt, timeout) + info += tmp[0] + result["state"] = tmp[1] + # To complete the receiving + break + else: + # To complete the receiving + info += self.channel.before + # read base prompt + info += self.channel.after + for section in prompt: + # section.values() is : [ [p1,p2,p3] ] + for _prompt in section.values()[0]: + if re.search(_prompt, info.split("\n")[-1]): + result["state"] = section.keys()[0] + break + # Find the specified state type + if not result["state"] is None: + break + # Find the specified state type,exit + if not result["state"] is None: + break + result['content'] += info + # Delete special characters caused by More split screen. + result["content"] = re.sub("<--- More --->\\r +\\r", "", result["content"]) + except Exception, e: + # If program accept a timeout, cancel SSH + self.logout() + raise ForwardError(str(e)) + except Exception, e: + # Program run failed + result["errLog"] = str(e) + result["status"] = False + return result diff --git a/lib/forward/devclass/baseSSHV2.py b/lib/forward/devclass/baseSSHV2.py new file mode 100644 index 0000000..a95c0f8 --- /dev/null +++ b/lib/forward/devclass/baseSSHV2.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Base device class for sshv2 method, by using paramiko module. +Author: Azrael, Cheung Kei-Chuen +""" + +import re +from forward.utils.sshv2 import sshv2 +from forward.utils.forwardError import ForwardError + + +class BASESSHV2(object): + def __init__(self, ip, username, password, **kwargs): + """Init a sshv2-like class instance, accept port/timeout/privilegePw as extra parameters + """ + self.ip = ip + self.username = username + self.password = password + + self.port = kwargs['port'] if 'port' in kwargs else 22 + self.timeout = kwargs['timeout'] if 'timeout' in kwargs else 30 + self.privilegePw = kwargs['privilegePw'] if 'privilegePw' in kwargs else '' + + self.isLogin = False + self.isEnable = False + + self.channel = '' + self.shell = '' + self.basePrompt = r'(>|#|\]|\$|\)) *$' + self.prompt = '' + self.moreFlag = '(\-)+( |\()?[Mm]ore.*(\)| )?(\-)+' + + """ + - parameter ip: device's ip + - parameter port : device's port + - parameter timeout : device's timeout(Only for login,not for execute) + - parameter channel: storage device connection channel session + - parameter shell: paramiko shell, used to send(cmd) and recv(result) + - parameter prompt: [ex][wangzhe@cloudlab100 ~]$ + """ + + def __del__(self): + # Logout after the program leaves. + self.logout() + + def login(self): + """Login method. + Creates a login session for the program to send commands to the target device. + """ + result = { + 'status': False, + 'errLog': '' + } + # sshv2(ip,username,password,timeout,port=22) + sshChannel = sshv2(self.ip, self.username, self.password, self.timeout, self.port) + if sshChannel['status']: + # Login succeed, init shell + try: + result['status'] = True + self._channel = sshChannel['content'] + # resize virtual console window size to 10000*10000 + self.shell = self._channel.invoke_shell(width=10000, height=10000) + self.channel = self.shell + tmpBuffer = '' + while ( + not re.search(self.basePrompt, tmpBuffer.split('\n')[-1]) + ) and ( + not re.search('new +password', tmpBuffer.split('\n')[-1], flags=re.IGNORECASE) + ): + tmpBuffer += self.shell.recv(1024) + # if prompt is 'New Password' ,raise Error. + if re.search('new +password', tmpBuffer.split('\n')[-1], flags=re.IGNORECASE): + raise ForwardError( + '[Login Error]: %s: Password expired, needed to be updated!' % self.ip + ) + self.shell.settimeout(self.timeout) + # Record login status to True. + self.isLogin = True + self.getPrompt() + except Exception as e: + result['status'] = False + result['errLog'] = str(e) + else: + # Login failed + self.isLogin = False + result['errLog'] = sshChannel['errLog'] + return result + + def logout(self): + """Logout method + A session used to log out of a target device + """ + result = { + 'status': False, + 'errLog': '' + } + try: + # Close SSH + self._channel.close() + # Modify login status to False. + self.isLogin = False + result['status'] = True + except Exception as e: + result['status'] = False + result['errLog'] = str(e) + return result + + def execute(self, cmd): + """execute a command line, only suitable for the scene when + the prompt is equal before and after execution + """ + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + self.cleanBuffer() + if self.isLogin: + # check login status + # [ex] when send('ls\r'),get 'ls\r\nroot base etc \r\n[wangzhe@cloudlab100 ~]$ ' + # [ex] data should be 'root base etc ' + self.shell.send(cmd + "\r") + resultPattern = '[\r\n]+([\s\S]*)[\r\n]+' + self.prompt + try: + while not re.search(self.prompt, result['content'].split('\n')[-1]): + self.getMore(result['content']) + result['content'] += self.shell.recv(1024) + # try to extract the return data + tmp = re.search(resultPattern, result['content']).group(1) + # Delete special characters caused by More split screen. + tmp = re.sub("<--- More --->\\r +\\r", "", tmp) + result['content'] = tmp + except Exception as e: + # pattern not match + result['status'] = False + result['content'] = result['content'] + result['errLog'] = str(e) + else: + # not login + result['status'] = False + result['errLog'] = '[Execute Error]: device not login' + return result + + def command(self, cmd=None, prompt=None, timeout=30): + """execute a command line, powerful and suitable for any scene, + but need to define whole prompt dict list + """ + result = { + 'status': True, + 'content': '', + 'errLog': '', + "state": None + } + # Parameters check + if (cmd is None) or (not isinstance(prompt, list)) or (not isinstance(timeout, int)): + raise ForwardError("""You should pass such a form of argument: \ +CMD = 'Your command', prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]""") + for section in prompt: + if not isinstance(section.values(), list): + raise ForwardError("""you should pass such a form of argument:\ +prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]""") + try: + self.shell.send("{cmd}\r".format(cmd=cmd)) + try: + while True: + self.getMore(result['content']) + result["content"] += self.shell.recv(1024) + for section in prompt: + # section.values() is : [ [p1,p2,p3] ] + for _prompt in section.values()[0]: + if re.search(_prompt, result["content"].split("\n")[-1]): + result["state"] = section.keys()[0] + break + # Find the specified state type + if not result["state"] is None: + break + # Find the specified state type,exit + if not result["state"] is None: + break + result["content"] = re.sub("<--- More --->\\r +\\r", "", result["content"]) + # If you accept a timeout, cancel SSH + except Exception, e: + self.logout() + raise ForwardError(str(e)) + except Exception, e: + result["errLog"] = str(e) + result["status"] = False + return result + + def getPrompt(self): + """Automatically get the current system prompt by sending a carriage return + """ + if self.isLogin: + # login status True + result = '' + self.cleanBuffer() + self.shell.send('\n') + # set recv timeout to self.timeout/10 fot temporary + while not re.search(self.basePrompt, result): + result += self.shell.recv(1024) + if result: + # recv() get something + # select last line character,[ex]' >[localhost@labstill019~]$ ' + self.prompt = result.split('\n')[-1] + # [ex]'>[localhost@labstill019~]$' + # self.prompt=self.prompt.split()[0] + # [ex]'[localhost@labstill019~]' + # self.prompt=self.prompt[1:-1] + # [ex]'\\[localhost\\@labstill019\\~\\]$' + self.prompt = re.escape(self.prompt) + return self.prompt + else: + # timeout,get nothing,raise error + raise ForwardError('[Get Prompt Error]: %s: Timeout,can not get prompt.' % self.ip) + else: + # login status failed + raise ForwardError('[Get Prompt Error]: %s: Not login yet.' % self.ip) + + def getMore(self, bufferData): + """Automatically get more echo infos by sending a blank symbol + """ + # if check buffer data has 'more' flag, at last line. + if re.search(self.moreFlag, bufferData.split('\n')[-1]): + # can't used to \n and ' \r' ,because product enter character + self.shell.send(' ') + + def cleanBuffer(self): + """Clean the shell buffer whatever they are, by sending a carriage return + """ + if self.shell.recv_ready(): + self.shell.recv(4096) + self.shell.send('\n') + buff = '' + # When after switching mode, the prompt will change, it should be based on basePrompt to check and at last line + while not re.search(self.basePrompt, buff.split('\n')[-1]): + try: + buff += self.shell.recv(1024) + except Exception: + raise ForwardError('[Clean Buffer Error]: %s: Receive timeout [%s]' % (self.ip, buff)) diff --git a/lib/forward/devclass/baseTELNET.py b/lib/forward/devclass/baseTELNET.py new file mode 100644 index 0000000..50664ee --- /dev/null +++ b/lib/forward/devclass/baseTELNET.py @@ -0,0 +1,275 @@ +#!/usr/bin/evn python +# coding:utf-8 +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Base device class for telnet method, by using telnetlib module. +Author: Azrael, Cheung Kei-Chuen +""" +import re +from forward.utils.telnet import telnet +from forward.utils.forwardError import ForwardError + + +class BASETELNET(object): + def __init__(self, ip, username, password, **kwargs): + """Init a telnet-like class instance, accept port/timeout/privilegePw as extra parameters + """ + self.ip = ip + self.username = username + self.password = password + + self.port = kwargs['port'] if 'port' in kwargs else 23 + self.timeout = kwargs['timeout'] if 'timeout' in kwargs else 30 + self.privilegePw = kwargs['privilegePw'] if 'privilegePw' in kwargs else '' + + self.isLogin = False + self.isEnable = False + + self.channel = '' + self.shell = '' + self.basePrompt = r'(>|#|\]|\$|\)) *$' + self.prompt = '' + self.moreFlag = '(\-)+( |\()?[Mm]ore.*(\)| )?(\-)+' + + """ + - parameter ip: device's ip + - parameter port : device's port + - parameter timeout : device's timeout(Only for login,not for execute) + - parameter channel: storage device connection channel session + - parameter shell: paramiko shell, used to send(cmd) and recv(result) + - parameter prompt: [ex][wangzhe@cloudlab100 ~]$ + - parameter njInfo : return interactive data's format + """ + + def login(self): + """Login method + Creates a login session for the program to send commands to the target device. + """ + result = { + 'status': False, + 'errLog': '' + } + # telnet(ip,username,password,port=23,timeout) + sshChannel = telnet(ip=self.ip, + username=self.username, + password=self.password, + port=self.port, + timeout=self.timeout) + if sshChannel['status']: + # Login succeed, init shell + self.channel = sshChannel['content'] + # Record login status to True. + self.isLogin = True + # Get host prompt. + self.getPrompt() + result['status'] = True + else: + result['errLog'] = sshChannel['errLog'] + return result + + def __del__(self): + # Logout after the program leaves. + self.logout() + + def logout(self): + """Logout method + A session used to log out of a target device + """ + result = { + 'status': False, + 'errLog': '' + } + try: + # Close SSH + self.channel.close() + # Modify login status to False. + self.isLogin = False + result['status'] = True + except Exception, e: + result['status'] = False + result['content'] = str(e) + return result + + def execute(self, cmd): + """execute a command line, only suitable for the scene when + the prompt is equal before and after execution + """ + dataPattern = '[\r\n]+([\s\S]*)[\r\n]+' + self.prompt + # Spaces will produce special characters and re.escape('show ver') --> show \\ ver + data = {'status': False, + 'content': '', + 'errLog': ''} + if self.isLogin: + # check login status + # [ex] when send('ls\r'),get 'ls\r\nroot base etc \r\n[wangzhe@cloudlab100 ~]$ ' + # [ex] data should be 'root base etc ' + self.cleanBuffer() + self.channel.write(cmd + "\n") + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.prompt], timeout=self.timeout) + # Get result + result = i[-1] + try: + if i[0] == 0: + # Receive more characters + result += self.getMore() + elif i[0] == -1: + # Recvive timeout + raise ForwardError('Error: receive timeout ') + data['content'] += result + try: + # Intercept command result + tmp = re.search(dataPattern, data['content']).group(1) + # Delete special characters caused by More split screen. + tmp = re.sub("<--- More --->\\r +\\r", "", tmp) + data['content'] = tmp + data['status'] = True + except Exception, e: + # Not found host prompt + raise ForwardError('not found host prompt Errorr(%s)' % str(e)) + except Exception, e: + # Not found host prompt + data['status'] = False + data['errLog'] = data['errLog'] + 'not found host prompt Errorr(%s)' % str(e) + else: + # Not login + data['status'] = False + data['content'] = 'ERROR:device not login' + return data + + def getMore(self): + # Apply to the execute method + """Automatically get more echo infos by sending a blank symbol + """ + result = '' + while True: + # The return message is received until there is no More character like More. + self.channel.send(' ') + i = self.channel.expect([r'%s' % self.moreFlag, self.prompt], timeout=self.timeout) + # Get result + result += i[-1] + if i[0] == 1: + break + return result + + def newGetMore(self, prompt, timeout): + # Applies to the command method + """Automatically get more echo infos by sending a blank symbol + """ + result = '' + state = None + continueRecv = False + while True: + # If the acceptance is not complete, you cannot send a space + if not continueRecv: + self.channel.send(' ') + i = self.channel.expect([r'%s' % self.moreFlag, self.basePrompt], timeout=timeout) + # Get result + result += i[-1] + if i[0] == 0: + # Get more + continue + if i[0] == 1: + # Find the base host prompt. + for section in prompt: + # section.values() is : [ [p1,p2,p3] ] + for _prompt in section.values()[0]: + if re.search(_prompt, result.split("\n")[-1]): + state = section.keys()[0] + break + # Find the specified state type + if state is not None: + break + # Find the specified state type,exit + if state is not None: + break + else: + # Not found,Continue to receive + continueRecv = True + else: + raise ForwardError('getMore recv timeout:[%s]' % result) + return (result, state) + + def getPrompt(self): + """Automatically get the current system prompt by sending a carriage return + """ + self.channel.send('\n') + i = self.channel.expect([r"%s" % self.basePrompt], timeout=self.timeout) + # select last line character,[ex]' >[localhost@labstill019~]$ ' + # [ex]'>[localhost@labstill019~]$' + # self.prompt=self.prompt.split()[0] + # [ex]'[localhost@labstill019~]' + # self.prompt=self.prompt[1:-1] + # [ex]'\\[localhost\\@labstill019\\~\\]$' + self.prompt = re.escape(i[-1].split('\n')[-1]) + return self.prompt + + def cleanBuffer(self): + """Clean the shell buffer whatever they are, by sending a carriage return + """ + self.channel.send('\n') + i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) + result = i[-1] + return result + + def command(self, cmd=None, prompt=None, timeout=30): + """execute a command line, powerful and suitable for any scene, + but need to define whole prompt dict list + """ + result = { + 'status': True, + 'content': '', + 'errLog': '', + "state": None + } + # Parameters check + if (cmd is None) or (not isinstance(prompt, list)) or (not isinstance(timeout, int)): + raise ForwardError("""You should pass such a form of argument: \ +CMD = 'Your command', prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}] ,\ +timeout=30""") + for section in prompt: + if not isinstance(section.values(), list): + raise ForwardError("""you should pass such a form of argument:\ +prompt = [{" success ": ['prompt1', 'prompt2']}, {" error" : ['prompt3', 'prompt4']}]""") + try: + self.channel.write("{cmd}\r".format(cmd=cmd)) + try: + info = '' + while True: + """ First, the program accepts the return message based on the base prompt, and if you accept + it directly from the specified prompt, there will be many times out of time in the middle, + resulting in reduced efficiency""" + i = self.channel.expect([r'%s' % self.moreFlag, r"%s" % self.basePrompt], timeout=timeout) + info += i[-1] + if i[0] == 0: + tmp = self.newGetMore(prompt, timeout) + info += tmp[0] + result["state"] = tmp[1] + break + elif i[0] == -1: + raise ForwardError('Error: receive timeout ') + else: + for section in prompt: + # section.values() is : [ [p1,p2,p3] ] + for _prompt in section.values()[0]: + if re.search(_prompt, info.split("\n")[-1]): + result["state"] = section.keys()[0] + break + # Find the specified state type + if not result["state"] is None: + break + # Find the specified state type,exit + if not result["state"] is None: + break + result['content'] += info + result["content"] = re.sub("<--- More --->\\r +\\r", "", result["content"]) + # If you accept a timeout, cancel SSH + except Exception, e: + self.logout() + raise ForwardError(str(e)) + except Exception, e: + result["errLog"] = str(e) + result["status"] = False + return result diff --git a/lib/forward/devclass/baseVenustech.py b/lib/forward/devclass/baseVenustech.py new file mode 100644 index 0000000..bfd1f0a --- /dev/null +++ b/lib/forward/devclass/baseVenustech.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for Venustech. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseTELNET import BASETELNET + + +class BASEVENUSTECH(BASETELNET): + """This is a manufacturer of venustech, using the + telnet version of the protocol, so it is integrated with BASETELNET library. + """ + pass diff --git a/lib/forward/devclass/baseZte.py b/lib/forward/devclass/baseZte.py new file mode 100644 index 0000000..8ca8b00 --- /dev/null +++ b/lib/forward/devclass/baseZte.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for zte,zhong-xing. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class BASEZTE(BASESSHV2): + """This is a manufacturer of zte, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/bclinux7.py b/lib/forward/devclass/bclinux7.py new file mode 100644 index 0000000..b313c30 --- /dev/null +++ b/lib/forward/devclass/bclinux7.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Device class for bclinux7. +Author: Cheung Kei-Chuen +""" + +from forward.devclass.baseLinux import BASELINUX + + +class BCLINUX7(BASELINUX): + """This is a manufacturer of linux, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/c2960.py b/lib/forward/devclass/c2960.py new file mode 100644 index 0000000..2b9b8f7 --- /dev/null +++ b/lib/forward/devclass/c2960.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for c2960. +Author: Cheung Kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class C2960(BASECISCO): + """This is a manufacturer of cisco, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + + def addUser(self, username, password): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in deleting user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') diff --git a/lib/forward/devclass/c4510.py b/lib/forward/devclass/c4510.py new file mode 100644 index 0000000..8a8871e --- /dev/null +++ b/lib/forward/devclass/c4510.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for c4510. +Author: Cheung kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class C4510(BASECISCO): + """This is a manufacturer of cisco, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + def addUser(self, username, password): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in deleting user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') diff --git a/lib/forward/devclass/c6506.py b/lib/forward/devclass/c6506.py new file mode 100644 index 0000000..f21cc84 --- /dev/null +++ b/lib/forward/devclass/c6506.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for c6506. +Author: Cheung Kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class C6506(BASECISCO): + """This is a manufacturer of cisco, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + pass diff --git a/lib/forward/devclass/c6509.py b/lib/forward/devclass/c6509.py new file mode 100644 index 0000000..dd7f668 --- /dev/null +++ b/lib/forward/devclass/c6509.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for c6509. +Author: Cheung Kei-chuen +""" + +from forward.devclass.baseCisco import BASECISCO + + +class C6509(BASECISCO): + """This is a manufacturer of cisco, using the + SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. + """ + + def addUser(self, username, password): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in deleting user parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='username {username} secret {password}\n') diff --git a/lib/forward/devclass/e1000e.py b/lib/forward/devclass/e1000e.py new file mode 100644 index 0000000..2e20d6f --- /dev/null +++ b/lib/forward/devclass/e1000e.py @@ -0,0 +1,14 @@ +#!/usr/bin/evn python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for E1000E. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class E1000E(BASEHUAWEI): + """This is a manufacturer of huawei, it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/e8000e.py b/lib/forward/devclass/e8000e.py new file mode 100644 index 0000000..b16823a --- /dev/null +++ b/lib/forward/devclass/e8000e.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for E8000E. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class E8000E(BASEHUAWEI): + """This is a manufacturer of huawei, it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/e8160e.py b/lib/forward/devclass/e8160e.py new file mode 100644 index 0000000..3ac174c --- /dev/null +++ b/lib/forward/devclass/e8160e.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for e8160e. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class E8160E(BASEHUAWEI): + """This is a manufacturer of huawei, it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/f1000.py b/lib/forward/devclass/f1000.py new file mode 100644 index 0000000..deaafa8 --- /dev/null +++ b/lib/forward/devclass/f1000.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for f1000. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseDepp import BASEDEPP + + +class F1000(BASEDEPP): + """This is a manufacturer of depp, it is integrated with BASEDEPP library. + """ + pass diff --git a/lib/forward/devclass/f510000.py b/lib/forward/devclass/f510000.py new file mode 100644 index 0000000..96228c3 --- /dev/null +++ b/lib/forward/devclass/f510000.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for F510000. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseF5 import BASEF5 + + +class F510000(BASEF5): + """This is a manufacturer of F5, it is integrated with BASEF5 library. + """ + + def addUser(self, username, password): + """Because the device of this model is different from the other F5 + devices in creating user parameters, it is rewritten. + """ + return BASEF5.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + + def _commit(self): + """Because the device of this model is different from the other + F5 devices in deleting user parameters, it is rewritten. + """ + return BASEF5._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') diff --git a/lib/forward/devclass/fg1240.py b/lib/forward/devclass/fg1240.py new file mode 100644 index 0000000..979b2a0 --- /dev/null +++ b/lib/forward/devclass/fg1240.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for fg1240. +Author: Cheung Kei-chuen +""" +from forward.devclass.baseFortinet import BASEFORTINET + + +class FG1240(BASEFORTINET): + """This is a manufacturer of fortinet, so it is integrated with BASEFORTINET library. + """ + pass diff --git a/lib/forward/devclass/fg3040.py b/lib/forward/devclass/fg3040.py new file mode 100644 index 0000000..c18654b --- /dev/null +++ b/lib/forward/devclass/fg3040.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for fg3040. +Author: wangzhe +""" +from forward.devclass.baseFortinet import BASEFORTINET + + +class FG3040(BASEFORTINET): + """This is a manufacturer of fortinet, so it is integrated with BASEFORTINET library. + """ + pass diff --git a/lib/forward/devclass/fg3950.py b/lib/forward/devclass/fg3950.py new file mode 100644 index 0000000..156de31 --- /dev/null +++ b/lib/forward/devclass/fg3950.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for fg3950. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseFortinet import BASEFORTINET + + +class FG3950(BASEFORTINET): + """This is a manufacturer of fortinet, so it is integrated with BASEFORTINET library. + """ + pass diff --git a/lib/forward/devclass/m6000.py b/lib/forward/devclass/m6000.py new file mode 100644 index 0000000..42e9934 --- /dev/null +++ b/lib/forward/devclass/m6000.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for m6000,zhong-xing. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseZte import BASEZTE + + +class M6000(BASEZTE): + """This is a manufacturer of zte, so it is integrated with BASEZTE library. + """ + pass diff --git a/lib/forward/devclass/mx960.py b/lib/forward/devclass/mx960.py new file mode 100644 index 0000000..4b3260c --- /dev/null +++ b/lib/forward/devclass/mx960.py @@ -0,0 +1,12 @@ +#!/usr/bin/evn python +# coding:utf-8 +""" It applies only to models of network equipment mx960 + See the detailed comments mx960.py +""" +from forward.devclass.baseJuniper import BASEJUNIPER + + +class MX960(BASEJUNIPER): + """This is a manufacturer of juniper, so it is integrated with BASEJUNIPER library. + """ + pass diff --git a/lib/forward/devclass/n5548.py b/lib/forward/devclass/n5548.py new file mode 100644 index 0000000..9c6a1e6 --- /dev/null +++ b/lib/forward/devclass/n5548.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n5548. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N5548(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # default is not admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/n5596.py b/lib/forward/devclass/n5596.py new file mode 100644 index 0000000..ff647ed --- /dev/null +++ b/lib/forward/devclass/n5596.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n5596. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N5596(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # default is not admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/n7010.py b/lib/forward/devclass/n7010.py new file mode 100644 index 0000000..f527c19 --- /dev/null +++ b/lib/forward/devclass/n7010.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7010. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N7010(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # param admin: defualt is not admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/n7018.py b/lib/forward/devclass/n7018.py new file mode 100644 index 0000000..92d74cd --- /dev/null +++ b/lib/forward/devclass/n7018.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7018. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N7018(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # default not is Admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/n7710.py b/lib/forward/devclass/n7710.py new file mode 100644 index 0000000..88cc3a1 --- /dev/null +++ b/lib/forward/devclass/n7710.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7018. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N7710(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # default not is Admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/n7718.py b/lib/forward/devclass/n7718.py new file mode 100644 index 0000000..6be24d4 --- /dev/null +++ b/lib/forward/devclass/n7718.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7018. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseCisco import BASECISCO + + +class N7718(BASECISCO): + """This is a manufacturer of cisco, so it is integrated with BASECISCO library. + """ + + def addUser(self, username, password, admin=False): + """Because the device of this model is different from the other Cisco + devices in creating user parameters, it is rewritten. + """ + # default not is Admin + if admin: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') + else: + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role priv-1\n') + + def _commit(self): + """Because the device of this model is different from the other + Cisco devices in commit parameters, it is rewritten. + """ + return BASECISCO._commit(self, + saveCommand='copy running-config startup-config', + exitCommand='end') + + def changePassword(self, username, password): + """Because the device of this model is different from the other + Cisco devices in change user's password parameters, it is rewritten. + """ + return BASECISCO.addUser(self, + username=username, + password=password, + addCommand='user {username} password {password} role network-admin\n') diff --git a/lib/forward/devclass/ne40ex16.py b/lib/forward/devclass/ne40ex16.py new file mode 100644 index 0000000..ae32c07 --- /dev/null +++ b/lib/forward/devclass/ne40ex16.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for ne40ex16. +""" +import re +from forward.devclass.baseHuawei import BASEHUAWEI +from forward.utils.sshv2 import sshv2 + + +class NE40EX16(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + + def _commit(self): + """Because the device of this model is different from the other + huawei devices in commit parameters, it is rewritten. + """ + saveCommand = "save" + # exitCommand = "return" + data = {"status": False, + "content": "", + "errLog": ""} + try: + # Check the config mode status. + if self.isConfigMode: + self._exitConfigMode() + # exit config mode + self.shell.send('%s\n' % (saveCommand)) + # save setup to system + while not re.search(self.prompt, data['content'].split('\n')[-1]): + data['content'] += self.shell.recv(1024) + # When prompted, reply Y,Search range at last line + if re.search(re.escape('Are you sure to continue?[Y/N]'), data['content'].split('\n')[-1]): + # interact,send y + self.shell.send("y\n") + """ + If the program finds information like ‘success’, etc. + in the received information, it indicates that the save configuration is successful. + """ + if re.search(re.escape('Save the configuration successfully'), data['content'], flags=re.IGNORECASE): + data['status'] = True + else: + raise IOError('Error: The current state is not configuration mode') + except Exception, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def login(self): + """Because the device of this model is different from the other + huawei devices in commit parameters, it is rewritten. + """ + njInfo = {"status": False, + "content": "", + "errLog": ""} + # sshv2(ip,username,password,timeout,port=22) + sshChannel = sshv2(self.ip, self.username, self.password, self.timeout, self.port) + if sshChannel['status']: + # Login succeed, init shell + try: + njInfo['status'] = True + self.channel = sshChannel['content'] + # resize virtual console window size to 10000*10000 + self.shell = self.channel.invoke_shell(width=1000, height=1000) + tmpBuffer = '' + while not re.search(self.basePrompt, tmpBuffer.split('\n')[-1]): + tmpBuffer += self.shell.recv(1024) + # When prompted, reply N + if re.search('\[Y/N\]:', tmpBuffer): + self.shell.send('N\n') + # set session timeout + self.shell.settimeout(self.timeout) + # Flag login status is True. + self.isLogin = True + # Get host prompt. + self.getPrompt() + njInfo["status"] = True + except Exception as e: + njInfo['status'] = False + njInfo['errLog'] = str(e) + else: + # Login failed + njInfo['errLog'] = sshChannel['errLog'] + return njInfo diff --git a/lib/forward/devclass/ne40ex3.py b/lib/forward/devclass/ne40ex3.py new file mode 100644 index 0000000..87f708b --- /dev/null +++ b/lib/forward/devclass/ne40ex3.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for ne40ex3. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class NE40EX3(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/r3048g.py b/lib/forward/devclass/r3048g.py new file mode 100644 index 0000000..9eff742 --- /dev/null +++ b/lib/forward/devclass/r3048g.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7018. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseRaisecom import BASERAISECOM +from forward.utils.forwardError import ForwardError +import re + + +class R3048G(BASERAISECOM): + """This is a manufacturer of raisecom, so it is integrated with BASERAISECOM library. + """ + def _configMode(self, cmd="configure"): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # Flag config mode is False + self.isConfigMode = False + result = { + "status": False, + "content": "", + "errLog": "" + } + # Clean buffer. + self.cleanBuffer() + self.shell.send("%s\n" % (cmd)) + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Flag config mode is True. + self.isConfigMode = True + result['status'] = True + return result + + def _exitConfigMode(self, cmd='quit'): + """Exit from configuration mode to privileged mode. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # Check current status + if self.isConfigMode: + self.shell.send("%s\n" % (cmd)) + while not re.search(self.basePrompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + # Flag config mode is False. + self.isConfigMode = False + result["status"] = True + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + result["status"] = False + result['errLog'] = str(e) + # release host prompt + self.getPrompt() + return result + + def _commit(self, saveCommand='write', exitCommand='quit'): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + result = { + "status": False, + "content": "", + "errLog": "" + } + try: + # Status check. + if self.isConfigMode: + self._exitConfigMode(exitCommand) + # save setup to system + self.shell.send('%s\n' % (saveCommand)) + while not re.search(self.prompt, result['content'].split('\n')[-1]): + result['content'] += self.shell.recv(1024) + """ + If the program finds information like ‘success’, 'OK' etc. + in the received information, it indicates that the save configuration is successful. + """ + if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): + result['status'] = True + else: + raise ForwardError('[Commit Config Error]: The current state is not configuration mode') + except ForwardError, e: + result['errLog'] = str(e) + result['status'] = False + return result diff --git a/lib/forward/devclass/rg5510.py b/lib/forward/devclass/rg5510.py new file mode 100644 index 0000000..38c925b --- /dev/null +++ b/lib/forward/devclass/rg5510.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for rg5510. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseRuijie import BASERUIJIE + + +class RG5510(BASERUIJIE): + """This is a manufacturer of ruijie, so it is integrated with BASERUIJIE library. + """ + def __init__(self, *args, **kws): + """Since the device's host prompt is different from BASESSHV2, + the basic prompt for the device is overwritten here. + """ + BASERUIJIE.__init__(self, *args, **kws) + self.basePrompt = r'(>|#.*#|\]|\$|\)) *$' diff --git a/lib/forward/devclass/s3300.py b/lib/forward/devclass/s3300.py new file mode 100644 index 0000000..c0760a7 --- /dev/null +++ b/lib/forward/devclass/s3300.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for s3300. +Author: Cheung Kei-Chuen +""" +import pexpect +import re +from forward.devclass.baseMaipu import BASEMAIPU +from forward.utils.forwardError import ForwardError + + +class S3300(BASEMAIPU): + """This is a manufacturer of maipu, so it is integrated with BASEMAIPU library. + """ + + def __init__(self, *args, **kws): + """Since the device's host prompt is different from BASESSHV1, + the basic prompt for the device is overwritten here. + """ + BASEMAIPU.__init__(self, *args, **kws) + self.moreFlag = re.escape('....press ENTER to next \ +line, Q to quit, other key to next page....') + + def _configMode(self): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + # Flag config mode is False. + self.isConfigMode = False + # Clean buffer. + self.cleanBuffer() + self.channel.send('conf term\n') + # Get result. + data = self._recv(self.basePrompt) + self.getPrompt() + if data['content']: + self.isConfigMode = True + return data + + def _recv(self, _prompt): + """A message returned after the receiving device has executed the command. + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + # If the received message contains the host prompt, stop accepting. + i = self.channel.expect([r"%s" % _prompt, pexpect.TIMEOUT], timeout=self.timeout) + result = '' + try: + if i == 0: + # Get result. + result = self.channel.before + data['status'] = True + elif i == 2: + raise ForwardError('Error: receive timeout') + else: + """If the program does not receive the message correctly, + and does not timeout, the program runs failed. + """ + data['errLog'] = self.channel.before + data['content'] = result + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def _exitConfigMode(self): + """Exit from configuration mode to privileged mode. + """ + # Set command. + exitCommand = "end" + data = {'status': False, + 'content': '', + 'errLog': ''} + try: + # Check config mode status. + if self.isConfigMode: + # Check current status + self.channel.send("%s\n" % (exitCommand)) + # Get result. + data = self._recv(self.basePrompt) + if data['status']: + # Flag config mode is False. + self.isConfigMode = False + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + self.getPrompt() + # release host prompt + return data + + def _commit(self): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + # Set command. + saveCommand = "copy running-config startup-config" + try: + # Check config mode status. + if self.isConfigMode: + # Exit config mode. + self._exitConfigMode() + self.channel.send('%s\n' % (saveCommand)) + # save setup to system + data = self._recv(self.prompt) + # Permission denied + if re.search('user "admin" only', data['content']): + raise ForwardError(data['content']) + else: + data['status'] = True + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def addUser(self, username, password, userLevel=1): + """Create a user on the device. + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + try: + if not username or not password: + raise ForwardError('Please specify the username = your-username \ + and password = your-password') + # Specify a user name and password parameters here. + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + if self.isConfigMode: + # check terminal status + self.channel.send("""username {username} privilege {userLevel} \ + password 0 {password}\n""".format(username=username, + password=password, + userLevel=userLevel)) + # Get result. + _result = self._recv(self.prompt) + _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) + # Permission denied + if _tmp: + raise ForwardError(_tmp.group()) + elif not _result['status']: + # Message acceptance failed + raise ForwardError(_result['errLog']) + # Send the command to create an account. + self.channel.send("""username {username} terminal ssh\n""".format(username=username, + password=password, + userLevel=userLevel)) + # Get result. + _result = self._recv(self.prompt) + if _result['status']: + # Save the configuration + data = self._commit() + else: + data = _result + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def deleteUser(self, username): + """Delete a user on the device + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + try: + if not username: + raise ForwardError('Please specify a username') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # Check config mode status. + if self.isConfigMode: + # check terminal status + self.channel.send("""no username {username}\n""".format(username=username)) + # Get result. + _result = self._recv(self.prompt) + # Permission denied + _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) + if _tmp: + raise ForwardError(_tmp.group()) + elif not _result['status']: + # Message acceptance failed + raise ForwardError(_result['errLog']) + if re.search('error|invalid', data['content'], flags=re.IGNORECASE): + raise ForwardError(data['content']) + if _result['status']: + # Save the configuration + data = self._commit() + else: + data = _result + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def changePassword(self, username, password, userLevel=1): + """Modify the password for the device account. + """ + data = {'status': False, + 'content': '', + 'errLog': ''} + try: + if not username or not password: + # Specify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # Check config mode stauts. + if self.isConfigMode: + # check terminal status + self.channel.send("""username {username} password 0 {password}\n""".format(username=username, + password=password, + userLevel=userLevel)) + # Get result. + _result = self._recv(self.prompt) + _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) + # Permission denied + if _tmp: + raise ForwardError(_tmp.group()) + elif not _result['status']: + # Message acceptance failed + raise ForwardError(_result['errLog']) + if _result['status']: + # Save the configuration + data = self._commit() + else: + data = _result + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data diff --git a/lib/forward/devclass/s5328.py b/lib/forward/devclass/s5328.py new file mode 100644 index 0000000..b493feb --- /dev/null +++ b/lib/forward/devclass/s5328.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for s5328. +Author: wangzhe +""" + +from forward.devclass.baseHuawei import BASEHUAWEI + + +class S5328(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/s5352.py b/lib/forward/devclass/s5352.py new file mode 100644 index 0000000..a1c4d2f --- /dev/null +++ b/lib/forward/devclass/s5352.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for s5352. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class S5352(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/s5800.py b/lib/forward/devclass/s5800.py new file mode 100644 index 0000000..78b26f6 --- /dev/null +++ b/lib/forward/devclass/s5800.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for S5800. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseFenghuo import BASEFENGHUO +from forward.utils.forwardError import ForwardError +import re + + +class S5800(BASEFENGHUO): + """This is a manufacturer of fenghuo, so it is integrated with BASEFENGHUO library. + """ + def isVlan(self, vlan): + """Check if the Vlan exists. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # swith to config mode + # info = self._configMode() + # if not info["status"]: + # raise ForwardError(info["errLog"]) + # switch to enable mode. + tmp = self.privilegeMode() + if not tmp: + raise ForwardError(tmp["errLog"]) + while True: + # Send command. + tmp = self.execute("show vlan {vlan} verbose".format(vlan=vlan)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + if re.search("VLAN ID:{vlan}".format(vlan=vlan), tmp["content"]): + # vlan is exists + info["status"] = True + break + elif re.search("Command is in use by", tmp["content"]): + # check failed,recheck + print 'Rechecking vlan...' + continue + else: + # vlan not is exitsts + info["status"] = False + info["errLog"] = tmp["content"] + break + return info + + def createVlan(self, vlan): + """Create a Vlan. + """ + info = {"status": False, + "content": "", + "errLog": ""} + """Warning: that vlan should be checked + by the 'self.isvlan(vlan) method + before setting up the vlan""" + # swith to config mode + info = self._configMode() + if not info["status"]: + raise ForwardError(info["errLog"]) + try: + # enter vlan + self.shell.send("vlan {vlan}\n".format(vlan=vlan)) + # Host prompt is modified + info["content"] = "" + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + self.getPrompt() + if not re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt): + raise ForwardError("Failed to enter vlan mode,command:vlan {vlan}".format(vlan=vlan)) + # exit vlan,switch to config mode + self.shell.send("quit\n") + # Host prompt is modified + info["content"] = "" + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get host prompt. + self.getPrompt() + # Failure to search for Vlan information. + if re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt): + raise ForwardError("Failed to exit vlan mode,command:quit") + # Save the configuration. + tmp = self._commit() + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the save configuration failed!") + else: + # Check is Vlan. + tmp = self.isVlan(vlan) + if not tmp["status"]: + # check vlan + raise ForwardError("Vlan has been set and has been saved, but the final\ + check found no configuration, so failed.\ + show vlan {vlan} verbose: [{content}]".format(vlan=vlan, content=tmp["errLog"])) + else: + # create successed. exit config mode + info["status"] = True + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + return info + + def isVlanInPort(self, vlan=None, port=None): + """Check that the Vlan exists in the port. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # Parameters check. + if (vlan is None) or (port is None): + raise ForwardError('Specify the `vlan` and `port` parameters') + # Execute command. + info = self.execute("show run") + if not info["status"]: + raise ForwardError(info["errLog"]) + try: + # Keyword search + tmp = re.search("\![\r\n]+interface gigaethernet {port}[\s\S]*por\ +t link-type (access|trunk)[\s\S]*port .* vlan .*{vlan}".format(vlan=vlan, port=port), info["content"]) + if tmp: + # Vlan in the port, case 1 + if tmp.group(1) == "access": + raise ForwardError("Configuration found, but port link - type is 'access', Not a trunk") + info["content"] = tmp.group().split("ABCDEFG") + info["status"] = True + else: + # No exists' + raise ForwardError('No exists') + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + return info + + def createVlanInPort(self, port=None, vlan=None): + """Create a vlan on the port. + """ + # Prameters check. + if (port is None) or (vlan is None): + raise ForwardError('Specify the `port` parameter') + info = {"status": False, + "content": "", + "errLog": ""} + try: + # switch to enable mode + tmp = self.privilegeMode() + if not tmp["status"]: + raise ForwardError(tmp['errLog']) + # else ,successed + # switch to config mode + tmp = self._configMode() + if not tmp["status"]: + raise ForwardError(tmp['errLog']) + # else ,successed + # switch to port mode + info["content"] = "" + self.shell.send("interface gigaethernet {port}\n".format(port=port)) + # Host prompt is modified + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Check the port mode + if not re.search('config.*-ge', self.prompt): + raise ForwardError('Switch to port mode is failed [%s]' % info["content"]) + # else successed. + tmp = self.execute("port link-type trunk") + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + else: + # Check the returned 'tmp['content']', which indicates failure if it contains' Failed ' + if re.search('%Failed', tmp["content"]): + raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\ + result is [%s] ' % tmp["content"]) + # else successed + tmp = self.execute("no shutdown") + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # quit port mode + self.shell.send("quit\n") + info["content"] = "" + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + self.getPrompt() + # save configuration + tmp = self._commit() + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # Verify that it is correct + tmp = self.isVlanInPort(port=port, vlan=vlan) + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the check configuration does not exist! [%s]" % tmp["errLog"]) + else: + # successed + info["content"] = "successed" + info["status"] = True + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + return info + + def isTrunkInInterface(self, port=None, vlan=None): + """Check the relationship between interface and turnk. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # Prameters check. + if (vlan is None) or (port is None): + raise ForwardError('Specify the `vlan` and `port` parameters') + while True: + # Execute command. + info = self.execute("show run") + if not info["status"]: + raise ForwardError(info["errLog"]) + try: + # Keyword search. + tmp = re.search("interface eth-trunk {port}[\r\n]+ mode .*[\r\n]+ por\ + t .*[\r\n]+ port .* vlan .*{vlan}".format(port=port, vlan=vlan), info['content']) + if tmp: + # Exists. + info["status"] = True + break + elif re.search('Command is in use by', info["content"]): + # Rechecking... + continue + else: + info["errLog"] = info['errLog'] + break + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + break + return info + + def trunkOpenVlan(self, port=None, vlan=None): + """Create a vlan on turnk. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # Parameters check. + if (vlan is None) or (port is None): + raise ForwardError('Specify the `vlan` and `port` parameters') + try: + # switch to enable mode + tmp = self.privilegeMode() + if not tmp["status"]: + raise ForwardError(tmp['errLog']) + # else ,successed + # switch to config mode + tmp = self._configMode() + if not tmp["status"]: + raise ForwardError(tmp['errLog']) + # else ,successed + # switch to port mode + self.shell.send("interface eth-trunk {port}\n".format(port=port)) + # Host prompt is modified + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # release host prompt + self.getPrompt() + # Keyword search. + if not re.search("config.*-eth.*-trunk.*-{port}".format(port=port), self.prompt): + raise ForwardError('[trunkOpenVlan] Switch to port mode is failed [%s]' % info["content"]) + # Execute command. + tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + else: + # Check the returned 'tmp['content']', which indicates failure if it contains' Failed ' + if re.search('%Failed', tmp["content"]): + raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\ + result is [%s] ' % tmp["content"]) + # quit port mode + self.shell.send("quit\n") + info["content"] = "" + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # save configuration + self.getPrompt() + # Save the configuration. + tmp = self._commit() + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # Verify that it is correct + tmp = self.isTrunkInInterface(port=port, vlan=vlan) + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the check configuration does not exist! [%s]" % tmp['errLog']) + info["status"] = True + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + return info diff --git a/lib/forward/devclass/s8512.py b/lib/forward/devclass/s8512.py new file mode 100644 index 0000000..db93d63 --- /dev/null +++ b/lib/forward/devclass/s8512.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for s8512. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class S8512(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/s9303.py b/lib/forward/devclass/s9303.py new file mode 100644 index 0000000..e1b9298 --- /dev/null +++ b/lib/forward/devclass/s9303.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for s9303. +Author: Cheung Kei-Cheun +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class S9303(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/s9306.py b/lib/forward/devclass/s9306.py new file mode 100644 index 0000000..6a955c0 --- /dev/null +++ b/lib/forward/devclass/s9306.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for s9306. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI + + +class S9306(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + pass diff --git a/lib/forward/devclass/s9312.py b/lib/forward/devclass/s9312.py new file mode 100644 index 0000000..a1b9d19 --- /dev/null +++ b/lib/forward/devclass/s9312.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for n7018. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseHuawei import BASEHUAWEI +from forward.utils.forwardError import ForwardError +import re + + +class S9312(BASEHUAWEI): + """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. + """ + def isVlan(self, vlan): + """Check if the Vlan exists. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # switch to enable mode. + tmp = self.privilegeMode() + if not tmp: + raise ForwardError(tmp["errLog"]) + tmp = self.execute("display vlan {vlan}".format(vlan=vlan)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # If the above fails, exit immediately + try: + if re.search("Error: The VLAN does not exist", tmp["content"]): + # vlan not is exitsts + info["status"] = False + else: + # vlan is exists + info["status"] = True + except Exception, e: + info["status"] = False + info["errLog"] = str(e) + return info + + def createVlan(self, vlan=None, ascription=None): + """Create a Vlan. + """ + info = {"status": False, + "content": "", + "errLog": ""} + if (vlan is None) or (ascription is None): + raise ForwardError("You must specify the `vlan` and `ascription` parameters") + """Warning: that vlan should be checked + by the 'self.isvlan(vlan) method + before setting up the vlan""" + # swith to config mode + info = self._configMode() + if not info["status"]: + raise ForwardError(info["errLog"]) + try: + # enter vlan + info["content"] = "" + self.shell.send("vlan {vlan}\n".format(vlan=vlan)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get host prompt + self.getPrompt() + if not re.search('.*-vlan', self.prompt): + raise ForwardError("Failed to enter vlan mode,command:vlan {vlan}".format(vlan=vlan)) + # set host's ascription + info["content"] = "" + # Send command. + self.shell.send("name {ascription}\n".format(ascription=ascription)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get host prompt. + self.getPrompt() + # save the configuration. + tmp = self._commit() + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the save configuration failed! [{info}]".format(info=info["content"])) + else: + if not self.isVlan(vlan)["status"]: + # check vlan + raise ForwardError("Vlan has been set and has been saved, but the final\ + check found no configuration, so failed.info:[%s]" % tmp["content"]) + else: + # create successed. exit config mode + info["status"] = True + except Exception, e: + info["status"] = False + info["errLog"] = str(e) + return info + + def isTrunkInInterface(self, port=None, vlan=None): + """Check the relationship between interface and turnk. + """ + info = {"status": False, + "content": "", + "errLog": ""} + if (vlan is None) or (port is None): + raise ForwardError('Specify the `vlan` and `port` parameters') + # switch to enable mode + tmp = self.privilegeMode() + if not tmp["status"]: + raise ForwardError(tmp['errLog']) + # else ,successed + while True: + tmp = self.execute("display current-configuration interface Eth-Trunk") + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + if re.search("Command is in use by", tmp["content"]): + # Recheck + continue + # Keyword search. + data = re.search("#[\r\n]+(interface Eth-Trunk{port}[\r\n]+[\s\S]*?)#".format(port=port), tmp["content"]) + if not data: + # No configuration found + raise ForwardError("Not found port(port) info".format(port=port)) + try: + if re.search("port trunk allow-pass vlan .*{vlan}".format(vlan=vlan), data.group(1)): + # found it. + info["status"] = True + else: + info["status"] = False + info["errLog"] = tmp["content"] + break + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + break + return info + + def trunkOpenVlan(self, port=None, vlan=None): + """Create a vlan on turnk. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # Parameter check. + if (vlan is None) or (port is None): + raise ForwardError('Specify the `vlan` and `port` parameters') + # get parameter + tmp = self.execute("display cur interface Eth-Trunk {port}".format(port=port)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # search parameter + data = re.search("#[\r\n]+(interface Eth-Trunk{port}[\r\n]+[\s\S]*?)#".format(port=port), tmp["content"]) + if not data: + raise ForwardError("Not found port(port) [{info}]".format(port=port, info=tmp["content"])) + else: + # Keyword search. + data = re.search("(port trunk allow-pass vlan.*)", data.group(1)) + if not data: + raise ForwardError("`Port turnk allow-pass vlan ...` is not found") + else: + # remove the end '\n' and '\r' + cmd = "{parameter} {vlan}".format(parameter=data.group(1).strip("\r\n"), vlan=vlan) + # switch to config mode + tmp = self._configMode() + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + try: + # switch to port mode + info["content"] = "" + # Send command. + self.shell.send("interface Eth-Trunk {port}\n".format(port=port)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get new host prompt. + self.getPrompt() + # Keyword search. + if not re.search('Trunk{port}'.format(port=port), self.prompt): + raise ForwardError("Failed to enter port mode,command:interface \ +Eth-Trunk {port} [{info}]".format(port=port, info=info["content"])) + # set vlan + info["content"] = "" + self.shell.send("{cmd}\n".format(cmd=cmd)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get new host prompt. + self.getPrompt() + # save configuration + tmp = self._commit() + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the save configuration failed! [{info}]".format(info=info["content"])) + # check configuration + tmp = self.isTrunkInInterface(port=port, vlan=vlan) + if not tmp["status"]: + raise ForwardError("Vlan has been set and has been saved, but the final\ + check found no configuration, so failed.info:[%s]" % tmp["errLog"]) + else: + info["status"] = True + except Exception, e: + info["errLog"] = str(e) + info["status"] = False + return info + + def isGateway(self, vlan): + """Check that the gateway exists. + """ + info = {"status": False, + "content": "", + "errLog": ""} + # switch to enable mode. + tmp = self.privilegeMode() + if not tmp: + raise ForwardError(tmp["errLog"]) + # Execute command. + tmp = self.execute("display current-configuration interface Vlanif {vlan}".format(vlan=vlan)) + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + # If the above fails, exit immediately + try: + if re.search("Error: Wrong parameter found at", tmp["content"]): + info["status"] = False + else: + info["status"] = True + except Exception, e: + info["status"] = False + info["errLog"] = str(e) + return info + + def setGateway(self, vlan=None, ascription=None, ip=None): + """Create a gateway + """ + info = {"status": False, + "content": "", + "errLog": ""} + # Parameters check. + if (vlan is None) or (ascription is None) or (ip is None): + raise ForwardError("You must specify `vlan` and `ascription` and `ip` parameters") + # Reset gateway ip address + ip = re.sub('[0-9]+$', '254', ip) + # switch to config mode + tmp = self._configMode() + if not tmp["status"]: + raise ForwardError(tmp["errLog"]) + try: + # switch to vlanif mode + info["content"] = "" + # Send command. + self.shell.send("interface Vlanif {vlan}\n".format(vlan=vlan)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get new host prompt. + self.getPrompt() + if not re.search('Vlanif', self.prompt): + raise ForwardError("Failed to enter Vlanif mode,command:port Vlanif {vlan}".format(vlan=vlan)) + # set ascription + info["content"] = "" + self.shell.send("description {ascription}\n".format(ascription=ascription)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Get new host prompt. + self.getPrompt() + # set ip + info["content"] = "" + # Send command. + self.shell.send("ip address {ip} 255.255.255.0\n".format(ip=ip)) + while not re.search(self.basePrompt, info['content'].split('\n')[-1]): + info['content'] += self.shell.recv(1024) + # Check + if re.search("Error: The specified IP address is invalid", info["content"]): + raise ForwardError("Error: The specified IP address is invalid,IP should be a network segment") + # Get new host prompt. + self.getPrompt() + # save the configuration + tmp = self._commit() + if not tmp["status"]: + raise ForwardError("The configuration command has been executed,\ + but the save configuration failed! [{info}]".format(info=info["content"])) + else: + # Check that the gateway configuration exists. + if not self.isGateway(vlan)["status"]: + # check vlan + raise ForwardError("Gateway has been set and has been saved, but the final\ + check found no configuration, so failed.info:[%s]" % tmp["content"]) + else: + # create successed. exit config mode + info["status"] = True + except Exception, e: + info["status"] = False + info["errLog"] = str(e) + return info diff --git a/lib/forward/devclass/sr7750.py b/lib/forward/devclass/sr7750.py new file mode 100644 index 0000000..ece85bf --- /dev/null +++ b/lib/forward/devclass/sr7750.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for sr7750. +Author: zhangqichuan +""" +from forward.devclass.baseBaer import BASEBAER + + +class SR7750(BASEBAER): + """This is a manufacturer of baer, so it is integrated with BASEBAER library.""" + pass diff --git a/lib/forward/devclass/sr7950.py b/lib/forward/devclass/sr7950.py new file mode 100644 index 0000000..27ffbe4 --- /dev/null +++ b/lib/forward/devclass/sr7950.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for sr7950. +Author: zhangqichuan +""" +from forward.devclass.baseBaer import BASEBAER + + +class SR7950(BASEBAER): + """This is a manufacturer of baer, so it is integrated with BASEBAER library. + """ + pass diff --git a/lib/forward/devclass/srx3400.py b/lib/forward/devclass/srx3400.py new file mode 100644 index 0000000..f267ae4 --- /dev/null +++ b/lib/forward/devclass/srx3400.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for srx3400. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseJuniper import BASEJUNIPER + + +class SRX3400(BASEJUNIPER): + """This is a manufacturer of juniper, so it is integrated with BASEJUNIPER library. + """ + pass diff --git a/lib/forward/devclass/usg1000.py b/lib/forward/devclass/usg1000.py new file mode 100644 index 0000000..3d4ce7c --- /dev/null +++ b/lib/forward/devclass/usg1000.py @@ -0,0 +1,219 @@ +#!/usr/bin/evn python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Device class for USG1000. +Author: Cheung Kei-Chuen +""" +import re +from forward.devclass.baseVenustech import BASEVENUSTECH +from forward.utils.forwardError import ForwardError + + +class USG1000(BASEVENUSTECH): + """This is a manufacturer of venustech, so it is integrated with BASEVENUSTECH library. + """ + + def privilegeMode(self): + """Used to switch from normal mode to privileged mode for command line mode. + Does not apply to other modes to switch to privileged mode. + """ + # Set command. + cmd = 'enable' + # Flag privilege mode is False. + self.isPrivilegeMode = False + data = {"status": False, + "content": "", + "errLog": ""} + # Clean buffer. + self.cleanBuffer() + self.channel.write("%s\n" % (cmd)) + # Get result. + data = self._recv(self.basePrompt) + if data['status']: + # Flag privilege mode is True. + self.isPrivilegeMode = True + # Get host prompt. + self.getPrompt() + return data + + def _configMode(self, cmd='conf term'): + """Used to switch from privileged mode to config mode for command line mode. + Does not apply to other modes to switch to config mode. + """ + # Flag config mode is False. + self.isConfigMode = False + data = {"status": False, + "content": "", + "errLog": ""} + # Clean buffer. + self.cleanBuffer() + self.channel.write("%s\n" % (cmd)) + # Get result. + data = self._recv(self.basePrompt) + if data['status']: + # Flag config mode is True. + self.isConfigMode = True + # Get host prompt. + self.getPrompt() + return data + + def _recv(self, _prompt): + # Gets the return message after the command is executed. + data = {"status": False, + "content": "", + "errLog": ""} + # If the received message contains the host prompt, stop receiving. + i = self.channel.expect([r"%s" % _prompt], timeout=self.timeout) + try: + if i[0] == -1: + # The supplied host prompt is incorrect, resulting in the receive message timeout. + raise ForwardError('Error: receive timeout') + # Successed. + data['status'] = True + # Get result. + data['content'] = i[-1] + except ForwardError, e: + data['errLog'] = str(e) + return data + + def _exitConfigMode(self): + """Exit from configuration mode to privileged mode. + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # Check config mode status. + if self.isConfigMode: + # Check current status + self.channel.write("end\n") + # Get result. + data = self._recv(self.basePrompt) + if data['status']: + # Flag config mode is False. + self.isConfigMode = False + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + # Get host prompt. + self.getPrompt() + return data + + def _commit(self): + """To save the configuration information of the device, + it should be confirmed that the device is under the Config Mode before use. + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # Check config mode status. + if self.isConfigMode: + # Exit config mode. + self._exitConfigMode() + # exit config terminal mode. + self.channel.write('copy running-config startup-config\n') + # Get result. + result = self._recv(self.prompt) + """The search receives messages that contain characters + similar to "Current config" to indicate success. + """ + if re.search('Current configuration:', result['content'], flags=re.IGNORECASE): + data['status'] = True + else: + data['content'] = result['content'] + else: + raise ForwardError('Error: The current state is not configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def addUser(self, username, password, admin=False): + """Create a user on the device. + """ + # Set command. + if admin: + command = """user administrator {username} local {password} \ + authorized-table admin\n""".format(username=username, password=password) + else: + command = """user administrator {username} local {password} \ + authorized-table admsee\n""".format(username=username, password=password) + data = {"status": False, + "content": "", + "errLog": ""} + try: + # parameters check. + if not username or not password: + # Spcify a user name and password parameters here. + raise ForwardError('Please specify the username = your-username and password = your-password') + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + if self.isConfigMode: + # check terminal status + self.channel.write(command) + # adduser + data = self._recv(self.prompt) + # recv result + if not data['status']: + # break + raise ForwardError(data['errLog']) + result = data['content'] + if re.search('error|invalid|assword', result, flags=re.IGNORECASE): + # command failure + raise ForwardError(result) + # set password is successed, save the configuration. + data = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def deleteUser(self, username): + """Delete a user on the device + """ + data = {"status": False, + "content": "", + "errLog": ""} + try: + # swith to config terminal mode. + checkPermission = self._configMode() + if not checkPermission['status']: + raise ForwardError(checkPermission['errLog']) + # Check config mode status. + if self.isConfigMode: + # check terminal status + # deleteUser + self.channel.write("""no user administrator {username}\n""".format(username=username)) + # recv result + data = self._recv(self.prompt) + if not data['status']: + # break + raise ForwardError(data['errLog']) + # Get result. + result = data['content'] + # Search for keywords to determine if the command execution is successful. + if re.search('error|invalid|assword', result, flags=re.IGNORECASE): + # command failure + raise ForwardError(result) + # delete user is successed, save the configuration. + data = self._commit() + else: + raise ForwardError('Has yet to enter configuration mode') + except ForwardError, e: + data['errLog'] = str(e) + data['status'] = False + return data + + def changePassword(self, username, password): + """Modify the password for the device account. + Because the password command to modify the account on the device is consistent with the creation + of the user's command, the interface to create the account is called. + """ + return self.addUser(username=username, password=password) diff --git a/lib/forward/devclass/vlb.py b/lib/forward/devclass/vlb.py new file mode 100644 index 0000000..ac702c5 --- /dev/null +++ b/lib/forward/devclass/vlb.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Device class for vlb. +Author: wangzhe +""" + +import re +from forward.devclass.baseBrocade import BASEBROCADE + + +class VLB(BASEBROCADE): + """This is a manufacturer of brocade, so it is integrated with BASEBROCADE library. + """ + def zcliMode(self): + """Execute the czli command and enter a new mode. + """ + # Flag zcli mode is False. + self.isZcliMode = False + # Set command. + cmd = "zcli\n" + # Set host prompt. + zcliPrompt = re.escape("admin@127.0.0.1 > ") + result = { + 'status': True, + 'content': '', + 'errLog': '' + } + # Clean buffer. + self.cleanBuffer() + # Login status check. + if self.isLogin: + self.shell.send(cmd) + try: + while not re.search(zcliPrompt, result["content"]): + result['content'] += self.shell.recv(1024) + # Save the host prompt before entering the zcli mode + self.oldPrompt = self.prompt + # update host prompt + self.prompt = zcliPrompt + # Flag zcli mode is True. + self.isZcliMode = True + result['status'] = True + except Exception, e: + # Error,flag zcli mode is False. + self.isZcliMode = False + result['status'] = False + result['errLog'] = '[ZCLI Error]: {info}'.format(info=str(e)) + else: + # not login + result['status'] = False + result['errLog'] = '[Execute Error]: device not login' + return result + + def exitZcli(self): + # Exit the zcli mode and return to normal mode. + cmd = "exit\n" + result = { + 'status': False, + 'content': '', + 'errLog': '' + } + # Login status check. + if self.isLogin: + if self.isZcliMode: + self.shell.send(cmd) + # Restore the host prompt + self.prompt = self.oldPrompt + try: + while not re.search(self.prompt, result["content"]): + result['content'] += self.shell.recv(1024) + # The switch mode status is False + self.isZcliMode = False + result['status'] = True + except Exception, e: + result['status'] = False + result['errLog'] = '[ZCLI Error]: {info}'.format(info=str(e)) + else: + result["errLog"] = "Error: The current state is not zcli mode" + else: + # not login + result['status'] = False + result['errLog'] = '[Execute Error]: device not login' + return result diff --git a/lib/forward/devclass/vyoslinux.py b/lib/forward/devclass/vyoslinux.py new file mode 100644 index 0000000..43b4961 --- /dev/null +++ b/lib/forward/devclass/vyoslinux.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Device class for bclinux7. +Author: Cheung Kei-Chuen +""" +import re +from forward.devclass.bclinux7 import BCLINUX7 + + +class VYOSLINUX(BCLINUX7): + """This is a manufacturer of linux, so it is integrated with BCLINUX7 library. + """ + def execute(self, cmd): + """Because of the specificity of the device, it is not consistent with + the execute method of the Linux device, so it is rewritten here.""" + result = { + 'status': False, + 'content': '', + 'errLog': '' + } + # Clean buffer. + self.cleanBuffer() + # Login status check. + if self.isLogin: + # check login status + """The result returned is similar to 'show version\r\n\x1b[?1h\x1b=\r + Version: VyOS 1.1.7\x1b[m\r\nDescription: VyOS 1.1.7 (helium + )\x1b[m\r\nCopyright: 0.29\x1b[m\r\n\x1b[m\r\n\r\x1b[K\x1b[?1l + \x1b>vyos@nfjd-sdn-fwvm-253-153:~$ + Because of this type of device, special character information + will be generated after executing the command, so delete it here. + """ + self.shell.send(cmd + "\r") + # resultPattern = '[\r\n]+([\s\S]*)[\r\n]+' + self.prompt + resultPatternOld = '[\r\n]+([\s\S]*)[\r\n]+' + self.prompt + resultPattern = "[\r\n]+([\s\S]*)({character1_1}|{character1_2}|{character1_\ +3}|{character1_4}){character2}".format( + character1_1=re.escape("\x1b[m\r\n\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>"), + character1_2=re.escape('\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'), + character1_3=re.escape('\x1b[?1h\x1b=\r\r\x1b[K\x1b[?1l\x1b>'), + character1_4=re.escape('\x1b[m\r\n\x1b[m\r\n \x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'), + character2=self.prompt) + try: + while not re.search(self.prompt, result['content'].split('\n')[-1]): + # Get more. + self.getMore(result['content']) + # Get result. + result['content'] += self.shell.recv(1024) + # try to extract the return data + try: + # Intercepting the results of the command execution. + tmp = re.search(resultPattern, result['content']).group(1) + except Exception: + # In cases where special characters are not included, + # the original character characteristics should be used + # Intercepting the results of the command execution. + tmp = re.search(resultPatternOld, result['content']).group(1) + result['content'] = tmp + result['status'] = True + except Exception as e: + # pattern not match + result['status'] = False + result['content'] = result['content'] + result['errLog'] = str(e) + else: + # not login + result['status'] = False + result['errLog'] = '[Execute Error]: device not login' + return result diff --git a/lib/forward/devclass/zx5952.py b/lib/forward/devclass/zx5952.py new file mode 100644 index 0000000..4370cc4 --- /dev/null +++ b/lib/forward/devclass/zx5952.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Device class for zx5952. +Author: Cheung Kei-Chuen +""" +from forward.devclass.baseZte import BASEZTE + + +class ZX5952(BASEZTE): + """This is a manufacturer of zte, so it is integrated with BASEZTE library. + """ + pass diff --git a/lib/forward/release.py b/lib/forward/release.py new file mode 100644 index 0000000..4fdc33f --- /dev/null +++ b/lib/forward/release.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + + +__version__ = '3.0.8' +__author__ = 'Azrael, Cheung Kei-Chuen' diff --git a/lib/forward/utils/__init__.py b/lib/forward/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lib/forward/utils/deviceListSplit.py b/lib/forward/utils/deviceListSplit.py new file mode 100644 index 0000000..ace28b6 --- /dev/null +++ b/lib/forward/utils/deviceListSplit.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][Forward] Split deviceList. +['1.1.1.1','2.2.2.2-2.2.2.4'] -> ['1.1.1.1','2.2.2.2','2.2.2.3','2.2.2.4'] +Author: Skate from CSDN blog. Azrael +""" + + +class DEVICELIST: + def __init__(self, deviceList): + self.deviceList = deviceList + self.deviceListSplited = [] + + def ipToNum(self, ip): + # ip address transformat into binary + ip = [int(x) for x in ip.split('.')] + return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] + + def numToIp(self, num): + # binary ip address transformat into x.x.x.x + return '%s.%s.%s.%s' % ((num & 0xff000000) >> 24, + (num & 0x00ff0000) >> 16, + (num & 0x0000ff00) >> 8, + num & 0x000000ff) + + def getIp(self, ip): + # input 'x.x.x.x-y.y.y.y' or 'z.z.z.z' + # output all ip within list belongs to 'x.x.x.x-y.y.y.y', except '0.0.0.0' + ipRangeList = [self.ipToNum(x) for x in ip.split('-')] + start, end = ipRangeList[0], ipRangeList[-1] + return [self.numToIp(num) for num in range(start, end + 1) if num & 0xff] + + def getIpList(self): + # deviceList:['1.1.1.1','2.2.2.2-2.2.3.4'] + # output all legal ip address within list + for element in self.deviceList: + self.deviceListSplited.extend(self.getIp(element)) + return self.deviceListSplited diff --git a/lib/forward/utils/forwardError.py b/lib/forward/utils/forwardError.py new file mode 100644 index 0000000..2e735ab --- /dev/null +++ b/lib/forward/utils/forwardError.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +""" +#Author: Cheung Kei-Chuen +forward specific types of errors +""" + + +class ForwardError(Exception): + pass diff --git a/lib/forward/utils/loginThread.py b/lib/forward/utils/loginThread.py new file mode 100644 index 0000000..819ba51 --- /dev/null +++ b/lib/forward/utils/loginThread.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][Forward] Login method thread function, used for the initialize multithread step +Author: Azrael +""" + + +def loginThread(instance): + # Login method thread function, used for the initialize multithread step + if not instance.isLogin: + result = instance.login() + if not result['status']: + print '[Login Error]: %s :%s' % (instance.ip, result['errLog']) diff --git a/lib/forward/utils/paraCheck.py b/lib/forward/utils/paraCheck.py new file mode 100644 index 0000000..d4d1bcc --- /dev/null +++ b/lib/forward/utils/paraCheck.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][Forward] addTargets parameters legal check function +Author: Azrael +""" + + +def paraCheck(targets): + # Legal targets: [target1, target2, target3....] + # Legal target type: [ip-str, model-str, user-str, pw-str, kwargs-dict] + # Legal target: ['192.168.1.1', 'n7k', 'admin', 'admin_pw', {'port': 22, 'timeout': 30}] + # Legal target: ['192.168.1.1', 'n7k', 'admin', 'admin_pw', {'port': 22}] + # Legal target: ['192.168.1.1', 'n7k', 'admin', 'admin_pw', {'timeout': 30}] + # Legal target: ['192.168.1.1', 'n7k', 'admin', 'admin_pw'] + bool_legal = isinstance(targets, list) + + if bool_legal: + for target in targets: + try: + bool_legal &= (len(target) >= 4 and len(target) < 6) + bool_legal &= isinstance(target[0], str) + bool_legal &= isinstance(target[1], str) + bool_legal &= isinstance(target[2], str) + bool_legal &= isinstance(target[3], str) + if len(target) > 4: + bool_legal &= isinstance(target[4], dict) + else: + bool_legal &= True + except Exception: + return False + if not bool_legal: + break + return bool_legal + else: + return False diff --git a/lib/forward/utils/sshv1.py b/lib/forward/utils/sshv1.py new file mode 100644 index 0000000..a2bcd27 --- /dev/null +++ b/lib/forward/utils/sshv1.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# coding:utf-8 +""" +-----Introduction----- +[Core][forward] Function for sshv1, by using pexpect module. +Author: Cheung Kei-Chuen,Wangzhe +""" +import os +import sys +import re +from forward.utils.forwardError import ForwardError +import pexpect + + +def checkPassWord(ssh, password, P=False): + njInfo = {"status": False, + "content": "", + "errLog": ""} + # througt SSH chanel determine whether there is interaction password prompt + if not P: + ssh.expect([r"[Pp]assword", ".*"]) + ssh.send(password + '\n') + p = ssh.expect([r"[Pp]assword", r"(>|#|\]|\$) *$"]) + if p == 0: + njInfo['errLog'] = "Username or Password wrong" + # if expect characters is password,then the account password is wrong + elif p == 1: + # if expect host's prompt characters,then normal + njInfo["status"] = True + njInfo["content"] = ssh + # return password cross-examination after the SSH channel + else: + njInfo['content'] = "Unknown login wrong" + return njInfo + + +class NJSSHV1Wraper(pexpect.spawn): + + def __init__(self, + ip='', + username='', + port=22, + timeout=30): + self.ip = ip + self.port = port + self.timeout = timeout + self.username = username + self.njInfo = {"status": False, + "content": "", + 'errLog': ""} + + def login(self, password=None): + pexpect.spawn.__init__(self, 'ssh -p %d %s@%s' % (self.port, self.username, self.ip)) + self.setwinsize(1000, 1000) + i = self.expect([r'[Pp]assword', + 'Are you sure you want to continue connecting (yes/no)?', + 'Connection refused', pexpect.TIMEOUT], self.timeout) + if i == 0: + self.njInfo = checkPassWord(self, password, True) + # True + elif i == 1: + self.sendline('yes') + self.njInfo = checkPassWord(self, password) + elif i == 2: + self.njInfo['errLog'] = 'port timeout [%s]' % self.ip + elif i == 3: + self.njInfo['errLog'] = 'port timeout [%s]' % self.ip + else: + self.njInfo['errLog'] = 'The error is unknown' + return self.njInfo + + +def sshv1(ip='', + username=None, + password=None, + port=22, + timeout=30): + njSSHv1Wraper = NJSSHV1Wraper(ip=ip, username=username, timeout=timeout) + return njSSHv1Wraper.login(password=password) diff --git a/lib/forward/utils/sshv2.py b/lib/forward/utils/sshv2.py new file mode 100644 index 0000000..4da7857 --- /dev/null +++ b/lib/forward/utils/sshv2.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# (c) 2017, Azrael + +""" +-----Introduction----- +[Core][forward] Function for sshv2, by using paramiko module. +Author: Cheung Kei-Chuen, Azrael +""" + +import paramiko + + +def sshv2(ip='', username='', password='', timeout=30, port=22): + # return SSH channel, use ssh.invoke_shell() to active a shell, and resize window size + njInfo = { + 'status': True, + 'errLog': '', + 'content': '' + } + try: + port = int(port) + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(ip, port, username, password, timeout=timeout) + njInfo['content'] = ssh + except Exception, e: + njInfo['status'] = False + njInfo['errLog'] = str(e) + return njInfo diff --git a/lib/forward/utils/telnet.py b/lib/forward/utils/telnet.py new file mode 100644 index 0000000..17f8376 --- /dev/null +++ b/lib/forward/utils/telnet.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# coding:utf-8 + +""" +-----Introduction----- +[Core][forward] Function for telnet, by using telnetlib module. +Author: Azrael, Cheung Kei-Chuen +""" + +import telnetlib +import re + + +class NJTELNETWraper(telnetlib.Telnet): + + def __init__(self, ip=None, port=23, timeout=30): + self.ip = ip + self.port = port + self.timeout = timeout + self.njInfo = {'content': "", + 'status': False, + 'errLog': ""} + self.prompt = "(>|#|\]|\$) *$" + + def login(self, username, password): + # login by username and password + njInfo = {"status": False, + "content": ""} + try: + telnetlib.Telnet.__init__(self, + host=self.ip, + port=self.port, + timeout=self.timeout) + # self.set_debuglevel(2) + # username + self.expect([r"Username|login"]) + self.write('%s\n' % username) + # password + self.expect([r"assword"]) + self.write('%s\n' % password) + T = self.expect([r"Login incorrect|assword", r"%s" % self.prompt]) + # is tuple ,notice \r \n + NT = T[0] + if NT == 1: + njInfo['content'] = self + # return telnetlib instance + njInfo['status'] = True + elif NT == 0: + njInfo['errLog'] = 'Username or Password wrong' + else: + njInfo['errLog'] = 'Login status is unknown' + except Exception, e: + njInfo['errLog'] = str(e) + return njInfo + + def send(self, command=None): + telnetlib.Telnet.write(self, command) + # def recv(self,prompt): + # return telnetlib.Telnet.expect(prompt)[-1] + + def rfc1073(self): + # resize the virtual console window size to 10000*10000 by use RFC1073 protocal + cmd = telnetlib.IAC + telnetlib.WILL + telnetlib.NAWS + self.get_socket().send(cmd) + cmd = telnetlib.IAC + telnetlib.SB + telnetlib.NAWS \ + + chr(39) + chr(16) + chr(39) + chr(16)\ + + telnetlib.IAC + telnetlib.SE + self.get_socket().send(cmd) + + +def telnet(ip=None, username=None, password=None, port=23, timeout=30): + njTelnetInstance = NJTELNETWraper(ip=ip, port=port, timeout=timeout) + njInfo = njTelnetInstance.login(username=username, password=password) + if njInfo['status']: + njTelnetInstance.rfc1073() + return njInfo + + +if __name__ == '__main__': + telnet('10.0.0.1', 'username', 'password', 23, 30) diff --git a/nosetests.ini b/nosetests.ini new file mode 100644 index 0000000..08484fc --- /dev/null +++ b/nosetests.ini @@ -0,0 +1,11 @@ +[nosetests] +verbosity=3 +where=unittests +stop=1 +with-xunit=1 +xunit-file=/apps/data/tomcat_8080/jenkins_file/forward/unittests/nosetests.xml +with-coverage=1 +cover-package=lib/forward +cover-xml=1 +cover-xml-file=/apps/data/tomcat_8080/jenkins_file/forward/unittests/coverage.xml +exe=1 diff --git a/protocol/flake8 b/protocol/flake8 new file mode 100644 index 0000000..c446e7e --- /dev/null +++ b/protocol/flake8 @@ -0,0 +1,4 @@ +[flake8] +exclude = unittests,build,tests,migrations,.git,.tox,docs,*egg,env,instance,callback,runScriptAdapter,runShellAdapter +ignore = E402, E123, F401 +max-line-length = 120 diff --git a/protocol/pre-commit b/protocol/pre-commit new file mode 100644 index 0000000..684bb07 --- /dev/null +++ b/protocol/pre-commit @@ -0,0 +1,14 @@ +#!/bin/sh + +#set_env_path +export PATH=/usr/local/bin:$PATH +source /Users/Azrael/.bashrc + +#flake8_check +echo ">[run flake8]" +flake8 ./ --config=protocol/flake8 +result_flake8=$? +if ((result_flake8 != 0)) +then + exit 1 +fi diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6a9cba6 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +flake8==2.4.1 +mock==2.0.0 +paramiko==1.16.0 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..3e3e422 --- /dev/null +++ b/setup.py @@ -0,0 +1,114 @@ +"""A setuptools based setup module. +See: +https://packaging.python.org/en/latest/distributing.html +https://github.com/pypa/sampleproject +""" + +# Always prefer setuptools over distutils +from setuptools import setup, find_packages +# To use a consistent encoding +# from codecs import open +import os +import sys + +sys.path.insert(0, os.path.abspath('lib')) +from forward.release import __version__, __author__ + +# here = path.abspath(path.dirname(__file__)) + +# Get the long description from the README file +# with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +# long_description = f.read() + +setup( + name='forward', + + # Versions should comply with PEP440. For a discussion on single-sourcing + # the version across setup.py and the project code, see + # https://packaging.python.org/en/latest/single_source_version.html + version=__version__, + + description='A CLI based batch device operation Python module', + # long_description=long_description, + + # The project's main homepage. + url='https://git.oschina.net/headkarl/Forwarder', + + # Author details + author=__author__, + author_email='azrael-ex@139.com', + + # Choose your license + license='GNU', + + # See https://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 3 - Alpha', + + # Indicate who your project is intended for + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Build Tools', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + ], + + # What does your project relate to? + keywords='CLI NETWORK AUTO-OPERATION', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + package_dir={'': 'lib'}, + packages=find_packages('lib'), + + # Alternatively, if you want to distribute just a my_module.py, uncomment + # this: + # py_modules=["my_module"], + + # List run-time dependencies here. These will be installed by pip when + # your project is installed. For an analysis of "install_requires" vs pip's + # requirements files see: + # https://packaging.python.org/en/latest/requirements.html + install_requires=['paramiko'], + + # List additional groups of dependencies here (e.g. development + # dependencies). You can install these using the following syntax, + # for example: + # $ pip install -e .[dev,test] + # extras_require={ + # 'dev': ['check-manifest'], + # 'test': ['coverage'], + # }, + + # If there are data files included in your packages that need to be + # installed, specify them here. If using Python 2.6 or less, then these + # have to be included in MANIFEST.in as well. + package_data={ + '': [], + }, + + # Although 'package_data' is the preferred approach, in some case you may + # need to place data files outside of your packages. See: + # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa + # In this case, 'data_file' will be installed into '/my_data' + data_files=[('', [])], + + # To provide executable scripts, use entry points in preference to the + # "scripts" keyword. Entry points provide cross-platform support and allow + # pip to create the appropriate form of executable for the target platform. + + # entry_points={ + # 'console_scripts': [ + # 'forward=forward.a:main', + # ], + # }, +) diff --git a/test b/test deleted file mode 100644 index 7898192..0000000 --- a/test +++ /dev/null @@ -1 +0,0 @@ -a diff --git a/unittests/__init__.py b/unittests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/unittests/baseBaseBrocade.py b/unittests/baseBaseBrocade.py new file mode 100644 index 0000000..5a7bb35 --- /dev/null +++ b/unittests/baseBaseBrocade.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseBrocade(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseBrocade" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testAdx03100.py b/unittests/testAdx03100.py new file mode 100644 index 0000000..e0460d6 --- /dev/null +++ b/unittests/testAdx03100.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassAdx03100(unittest.TestCase): + def setUp(self): + self.deviceClassName = "adx03100" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testAsa.py b/unittests/testAsa.py new file mode 100644 index 0000000..6778dfd --- /dev/null +++ b/unittests/testAsa.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassAsa(unittest.TestCase): + def setUp(self): + self.deviceClassName = "asa" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testAsr1006.py b/unittests/testAsr1006.py new file mode 100644 index 0000000..4e2e254 --- /dev/null +++ b/unittests/testAsr1006.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassAsr1006(unittest.TestCase): + def setUp(self): + self.deviceClassName = "asr1006" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseBaer.py b/unittests/testBaseBaer.py new file mode 100644 index 0000000..d9e0b44 --- /dev/null +++ b/unittests/testBaseBaer.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseBaer(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseBaer" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testBaseCisco.py b/unittests/testBaseCisco.py new file mode 100644 index 0000000..321199b --- /dev/null +++ b/unittests/testBaseCisco.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseCisco(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseCisco" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseDepp.py b/unittests/testBaseDepp.py new file mode 100644 index 0000000..34ba10d --- /dev/null +++ b/unittests/testBaseDepp.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseDepp(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseDepp" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testBaseF5.py b/unittests/testBaseF5.py new file mode 100644 index 0000000..0511dfa --- /dev/null +++ b/unittests/testBaseF5.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseF5(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseF5" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testBaseFenghuo.py b/unittests/testBaseFenghuo.py new file mode 100644 index 0000000..f0e8aa5 --- /dev/null +++ b/unittests/testBaseFenghuo.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseFenghuo(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseFenghuo" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testBaseFortinet.py b/unittests/testBaseFortinet.py new file mode 100644 index 0000000..7c9392f --- /dev/null +++ b/unittests/testBaseFortinet.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseFortinet(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseFortinet" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testBaseHuawei.py b/unittests/testBaseHuawei.py new file mode 100644 index 0000000..ade43bb --- /dev/null +++ b/unittests/testBaseHuawei.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseHuawei(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseHuawei" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseJuniper.py b/unittests/testBaseJuniper.py new file mode 100644 index 0000000..aeb84ab --- /dev/null +++ b/unittests/testBaseJuniper.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseTELNET import BASETELNET + + +class deviceClassBaseJuniper(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseJuniper" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + self.deviceClassMethod = ["_recv", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASETELNET) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseLinux.py b/unittests/testBaseLinux.py new file mode 100644 index 0000000..ae10b66 --- /dev/null +++ b/unittests/testBaseLinux.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseLinux(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseLinux" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + self.deviceClassMethod = ["addUser", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseMaipu.py b/unittests/testBaseMaipu.py new file mode 100644 index 0000000..dab7925 --- /dev/null +++ b/unittests/testBaseMaipu.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV1 import BASESSHV1 + + +class deviceClassBaseMaipu(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseMaipu" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV1) diff --git a/unittests/testBaseRaisecom.py b/unittests/testBaseRaisecom.py new file mode 100644 index 0000000..60884f4 --- /dev/null +++ b/unittests/testBaseRaisecom.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseRaisecom(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseRaisecom" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + """self.deviceClassMethod = ["_recv", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"]""" + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) + + """def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testBaseSSHV1.py b/unittests/testBaseSSHV1.py new file mode 100644 index 0000000..5b722d5 --- /dev/null +++ b/unittests/testBaseSSHV1.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError + + +class deviceClassBaseSSHV1(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseSSHV1" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + """def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2)""" diff --git a/unittests/testBaseSSHV2.py b/unittests/testBaseSSHV2.py new file mode 100644 index 0000000..1b072ce --- /dev/null +++ b/unittests/testBaseSSHV2.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError + + +class deviceClassBaseSSHV2(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseSSHV2" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + """def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2)""" diff --git a/unittests/testBaseTELNET.py b/unittests/testBaseTELNET.py new file mode 100644 index 0000000..441f87f --- /dev/null +++ b/unittests/testBaseTELNET.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError + + +class deviceClassBaseTELNET(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseTELNET" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + """def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2)""" diff --git a/unittests/testBaseVenustech.py b/unittests/testBaseVenustech.py new file mode 100644 index 0000000..953f61a --- /dev/null +++ b/unittests/testBaseVenustech.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseTELNET import BASETELNET + + +class deviceClassBaseMaipu(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseVenustech" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASETELNET) diff --git a/unittests/testBaseZte.py b/unittests/testBaseZte.py new file mode 100644 index 0000000..62f3479 --- /dev/null +++ b/unittests/testBaseZte.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseSSHV2 import BASESSHV2 + + +class deviceClassBaseZte(unittest.TestCase): + def setUp(self): + self.deviceClassName = "baseZte" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASESSHV2) diff --git a/unittests/testC2960.py b/unittests/testC2960.py new file mode 100644 index 0000000..2617b2d --- /dev/null +++ b/unittests/testC2960.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassC2960(unittest.TestCase): + def setUp(self): + self.deviceClassName = "c2960" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC4510.py b/unittests/testC4510.py new file mode 100644 index 0000000..9fd8a5c --- /dev/null +++ b/unittests/testC4510.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassC4510(unittest.TestCase): + def setUp(self): + self.deviceClassName = "c4510" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC6506.py b/unittests/testC6506.py new file mode 100644 index 0000000..1c2ff8b --- /dev/null +++ b/unittests/testC6506.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassC6506(unittest.TestCase): + def setUp(self): + self.deviceClassName = "c6506" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC6509.py b/unittests/testC6509.py new file mode 100644 index 0000000..96bd2d4 --- /dev/null +++ b/unittests/testC6509.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassC6509(unittest.TestCase): + def setUp(self): + self.deviceClassName = "c6509" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testDevclassInit.py b/unittests/testDevclassInit.py new file mode 100644 index 0000000..0df61d0 --- /dev/null +++ b/unittests/testDevclassInit.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError + + +class deviceClassInitTest(unittest.TestCase): + def setUp(self): + self.devclass = ["adx03100", + "asa", + "asr1006", + "baseBaer", + "baseDepp", + "baseF5", + "baseFortinet", + "baseHuawei", + "baseCisco", + "baseJuniper", + "baseLinux", + "baseRaisecom", + "baseZte", + "c2960", + "c4510", + "c6506", + "c6509", + "e1000e", + "e8000e", + "e8160e", + "f1000", + "f510000", + "fg1240", + "fg3040", + "fg3950", + "m6000", + "mx960", + "n5548", + "n5596", + "n7010", + "n7018", + "n7710", + "n7718", + "ne40ex16", + "ne40ex3", + "r3048g", + "s3300", + "s5328", + "s5352", + "s5800", + "s8512", + "s9303", + "s9306", + "s9312", + "sr7750", + "srx3400", + "usg1000", + "vlb", + "zx5952"] + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test__all_instance(self): + for dev in self.devclass: + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=dev)), dev.upper()) + _dev(1,2,3) + + def test_class_parameters(self): + for dev in self.devclass: + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=dev)), dev.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (dev), parameter) diff --git a/unittests/testE1000e.py b/unittests/testE1000e.py new file mode 100644 index 0000000..f8c27e2 --- /dev/null +++ b/unittests/testE1000e.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassE1000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "e1000e" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = [] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testE8000e.py b/unittests/testE8000e.py new file mode 100644 index 0000000..a6a2ea3 --- /dev/null +++ b/unittests/testE8000e.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassE8000e(unittest.TestCase): + def setUp(self): + self.deviceClassName = "e8000e" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) diff --git a/unittests/testE8160e.py b/unittests/testE8160e.py new file mode 100644 index 0000000..3cca229 --- /dev/null +++ b/unittests/testE8160e.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassE8160e(unittest.TestCase): + def setUp(self): + self.deviceClassName = "e8160e" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) diff --git a/unittests/testF1000.py b/unittests/testF1000.py new file mode 100644 index 0000000..86e62a4 --- /dev/null +++ b/unittests/testF1000.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseDepp import BASEDEPP + + +class deviceClassF1000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "f1000" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEDEPP) diff --git a/unittests/testF510000.py b/unittests/testF510000.py new file mode 100644 index 0000000..c1295ec --- /dev/null +++ b/unittests/testF510000.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseF5 import BASEF5 + + +class deviceClassBaseF510000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "f510000" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEF5) diff --git a/unittests/testFg1240.py b/unittests/testFg1240.py new file mode 100644 index 0000000..08f1aa2 --- /dev/null +++ b/unittests/testFg1240.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseFortinet import BASEFORTINET + + +class deviceClassFg1240(unittest.TestCase): + def setUp(self): + self.deviceClassName = "fg1240" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEFORTINET) diff --git a/unittests/testFg3040.py b/unittests/testFg3040.py new file mode 100644 index 0000000..be190b4 --- /dev/null +++ b/unittests/testFg3040.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseFortinet import BASEFORTINET + + +class deviceClassFg3040(unittest.TestCase): + def setUp(self): + self.deviceClassName = "fg3040" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEFORTINET) diff --git a/unittests/testFg3950.py b/unittests/testFg3950.py new file mode 100644 index 0000000..d33a8ee --- /dev/null +++ b/unittests/testFg3950.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseFortinet import BASEFORTINET + + +class deviceClassFg3950(unittest.TestCase): + def setUp(self): + self.deviceClassName = "fg3950" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEFORTINET) diff --git a/unittests/testM6000.py b/unittests/testM6000.py new file mode 100644 index 0000000..ca8dc88 --- /dev/null +++ b/unittests/testM6000.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseZte import BASEZTE + + +class deviceClassM6000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "m6000" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEZTE) diff --git a/unittests/testMainClass.py b/unittests/testMainClass.py new file mode 100644 index 0000000..f2b27d2 --- /dev/null +++ b/unittests/testMainClass.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +import unittest +import importlib +from forward import Forward +from forward.utils.forwardError import ForwardError + +class TestMainForward(unittest.TestCase): + + def test_init(self): + # new blank instance + new_blank = Forward() + self.assertEquals(new_blank.targets, []) + self.assertEquals(new_blank.instances, {}) + self.assertTrue(isinstance(new_blank, Forward)) + + # new success instance + new_success = Forward(targets=[ + ['192.168.1.1', 'vlb', 'admin', 'admin_pw', {'port': 22, 'timeout': 30}], + ['192.168.1.1', 'vlb', 'admin', 'admin_pw'] + ]) + self.assertEquals(new_success.targets, [ + ['192.168.1.1', 'vlb', 'admin', 'admin_pw', {'port': 22, 'timeout': 30}], + ['192.168.1.1', 'vlb', 'admin', 'admin_pw'] + ]) + self.assertTrue(isinstance(new_success, Forward)) + + # new fail instance + with self.assertRaises(ForwardError): + new_fail = Forward(targets=[['192.168.1.1', 'vlb', 'admin', 234]]) + + def test_add_targets(self): + new_blank = Forward() + new_blank.addTargets( + ['192.168.113.123'], + 'bclinux7', + 'north_king', + 'wolf_spirit', + timeout=40, + port=25 + ) + new_blank.addTargets( + ['192.168.113.124-192.168.113.126'], + 'vlb', + 'south_king', + 'fish_spirit' + ) + self.assertEquals(new_blank.targets, [ + ['192.168.113.123', 'bclinux7', 'north_king', 'wolf_spirit', {'timeout': 40, 'port': 25}], + ['192.168.113.124', 'vlb', 'south_king', 'fish_spirit', {}], + ['192.168.113.125', 'vlb', 'south_king', 'fish_spirit', {}], + ['192.168.113.126', 'vlb', 'south_king', 'fish_spirit', {}] + ]) + + def test_get_instances(self): + new_blank = Forward() + new_blank.addTargets( + ['192.168.113.123'], + 'bclinux7', + 'north_king', + 'wolf_spirit', + timeout=40, + port=25 + ) + new_blank.addTargets( + ['192.168.113.124-192.168.113.126'], + 'vlb', + 'south_king', + 'fish_spirit' + ) + instances = new_blank.getInstances(preLogin=False) + node123 = instances['192.168.113.123'] + node124 = instances['192.168.113.124'] + node125 = instances['192.168.113.125'] + node126 = instances['192.168.113.126'] + + self.assertTrue(isinstance(node123, getattr( + importlib.import_module('forward.devclass.%s' % 'bclinux7'), + 'BCLINUX7' + ))) + self.assertTrue(isinstance(node125, getattr( + importlib.import_module('forward.devclass.%s' % 'vlb'), + 'VLB' + ))) diff --git a/unittests/testMx960.py b/unittests/testMx960.py new file mode 100644 index 0000000..8dc3d5c --- /dev/null +++ b/unittests/testMx960.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseJuniper import BASEJUNIPER + + +class deviceClassMx6000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "mx960" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEJUNIPER) diff --git a/unittests/testN5548.py b/unittests/testN5548.py new file mode 100644 index 0000000..07d2d6a --- /dev/null +++ b/unittests/testN5548.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN5548(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n5548" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN5596.py b/unittests/testN5596.py new file mode 100644 index 0000000..ed3830c --- /dev/null +++ b/unittests/testN5596.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN5596(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n5596" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7010.py b/unittests/testN7010.py new file mode 100644 index 0000000..056b8a0 --- /dev/null +++ b/unittests/testN7010.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN7010(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n7010" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7018.py b/unittests/testN7018.py new file mode 100644 index 0000000..f09ea9a --- /dev/null +++ b/unittests/testN7018.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN7018(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n7018" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7710.py b/unittests/testN7710.py new file mode 100644 index 0000000..4ee56bb --- /dev/null +++ b/unittests/testN7710.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN7710(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n7710" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7718.py b/unittests/testN7718.py new file mode 100644 index 0000000..a3d891a --- /dev/null +++ b/unittests/testN7718.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseCisco import BASECISCO + + +class deviceClassN7718(unittest.TestCase): + def setUp(self): + self.deviceClassName = "n7718" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASECISCO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testNe40ex16.py b/unittests/testNe40ex16.py new file mode 100644 index 0000000..87bd1e1 --- /dev/null +++ b/unittests/testNe40ex16.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassNe40ex16(unittest.TestCase): + def setUp(self): + self.deviceClassName = "ne40ex16" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testNe40ex3.py b/unittests/testNe40ex3.py new file mode 100644 index 0000000..71304d7 --- /dev/null +++ b/unittests/testNe40ex3.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassNe40ex3(unittest.TestCase): + def setUp(self): + self.deviceClassName = "ne40ex3" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testR3048g.py b/unittests/testR3048g.py new file mode 100644 index 0000000..e52485c --- /dev/null +++ b/unittests/testR3048g.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseRaisecom import BASERAISECOM + + +class deviceClassR3048g(unittest.TestCase): + def setUp(self): + self.deviceClassName = "r3048g" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + """self.deviceClassMethod = ["_recv", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"]""" + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASERAISECOM) + + """def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testRg5510.py b/unittests/testRg5510.py new file mode 100644 index 0000000..8672d92 --- /dev/null +++ b/unittests/testRg5510.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseRuijie import BASERUIJIE + + +class deviceClassRg5510(unittest.TestCase): + def setUp(self): + self.deviceClassName = "rg5510" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + """self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"]""" + self.deviceClassMethod = ["cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + """def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASERUIJIE) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS3300.py b/unittests/testS3300.py new file mode 100644 index 0000000..b17c7e1 --- /dev/null +++ b/unittests/testS3300.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseMaipu import BASEMAIPU + + +class deviceClassS3300(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s3300" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEMAIPU) diff --git a/unittests/testS5328.py b/unittests/testS5328.py new file mode 100644 index 0000000..1e19253 --- /dev/null +++ b/unittests/testS5328.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS5328(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s5328" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS5352.py b/unittests/testS5352.py new file mode 100644 index 0000000..4780343 --- /dev/null +++ b/unittests/testS5352.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS5352(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s5352" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS5800.py b/unittests/testS5800.py new file mode 100644 index 0000000..c9cbc29 --- /dev/null +++ b/unittests/testS5800.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseFenghuo import BASEFENGHUO + + +class deviceClassS5800(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s5800" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "_configMode", + "_exitConfigMode"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEFENGHUO) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS8512.py b/unittests/testS8512.py new file mode 100644 index 0000000..dac9306 --- /dev/null +++ b/unittests/testS8512.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS8512(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s8512" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9303.py b/unittests/testS9303.py new file mode 100644 index 0000000..ae3e8e6 --- /dev/null +++ b/unittests/testS9303.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS9303(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s9303" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9306.py b/unittests/testS9306.py new file mode 100644 index 0000000..096cbe4 --- /dev/null +++ b/unittests/testS9306.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS9306(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s9306" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9312.py b/unittests/testS9312.py new file mode 100644 index 0000000..f673925 --- /dev/null +++ b/unittests/testS9312.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseHuawei import BASEHUAWEI + + +class deviceClassS9312(unittest.TestCase): + def setUp(self): + self.deviceClassName = "s9312" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["privilegeMode", + "_commit", + "addUser", + "getUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEHUAWEI) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testSr7750.py b/unittests/testSr7750.py new file mode 100644 index 0000000..611beb7 --- /dev/null +++ b/unittests/testSr7750.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseBaer import BASEBAER + + +class deviceClassSr7750(unittest.TestCase): + def setUp(self): + self.deviceClassName = "sr7750" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + """self.deviceClassMethod = ["_recv", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"]""" + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEBAER) + + """def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testSr7950.py b/unittests/testSr7950.py new file mode 100644 index 0000000..4c184ba --- /dev/null +++ b/unittests/testSr7950.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseBaer import BASEBAER + + +class deviceClassSr7950(unittest.TestCase): + def setUp(self): + self.deviceClassName = "sr7950" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEBAER) diff --git a/unittests/testSrx3400.py b/unittests/testSrx3400.py new file mode 100644 index 0000000..47ac1ff --- /dev/null +++ b/unittests/testSrx3400.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseJuniper import BASEJUNIPER + +class deviceClassSrx3400(unittest.TestCase): + def setUp(self): + self.deviceClassName = "srx3400" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["_recv", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASETELNET + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEJUNIPER) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testUsg1000.py b/unittests/testUsg1000.py new file mode 100644 index 0000000..4c28a63 --- /dev/null +++ b/unittests/testUsg1000.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseVenustech import BASEVENUSTECH + + +class deviceClassUsg1000(unittest.TestCase): + def setUp(self): + self.deviceClassName = "usg1000" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["_recv", + "privilegeMode", + "_commit", + "addUser", + "_configMode", + "_exitConfigMode", + "changePassword", + "deleteUser"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEVENUSTECH) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testVlb.py b/unittests/testVlb.py new file mode 100644 index 0000000..8dd91a0 --- /dev/null +++ b/unittests/testVlb.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseBrocade import BASEBROCADE + + +class deviceClassVlb(unittest.TestCase): + def setUp(self): + self.deviceClassName = "vlb" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.baseClassMethod = ["zcliMode", + "exitZcli"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1, 2, 3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1, 2, 3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEBROCADE) diff --git a/unittests/testVyoslinux.py b/unittests/testVyoslinux.py new file mode 100644 index 0000000..226ee58 --- /dev/null +++ b/unittests/testVyoslinux.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.bclinux7 import BCLINUX7 + +class deviceClassVyoslinux(unittest.TestCase): + def setUp(self): + self.deviceClassName = "vyoslinux" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + self.deviceClassMethod = ["execute"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BCLINUX7 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BCLINUX7) + + def test_device_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.deviceClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testZx5952.py b/unittests/testZx5952.py new file mode 100644 index 0000000..76e6cf0 --- /dev/null +++ b/unittests/testZx5952.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# encodint:utf-8 +# Author:Cheung Kei-Chuen +import unittest +import importlib +from forward.utils.forwardError import ForwardError +from forward.devclass.baseZte import BASEZTE + + +class deviceClassZx5952(unittest.TestCase): + def setUp(self): + self.deviceClassName = "zx5952" + self.initParameters = ["ip", + "username", + "password", + "port", + "timeout", + "privilegePw", + "isLogin", + "isEnable", + "channel", + "shell", + "basePrompt", + "prompt", + "moreFlag"] + self.baseClassMethod = ["login", + "logout", + "execute", + "getMore", + "getPrompt", + "cleanBuffer"] + + def test_class_parameters(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for parameter in self.initParameters: + if not hasattr(_dev(1,2,3), parameter): + raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) + + def test_base_class_method(self): + _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + for method in self.baseClassMethod: + if not hasattr(_dev(1,2,3), method): + raise IOError('%s not have parameter:' % (self.deviceClassName), method) + + def test_inherit_check(self): + # Inherit from BASESSHV2 + cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), + self.deviceClassName.upper()) + self.assertEquals(cls.__bases__[0], BASEZTE) From 169d3d651905c8cba41b4837fb14ff27db3ace2c Mon Sep 17 00:00:00 2001 From: Zhang Qi-chuan Date: Thu, 8 Feb 2018 16:45:35 +0800 Subject: [PATCH 4/9] Init forward. --- lib/forward/devclass/asa.py | 14 -- lib/forward/devclass/asr1006.py | 14 +- lib/forward/devclass/baseCisco.py | 298 +--------------------- lib/forward/devclass/baseFenghuo.py | 175 +------------ lib/forward/devclass/baseHuawei.py | 370 +--------------------------- lib/forward/devclass/baseJuniper.py | 239 ------------------ lib/forward/devclass/baseLinux.py | 115 +-------- lib/forward/devclass/c2960.py | 19 +- lib/forward/devclass/c4510.py | 18 +- lib/forward/devclass/c6509.py | 19 +- lib/forward/devclass/f510000.py | 18 +- lib/forward/devclass/n5548.py | 34 +-- lib/forward/devclass/n5596.py | 34 +-- lib/forward/devclass/n7010.py | 34 +-- lib/forward/devclass/n7018.py | 34 +-- lib/forward/devclass/n7710.py | 34 +-- lib/forward/devclass/n7718.py | 34 +-- lib/forward/devclass/ne40ex16.py | 35 --- lib/forward/devclass/r3048g.py | 79 +----- lib/forward/devclass/s3300.py | 203 --------------- lib/forward/devclass/s5800.py | 286 +-------------------- lib/forward/devclass/s9312.py | 270 +------------------- lib/forward/devclass/usg1000.py | 185 -------------- lib/forward/devclass/vlb.py | 71 +----- unittests/testAdx03100.py | 14 -- unittests/testAsa.py | 14 -- unittests/testAsr1006.py | 14 -- unittests/testBaseCisco.py | 23 +- unittests/testBaseHuawei.py | 23 +- unittests/testBaseJuniper.py | 21 +- unittests/testBaseLinux.py | 16 +- unittests/testBaseRaisecom.py | 21 +- unittests/testC2960.py | 14 -- unittests/testC4510.py | 14 -- unittests/testC6506.py | 14 -- unittests/testC6509.py | 15 +- unittests/testE1000e.py | 7 - unittests/testN5548.py | 15 -- unittests/testN5596.py | 14 -- unittests/testN7010.py | 14 -- unittests/testN7018.py | 14 -- unittests/testN7710.py | 15 -- unittests/testN7718.py | 15 -- unittests/testNe40ex16.py | 14 -- unittests/testNe40ex3.py | 15 -- unittests/testR3048g.py | 13 - unittests/testRg5510.py | 15 +- unittests/testS3300.py | 2 +- unittests/testS5328.py | 14 -- unittests/testS5352.py | 14 -- unittests/testS5800.py | 10 - unittests/testS8512.py | 14 -- unittests/testS9303.py | 14 -- unittests/testS9306.py | 14 -- unittests/testS9312.py | 15 -- unittests/testSr7750.py | 13 - unittests/testSr7950.py | 2 +- unittests/testSrx3400.py | 14 -- unittests/testUsg1000.py | 14 -- unittests/testVlb.py | 2 - unittests/testVyoslinux.py | 8 - unittests/testZx5952.py | 2 +- 62 files changed, 47 insertions(+), 3091 deletions(-) diff --git a/lib/forward/devclass/asa.py b/lib/forward/devclass/asa.py index 981647b..3c12f96 100644 --- a/lib/forward/devclass/asa.py +++ b/lib/forward/devclass/asa.py @@ -33,17 +33,3 @@ def cleanBuffer(self): buff += self.shell.recv(1024) except Exception: raise ForwardError('Receive timeout [%s]' % (buff)) - - def addUser(self, username, password): - # Overriding methods - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} password {password}\n') - - def changePassword(self, username, password): - # Overriding methods - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} password {password}\n') diff --git a/lib/forward/devclass/asr1006.py b/lib/forward/devclass/asr1006.py index 17c11cc..ba5b06e 100644 --- a/lib/forward/devclass/asr1006.py +++ b/lib/forward/devclass/asr1006.py @@ -14,16 +14,4 @@ class ASR1006(BASECISCO): """The device model belongs to the cisco series so the attributes and methods of BASECISCO are inherited. """ - def addUser(self, username, password): - # Overriding methods - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') - - def changePassword(self, username, password): - # Overriding methods - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') + pass diff --git a/lib/forward/devclass/baseCisco.py b/lib/forward/devclass/baseCisco.py index 10f7c24..83582c1 100644 --- a/lib/forward/devclass/baseCisco.py +++ b/lib/forward/devclass/baseCisco.py @@ -18,300 +18,4 @@ class BASECISCO(BASESSHV2): """This is a manufacturer of cisco, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - def privilegeMode(self): - """Used to switch from normal mode to privileged mode for command line mode. - Does not apply to other modes to switch to privileged mode. - """ - result = { - 'status': True, - 'content': '', - 'errLog': '' - } - # Clean buffer. - self.cleanBuffer() - if self.isLogin and (len(self.privilegePw) > 0): - """This can only be performed when the device - has been successfully logged in and the privilege mode password is specified.""" - # (login succeed status) and (self.privilegePw exist) - self.privilegeModeCommand = 'enable' - self.cleanBuffer() - self.shell.send('%s\n' % (self.privilegeModeCommand)) - enableResult = '' - while True: - """It's not until you have a password prompt or when you switch successfully - that you stop popping out of the loop.""" - """ - etc: - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ - - or - - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - Password: - """ - """ - fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' - """ - # need password - passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand - promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( - command=self.privilegeModeCommand, - basePrompt=self.basePrompt - ) - - # Second layers of judgment, Privileged command char 'super/enable' must be received. - # otherwise recv continue... important! - if re.search(passwordChar, enableResult): - # if received 'password' - break - # no password - elif re.search(promptChar, enableResult): - # if no password - break - else: - # not finished,continue - enableResult += self.shell.recv(1024) - - if re.search('assword', enableResult): - # need password - self.shell.send("%s\n" % self.privilegePw) - _data = '' - while not re.search(self.basePrompt, _data) and (not re.search('assword|denied|Denied', _data)): - _data += self.shell.recv(1024) - if re.search('assword|denied|Denied', _data): - # When send the self.privilegePw, once again encountered a password hint password wrong. - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Password incorrect' - elif re.search(self.basePrompt, _data): - # Switch mode succeed - self.getPrompt() - result['status'] = True - - # Check the error information in advance - elif re.search('\%|Invalid|\^', enableResult): - # bad enable command - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' - elif re.search(self.basePrompt, enableResult): - # Switch mode succeed, don't need password - self.getPrompt() - result['status'] = True - else: - result['stauts'] = False - result['errLog'] = '[Switch Mode Failed]: Unknown device status' - - elif not self.isLogin: - # login failed - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Not login yet' - - elif len(self.privilegePw) == 0: - # self.privilegePw dosen't exist, do nothing - pass - - return result - - def _commit(self, saveCommand='write', exitCommand='end'): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if self.isConfigMode: - # Exit from configuration mode to privileged mode. - self._exitConfigMode(exitCommand) - # save setup to system - self.shell.send('%s\n' % (saveCommand)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - """ - If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. - in the received information, it indicates that the save configuration is successful. - """ - if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): - result['status'] = True - else: - raise ForwardError('[Commit Config Error]: The current state is not configuration mode') - except ForwardError, e: - result['errLog'] = str(e) - result['status'] = False - return result - - def addUser(self, username, password, addCommand='username {username} password {password}\n'): - """Create a user on the device. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if not addCommand: - raise ForwardError("Please specify the add user's command") - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # check terminal status - if self.isConfigMode: - self.cleanBuffer() - # adduser - self.shell.send(addCommand.format(username=username, password=password)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - """If the program is in the received message, it searches for character - information such as error and inavalid, indicating that the account creation failed. - """ - if re.search('error|invalid', result['content'], flags=re.IGNORECASE): - result['content'] = '' - raise ForwardError(result['content']) - else: - # set password is successed. - result = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result - - def deleteUser(self, username=''): - """Delete a user on the device - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if not username: - raise ForwardError("Please specify a username") - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # check terminal status - if self.isConfigMode: - self.cleanBuffer() - # delete username - self.shell.send("no username {username}\n".format(username=username)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - if re.search('error|invalid', result['content'], flags=re.IGNORECASE): - raise ForwardError(result['content']) - else: - # deleted username - result = self._commit() - result['status'] = True - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result - - def getUser(self, command="show running-config | in username"): - """Gets the list of users on the device. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # [{"username":"zhang-qichuan","secret":5},{}....] - userList = [] - # execute query command - info = self.execute(command) - if not info["status"]: - raise ForwardError("Error:get user list failed: %s" % info["errLog"]) - # process result - result = info["content"] - for line in result.split('\n'): - # Each line - index = 0 - # ['username' , 'test-user' , 'secret', '5','$.........'] - segments = line.split() - for segment in segments: - if index <= 1: - index += 1 - # Check after second fields username my-username secret/password ..... - continue - else: - if segment == "secret" or segment == "password": - # get secret level - userData = {"username": segments[1], "secret": segments[index + 1]} - userList.append(userData) - break - index += 1 - result["content"] = userList - result["status"] = True - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result - - def _configMode(self, cmd='conf term'): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # Flag isCOnfigMode is False - self.isConfigMode = False - result = { - "status": False, - "content": "", - "errLog": "" - } - self.cleanBuffer() - self.shell.send("%s\n" % (cmd)) - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Flag config mode is True - self.isConfigMode = True - result['status'] = True - return result - - def _exitConfigMode(self, cmd='end'): - """Exit from configuration mode to privileged mode. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # Check current status - if self.isConfigMode: - self.shell.send("%s\n" % (cmd)) - """Because the mode is switched, it is only based on basePrompt - to determine whether the message is returned when the message is received. - """ - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # Flag isCOnfigMode is False - self.isConfigMode = False - result["status"] = True - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - result["status"] = False - result['errLog'] = str(e) - # release host prompt - self.getPrompt() - return result - - def changePassword(self, username, password, addCommand='username {username} password {password}\n'): - """Modify the password for the device account. - Because the password command to modify the account on the device is consistent with the creation - of the user's command, the interface to create the account is called. - """ - self.addUser(self, username=username, password=password, addCommand=addCommand) + pass diff --git a/lib/forward/devclass/baseFenghuo.py b/lib/forward/devclass/baseFenghuo.py index 5fc286c..055fbe4 100644 --- a/lib/forward/devclass/baseFenghuo.py +++ b/lib/forward/devclass/baseFenghuo.py @@ -15,177 +15,4 @@ class BASEFENGHUO(BASESSHV2): """This is a manufacturer of fenghuo, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - def privilegeMode(self): - """Used to switch from normal mode to privileged mode for command line mode. - Does not apply to other modes to switch to privileged mode. - """ - self.privilegeModeCommand = 'enable' - result = { - 'status': True, - 'content': '', - 'errLog': '' - } - self.cleanBuffer() - if self.isLogin and (len(self.privilegePw) > 0): - """This can only be performed when the device - has been successfully logged in and the privilege mode password is specified.""" - # (login succeed status) and (self.privilegePw exist) - self.cleanBuffer() - self.shell.send('%s\n' % (self.privilegeModeCommand)) - enableResult = '' - while True: - """ - etc: - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ - - or - - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - Password: - """ - """ - fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' - """ - # need password - passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand - promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( - command=self.privilegeModeCommand, - basePrompt=self.basePrompt - ) - - # Second layers of judgment, Privileged command char 'super/enable' must be received. - # otherwise recv continue... important! - if re.search(passwordChar, enableResult): - # if received 'password' - break - # no password - elif re.search(promptChar, enableResult): - # if no password - break - else: - # not finished,continue - enableResult += self.shell.recv(1024) - - if re.search('assword', enableResult): - # need password - self.shell.send("%s\n" % self.privilegePw) - result = '' - while not re.search(self.basePrompt, result) and (not re.search('assword|denied|Denied', result)): - result += self.shell.recv(1024) - if re.search('assword|denied|Denied', result): - # When send the self.privilegePw, once again encountered a password hint password wrong. - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Password incorrect' - elif re.search(self.basePrompt, result): - # Switch mode succeed - self.getPrompt() - result['status'] = True - - # Check the error information in advance - elif re.search('\%|Invalid|\^', enableResult): - # bad enable command - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' - elif re.search(self.basePrompt, enableResult): - # Switch mode succeed, don't need password - self.getPrompt() - result['status'] = True - else: - result['stauts'] = False - result['errLog'] = '[Switch Mode Failed]: Unknown device status' - - elif not self.isLogin: - # login failed - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Not login yet' - - elif len(self.privilegePw) == 0: - # self.privilegePw dosen't exist, do nothing - pass - return result - - def _commit(self, saveCommand='write file', exitCommand='quit'): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if self.isConfigMode: - self._exitConfigMode(exitCommand) - # save setup to system - self.shell.send('%s\n' % (saveCommand)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # When prompted, reply Y,Search range at last line - if re.search(re.escape("Are you sure?(y/n) [y]"), result['content'].split('\n')[-1]): - self.shell.send("y\n") - continue - """ - If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. - in the received information, it indicates that the save configuration is successful. - """ - if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): - result['status'] = True - # Clean buffer - self.cleanBuffer() - else: - raise ForwardError('[Commit Config Error]: The current state is not configuration mode') - except ForwardError, e: - result['errLog'] = str(e) - result['status'] = False - return result - - def _configMode(self, cmd='configure'): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # Flag isCOnfigMode is False - self.isConfigMode = False - result = { - "status": False, - "content": "", - "errLog": "" - } - self.cleanBuffer() - self.shell.send("%s\n" % (cmd)) - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Flag isCOnfigMode is True - self.isConfigMode = True - result['status'] = True - return result - - def _exitConfigMode(self, cmd='quit'): - """Exit from configuration mode to privileged mode. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # Check current status - if self.isConfigMode: - self.shell.send("%s\n" % (cmd)) - """Exit from configuration mode to privileged mode. - """ - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # Flag isCOnfigMode is False - self.isConfigMode = False - result["status"] = True - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - result["status"] = False - result['errLog'] = str(e) - # release host prompt - self.getPrompt() - return result + pass diff --git a/lib/forward/devclass/baseHuawei.py b/lib/forward/devclass/baseHuawei.py index b62f2e4..459c0f7 100644 --- a/lib/forward/devclass/baseHuawei.py +++ b/lib/forward/devclass/baseHuawei.py @@ -17,372 +17,4 @@ class BASEHUAWEI(BASESSHV2): """This is a manufacturer of huawei, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - def privilegeMode(self): - """Used to switch from normal mode to privileged mode for command line mode. - Does not apply to other modes to switch to privileged mode. - """ - self.privilegeModeCommand = 'super' - result = { - 'status': True, - 'content': '', - 'errLog': '' - } - self.cleanBuffer() - if self.isLogin and (len(self.privilegePw) > 0): - # (login succeed status) and (self.privilegePw exist) - self.cleanBuffer() - self.shell.send('%s\n' % (self.privilegeModeCommand)) - enableResult = '' - while True: - """ - etc: - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ - - or - - [admin@NFJD-PSC-MGMT-COREVM60 ~]$ super - Password: - """ - """ - fg3950: enable command result : 'enable\r\r\nUnknown action 0\r\n' - """ - # need password - passwordChar = """%s[\r\n]+ *[pP]assword""" % self.privilegeModeCommand - promptChar = """{command}[\r\n]+[\s\S]*{basePrompt}""".format( - command=self.privilegeModeCommand, - basePrompt=self.basePrompt - ) - - # Second layers of judgment, Privileged command char 'super/enable' must be received. - # otherwise recv continue... important! - if re.search(passwordChar, enableResult): - # if received 'password' - break - # no password - elif re.search(promptChar, enableResult): - # if no password - break - else: - # not finished,continue - enableResult += self.shell.recv(1024) - - if re.search('assword', enableResult): - # need password - self.shell.send("%s\n" % self.privilegePw) - result = '' - while not re.search(self.basePrompt, result) and (not re.search('assword|denied|Denied', result)): - result += self.shell.recv(1024) - if re.search('assword|denied|Denied', result): - # When send the self.privilegePw, once again encountered a password hint password wrong. - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Password incorrect' - elif re.search(self.basePrompt, result): - # Switch mode succeed - self.getPrompt() - result['status'] = True - - # Check the error information in advance - elif re.search('\%|Invalid|\^', enableResult): - # bad enable command - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Privileged mode command incorrect-A' - elif re.search(self.basePrompt, enableResult): - # Switch mode succeed, don't need password - self.getPrompt() - result['status'] = True - else: - result['stauts'] = False - result['errLog'] = '[Switch Mode Failed]: Unknown device status' - - elif not self.isLogin: - # login failed - result['status'] = False - result['errLog'] = '[Switch Mode Failed]: Not login yet' - - elif len(self.privilegePw) == 0: - # self.privilegePw dosen't exist, do nothing - pass - - return result - - def _commit(self, saveCommand='save', exitCommand='return'): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if self.isConfigMode: - # Exit from configuration mode to privileged mode. - self._exitConfigMode(exitCommand) - # save setup to system - self.shell.send('%s\n' % (saveCommand)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # When prompted, reply Y,Search range at last line - if re.search(re.escape("Are you sure to continue?[Y/N]"), result["content"].split("\n")[-1]): - self.shell.send("Y\n") - """ - If the program finds information like ‘success’, ‘OK’, ‘copy complete’, etc. - in the received information, it indicates that the save configuration is successful. - """ - if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): - result['status'] = True - else: - raise ForwardError('[Commit Config Error]: The current state is not configuration mode') - except ForwardError, e: - result['errLog'] = str(e) - result['status'] = False - return result - - def addUser(self, username, password, userLevel=1): - """Create a user on the device. - """ - # user leve default 1 - data = {"status": False, - "content": "", - "errLog": ""} - try: - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - checkPermission = self._configMode(cmd='sys\naaa') - # swith to config terminal mode. - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - if self.isConfigMode: - # check terminal status - self.shell.send('local-user {username} password cipher {password}\n'.format(username=username, - password=password)) - while True: - # Check that the user is created. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and\ - (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - # Set the user level for the new user. - self.shell.send('local-user {username} privilege level {userLevel}\n'.format(username=username, - userLevel=userLevel)) - data['content'] = '' - while True: - # Check whether the user level Settings are complete. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and\ - (re.search('local-user .* privilege level[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - # Set the user terminal parameters. - self.shell.send("local-user {username} service-type terminal ssh\n".format(username=username)) - data['content'] = '' - while True: - # Check whether the user terminal parameters are set. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ - (re.search('local-user .* service-type terminal ssh[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - self.shell.send("quit\n") - data['content'] = '' - while True: - # Exit create user mode. - if (re.search(self.basePrompt, data['content'].split('\n')[-1])) and \ - (re.search('quit.*[\s\S]+%s' % self.basePrompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - self.getPrompt() - # Set the password for the new user. - self.shell.send("ssh user {username} authentication-type password\n".format(username=username)) - data['content'] = '' - while True: - # Check that the password is set. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ - (re.search('ssh user .* authentication-type password[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - # Set the user terminal parameters. - self.shell.send("ssh user {username} service-type all\n".format(username=username)) - data['content'] = '' - while True: - # # Check whether the user terminal parameters are set. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ - (re.search('ssh user .* service-type all[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - # Save the configuration - data = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['status'] = False - data['errLog'] = str(e) - return data - - def getUser(self, command="show running-config | in username"): - """Gets the list of users on the device. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # [{"username":"zhang-qichuan","secret":5},{}....] - userList = [] - # execute query command - info = self.execute(command) - if not info["status"]: - raise ForwardError("Error:get user list failed: %s" % info["errLog"]) - # process result - result = info["content"] - for line in result.split('\n'): - # Each line - index = 0 - # ['username' , 'test-user' , 'secret', '5','$.........'] - segments = line.split() - for segment in segments: - if index <= 1: - index += 1 - # Check after second fields username my-username secret/password ..... - continue - else: - if segment == "secret" or segment == "password": - # get secret level - userData = {"username": segments[1], "secret": segments[index + 1]} - userList.append(userData) - break - index += 1 - result["content"] = userList - result["status"] = True - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result - - def _configMode(self, cmd='sys'): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # cmd = 'sys\naaa' if addUser - # Flag config mode is False - self.isConfigMode = False - result = { - "status": False, - "content": "", - "errLog": "" - } - self.cleanBuffer() - self.shell.send("%s\n" % (cmd)) - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Flag config mode is True - self.isConfigMode = True - result['status'] = True - return result - - def _exitConfigMode(self, cmd='return'): - """Exit from configuration mode to privileged mode. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - self.getPrompt() - # Check current status - if self.isConfigMode: - self.shell.send("%s\n" % (cmd)) - """Because the mode is switched, it is only based on basePrompt - to determine whether the message is returned when the message is received. - """ - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # Flag isCOnfigMode is False - self.isConfigMode = False - result["status"] = True - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - result["status"] = False - result['errLog'] = str(e) - # release host prompt - self.getPrompt() - return result - - def changePassword(self, username, password, userLevel=1): - """Modify the password for the device account. - """ - # user leve default 1 - data = {"status": False, - "content": "", - "errLog": ""} - try: - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - checkPermission = self._configMode() - # swith to config terminal mode. - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - if self.isConfigMode: - # check terminal status - self.shell.send('local-user {username} password cipher {password}\n'.format(username=username, - password=password)) - while True: - # Check that the password has been modified - if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ - (re.search('local-user .* password cipher[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - data = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['status'] = False - data['errLog'] = str(e) - return data - - def deleteUser(self, username): - """Delete a user on the device - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - if self.isConfigMode: - # check terminal status - self.cleanBuffer() - self.shell.send('undo local-user {username}\n'.format(username=username)) - while True: - # Check whether the user has been deleted. - if (re.search(self.prompt, data['content'].split('\n')[-1])) and \ - (re.search('undo local-user[\s\S]+%s' % self.prompt, data['content'])): - break - else: - data['content'] += self.shell.recv(1024) - # When prompted, reply Y,Search range at last line - if re.search('error|invalid', data['content'], flags=re.IGNORECASE): - raise ForwardError(data['content']) - # Save the configuration - data = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['status'] = False - data['errLog'] = str(e) - return data + pass diff --git a/lib/forward/devclass/baseJuniper.py b/lib/forward/devclass/baseJuniper.py index 13cc52c..bfd7da5 100644 --- a/lib/forward/devclass/baseJuniper.py +++ b/lib/forward/devclass/baseJuniper.py @@ -29,242 +29,3 @@ def _recv(self, _prompt): except ForwardError, e: data['errLog'] = str(e) return data - - def _configMode(self): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # Flag isCOnfigMode is False - self.isConfigMode = False - data = {"status": False, - "content": "", - "errLog": ""} - self.cleanBuffer() - self.channel.write("configure\n") - # Get result - data = self._recv(self.basePrompt) - if data['status']: - self.isConfigMode = True - self.getPrompt() - return data - - def _exitConfigMode(self): - """Exit from configuration mode to privileged mode. - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # Check current status - if self.isConfigMode: - self.channel.write("exit\n") - # Get result - data = self._recv(self.basePrompt) - if data['status']: - self.isConfigMode = False - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - self.getPrompt() - return data - - def _commit(self): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # Check status - if self.isConfigMode: - self.channel.write('commit\n') - result = self._recv(self.prompt) - # If the success character is found, it is successful. - if re.search('succeeds', result['content'], flags=re.IGNORECASE): - data['status'] = True - else: - data['content'] = result['content'] - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def addUser(self, username, password, admin=False): - """Create a user on the device. - """ - # Separate commands to create administrator accounts and common accounts. - if admin: - command = "set system login user {username} class read-only\n".format(username=username) - else: - command = "set system login user {username} class ABC\n".format(username=username) - data = {"status": False, - "content": "", - "errLog": ""} - try: - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - checkPermission = self._configMode() # swith to config terminal mode. - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # check terminal status - if self.isConfigMode: - # adduser - self.channel.write(command) - # recv result - data = self._recv(self.prompt) - if not data['status']: - # break - raise ForwardError(data['errLog']) - # execute useradd command - self.channel.write('set system login user {username} \ - authentication plain-text-password\n'.format(username=username)) - i = self.channel.expect([r"New password:", r"%s" % self.prompt], timeout=self.timeout) - result = i[-1] - if re.search('error|invalid', result, flags=re.IGNORECASE): - # command failure - raise ForwardError(result) - # Enter password - self.channel.write("{password}\n".format(password=password)) - # check password - i = self.channel.expect([r"Retype new password:", r"%s" % self.prompt], timeout=self.timeout) - # repassword - if i[0] == 0: - self.channel.write("{password}\n".format(password=password)) - # check password - i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) - if i[0] == 0: - result = i[-1] - if re.search('error|invalid', result, flags=re.IGNORECASE): - raise ForwardError(result) - else: - # set password is successed. - data = self._commit() - # exit config terminal mode. - self._exitConfigMode() - elif i[0] == -1: - raise ForwardError('Error: receive timeout') - elif i[0] == 1: - # password wrong - raise ForwardError(i[-1]) - elif i[0] == -1: - # timeout - raise ForwardError('Error: receive timeout') - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def deleteUser(self, username): - """Delete a user on the device - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - if not username: - raise ForwardError('Please specify a username') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # check terminal status - if self.isConfigMode: - # delete user - self.channel.write('delete system login user {username}\n'.format(username=username)) - i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) - result = i[-1] - if re.search('error|invalid', result, flags=re.IGNORECASE): - # command failure - raise ForwardError(result) - else: - # Save - data = self._commit() - # exit config terminal mode. - self._exitConfigMode() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def changePassword(self, username, password): - """Modify the password for the device account. - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # check terminal status - if self.isConfigMode: - # execute useradd command - self.channel.write('set system login user {username} \ - authentication plain-text-password\n'.format(username=username)) - i = self.channel.expect([r"New password:", r"%s" % self.prompt], timeout=self.timeout) - result = i[-1] - if re.search('error|invalid', result, flags=re.IGNORECASE): - # command failure - raise ForwardError(result) - # Enter password - self.channel.write("{password}\n".format(password=password)) - # check password - i = self.channel.expect([r"Retype new password:", r"%s" % self.prompt], timeout=self.timeout) - if i[0] == 0: - # repassword - self.channel.write("{password}\n".format(password=password)) - # check password - i = self.channel.expect([r"%s" % self.prompt], timeout=self.timeout) - if i[0] == 0: - # Get result. - result = i[-1] - if re.search('error|invalid', result, flags=re.IGNORECASE): - raise ForwardError(result) - else: - # change password is successed. - data = self._commit() - # exit config terminal mode. - self._exitConfigMode() - elif i[0] == -1: - raise ForwardError('Error: receive timeout') - elif i[0] == 1: - # password wrong - raise ForwardError(i[-1]) - elif i[0] == -1: - # timeout - raise ForwardError('Error: receive timeout') - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - # def bindBandwidth(self, ip='', bandwidth=''): - # njInfo = {"status": False, - # "content": "", - # "errLog": ""} - # mx960Bandwidth = Bandwidth(ip=ip, bandwidth=bandwidth, shell=self) - # njInfo = mx960Bandwidth.bindBandwidth() - # return njInfo - # - # def deleteBindIPAndBandwidth(self, ip='', bandwidth=''): - # njInfo = {"status": False, - # "content": "", - # "errLog": ""} - # mx960Bandwidth = Bandwidth(ip=ip, bandwidth=bandwidth, shell=self) - # njInfo = mx960Bandwidth.deleteBindIPAndBandwidth() - # return njInfo diff --git a/lib/forward/devclass/baseLinux.py b/lib/forward/devclass/baseLinux.py index 53f2c47..49dab84 100644 --- a/lib/forward/devclass/baseLinux.py +++ b/lib/forward/devclass/baseLinux.py @@ -18,117 +18,4 @@ class BASELINUX(BASESSHV2): """This is a manufacturer of linux, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - def privilegeMode(self): - """Used to switch from normal mode to privileged mode for command line mode. - Does not apply to other modes to switch to privileged mode. - """ - result = { - 'status': True, - 'content': '', - 'errLog': '' - } - return result - - def addUser(self, username, password, **kwargs): - """Create a user on the device. - """ - # Extra parameters - group = kwargs['group'] if 'group' in kwargs else username - commandAdduser = 'adduser %s' % username if group == username else 'adduser --gid %s %s' % (group, username) - commandPw = 'passwd %s\n' % username - - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # legal check - if not group: - raise ForwardError("[Add User Error]: %s: Group could NOT be blank." % self.ip) - if not username or not password: - raise ForwardError("[Add User Error]: %s: Username or Password could NOT be blank." % self.ip) - - if self.isLogin: - # execute adduser - addUserResult = self.execute(commandAdduser) - if addUserResult['status']: - dirExtPattern = '(目录已经存在|home directory already exists)' - - if not addUserResult['content']: - # success - pass - elif re.search(dirExtPattern, addUserResult['content']): - # success, but homedir already exist - pass - else: - # other errors - raise ForwardError("[Add User Error]: %s: %s" % (self.ip, addUserResult['content'])) - - # set passwd - self.shell.send(commandPw) - buff = '' - while not (re.search(self.basePrompt, buff) or re.search('New password:', buff)): - buff += self.shell.recv(256) - if re.search('New password:', buff): - # send password - self.shell.send(password + '\n') - buff = '' - while not (re.search(self.basePrompt, buff) or re.search('Retype new password:', buff)): - buff += self.shell.recv(256) - if re.search('Retype new password:', buff): - # Confirm password - self.shell.send(password + '\n') - buff = '' - while not re.search(self.prompt, buff): - buff += self.shell.recv(256) - # successed. - if re.search('updated successfully', buff): - result['status'] = True - return result - - # error somewhere, raise - raise ForwardError("[Set Password Error]: %s: %s" % (self.ip, buff)) - else: - raise ForwardError("[Add User Error]: %s: %s" % (self.ip, addUserResult['errLog'])) - else: - raise ForwardError("[Add User Error]: %s: Not login yet." % self.ip) - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result - - def deleteUser(self, username): - """Delete a user on the device - """ - # set command - commandDelUser = 'userdel %s' % username - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - if not username: - raise ForwardError("[Delete User Error]: %s: Username could NOT be blank." % self.ip) - # Login status check. - if self.isLogin: - # send command. - delUserResult = self.execute(commandDelUser) - if delUserResult['status']: - if not delUserResult['content']: - # success - pass - else: - # failed. - raise ForwardError("[Delete User Error]: %s: %s" % (self.ip, delUserResult['content'])) - result['status'] = True - return result - else: - raise ForwardError("[Delete User Error]: %s: %s" % (self.ip, delUserResult['errLog'])) - else: - raise ForwardError("[Delete User Error]: %s: Not login yet." % self.ip) - except ForwardError, e: - result['status'] = False - result['errLog'] = str(e) - return result + pass diff --git a/lib/forward/devclass/c2960.py b/lib/forward/devclass/c2960.py index 2b9b8f7..1bb1180 100644 --- a/lib/forward/devclass/c2960.py +++ b/lib/forward/devclass/c2960.py @@ -14,21 +14,4 @@ class C2960(BASECISCO): """This is a manufacturer of cisco, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - - def addUser(self, username, password): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in deleting user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') + pass diff --git a/lib/forward/devclass/c4510.py b/lib/forward/devclass/c4510.py index 8a8871e..f24116d 100644 --- a/lib/forward/devclass/c4510.py +++ b/lib/forward/devclass/c4510.py @@ -14,20 +14,4 @@ class C4510(BASECISCO): """This is a manufacturer of cisco, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - def addUser(self, username, password): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in deleting user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') + pass diff --git a/lib/forward/devclass/c6509.py b/lib/forward/devclass/c6509.py index dd7f668..0aa9f9a 100644 --- a/lib/forward/devclass/c6509.py +++ b/lib/forward/devclass/c6509.py @@ -14,21 +14,4 @@ class C6509(BASECISCO): """This is a manufacturer of cisco, using the SSHV2 version of the protocol, so it is integrated with BASESSHV2 library. """ - - def addUser(self, username, password): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in deleting user parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='username {username} secret {password}\n') + pass diff --git a/lib/forward/devclass/f510000.py b/lib/forward/devclass/f510000.py index 96228c3..dd3d61d 100644 --- a/lib/forward/devclass/f510000.py +++ b/lib/forward/devclass/f510000.py @@ -12,20 +12,4 @@ class F510000(BASEF5): """This is a manufacturer of F5, it is integrated with BASEF5 library. """ - - def addUser(self, username, password): - """Because the device of this model is different from the other F5 - devices in creating user parameters, it is rewritten. - """ - return BASEF5.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - - def _commit(self): - """Because the device of this model is different from the other - F5 devices in deleting user parameters, it is rewritten. - """ - return BASEF5._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') + pass diff --git a/lib/forward/devclass/n5548.py b/lib/forward/devclass/n5548.py index 9c6a1e6..51d8d4b 100644 --- a/lib/forward/devclass/n5548.py +++ b/lib/forward/devclass/n5548.py @@ -12,36 +12,4 @@ class N5548(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # default is not admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/n5596.py b/lib/forward/devclass/n5596.py index ff647ed..8b15761 100644 --- a/lib/forward/devclass/n5596.py +++ b/lib/forward/devclass/n5596.py @@ -12,36 +12,4 @@ class N5596(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # default is not admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/n7010.py b/lib/forward/devclass/n7010.py index f527c19..03ae941 100644 --- a/lib/forward/devclass/n7010.py +++ b/lib/forward/devclass/n7010.py @@ -12,36 +12,4 @@ class N7010(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # param admin: defualt is not admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/n7018.py b/lib/forward/devclass/n7018.py index 92d74cd..f657829 100644 --- a/lib/forward/devclass/n7018.py +++ b/lib/forward/devclass/n7018.py @@ -12,36 +12,4 @@ class N7018(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # default not is Admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/n7710.py b/lib/forward/devclass/n7710.py index 88cc3a1..66bf2ea 100644 --- a/lib/forward/devclass/n7710.py +++ b/lib/forward/devclass/n7710.py @@ -12,36 +12,4 @@ class N7710(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # default not is Admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/n7718.py b/lib/forward/devclass/n7718.py index 6be24d4..783d10a 100644 --- a/lib/forward/devclass/n7718.py +++ b/lib/forward/devclass/n7718.py @@ -12,36 +12,4 @@ class N7718(BASECISCO): """This is a manufacturer of cisco, so it is integrated with BASECISCO library. """ - - def addUser(self, username, password, admin=False): - """Because the device of this model is different from the other Cisco - devices in creating user parameters, it is rewritten. - """ - # default not is Admin - if admin: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') - else: - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role priv-1\n') - - def _commit(self): - """Because the device of this model is different from the other - Cisco devices in commit parameters, it is rewritten. - """ - return BASECISCO._commit(self, - saveCommand='copy running-config startup-config', - exitCommand='end') - - def changePassword(self, username, password): - """Because the device of this model is different from the other - Cisco devices in change user's password parameters, it is rewritten. - """ - return BASECISCO.addUser(self, - username=username, - password=password, - addCommand='user {username} password {password} role network-admin\n') + pass diff --git a/lib/forward/devclass/ne40ex16.py b/lib/forward/devclass/ne40ex16.py index ae32c07..1d649a0 100644 --- a/lib/forward/devclass/ne40ex16.py +++ b/lib/forward/devclass/ne40ex16.py @@ -14,41 +14,6 @@ class NE40EX16(BASEHUAWEI): """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. """ - def _commit(self): - """Because the device of this model is different from the other - huawei devices in commit parameters, it is rewritten. - """ - saveCommand = "save" - # exitCommand = "return" - data = {"status": False, - "content": "", - "errLog": ""} - try: - # Check the config mode status. - if self.isConfigMode: - self._exitConfigMode() - # exit config mode - self.shell.send('%s\n' % (saveCommand)) - # save setup to system - while not re.search(self.prompt, data['content'].split('\n')[-1]): - data['content'] += self.shell.recv(1024) - # When prompted, reply Y,Search range at last line - if re.search(re.escape('Are you sure to continue?[Y/N]'), data['content'].split('\n')[-1]): - # interact,send y - self.shell.send("y\n") - """ - If the program finds information like ‘success’, etc. - in the received information, it indicates that the save configuration is successful. - """ - if re.search(re.escape('Save the configuration successfully'), data['content'], flags=re.IGNORECASE): - data['status'] = True - else: - raise IOError('Error: The current state is not configuration mode') - except Exception, e: - data['errLog'] = str(e) - data['status'] = False - return data - def login(self): """Because the device of this model is different from the other huawei devices in commit parameters, it is rewritten. diff --git a/lib/forward/devclass/r3048g.py b/lib/forward/devclass/r3048g.py index 9eff742..6e9409f 100644 --- a/lib/forward/devclass/r3048g.py +++ b/lib/forward/devclass/r3048g.py @@ -14,81 +14,4 @@ class R3048G(BASERAISECOM): """This is a manufacturer of raisecom, so it is integrated with BASERAISECOM library. """ - def _configMode(self, cmd="configure"): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # Flag config mode is False - self.isConfigMode = False - result = { - "status": False, - "content": "", - "errLog": "" - } - # Clean buffer. - self.cleanBuffer() - self.shell.send("%s\n" % (cmd)) - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Flag config mode is True. - self.isConfigMode = True - result['status'] = True - return result - - def _exitConfigMode(self, cmd='quit'): - """Exit from configuration mode to privileged mode. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # Check current status - if self.isConfigMode: - self.shell.send("%s\n" % (cmd)) - while not re.search(self.basePrompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - # Flag config mode is False. - self.isConfigMode = False - result["status"] = True - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - result["status"] = False - result['errLog'] = str(e) - # release host prompt - self.getPrompt() - return result - - def _commit(self, saveCommand='write', exitCommand='quit'): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - result = { - "status": False, - "content": "", - "errLog": "" - } - try: - # Status check. - if self.isConfigMode: - self._exitConfigMode(exitCommand) - # save setup to system - self.shell.send('%s\n' % (saveCommand)) - while not re.search(self.prompt, result['content'].split('\n')[-1]): - result['content'] += self.shell.recv(1024) - """ - If the program finds information like ‘success’, 'OK' etc. - in the received information, it indicates that the save configuration is successful. - """ - if re.search('(\[OK\])|(Copy complete)|(successfully)', result['content'], flags=re.IGNORECASE): - result['status'] = True - else: - raise ForwardError('[Commit Config Error]: The current state is not configuration mode') - except ForwardError, e: - result['errLog'] = str(e) - result['status'] = False - return result + pass diff --git a/lib/forward/devclass/s3300.py b/lib/forward/devclass/s3300.py index c0760a7..e9daf0a 100644 --- a/lib/forward/devclass/s3300.py +++ b/lib/forward/devclass/s3300.py @@ -23,25 +23,6 @@ def __init__(self, *args, **kws): self.moreFlag = re.escape('....press ENTER to next \ line, Q to quit, other key to next page....') - def _configMode(self): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - data = {'status': False, - 'content': '', - 'errLog': ''} - # Flag config mode is False. - self.isConfigMode = False - # Clean buffer. - self.cleanBuffer() - self.channel.send('conf term\n') - # Get result. - data = self._recv(self.basePrompt) - self.getPrompt() - if data['content']: - self.isConfigMode = True - return data - def _recv(self, _prompt): """A message returned after the receiving device has executed the command. """ @@ -68,187 +49,3 @@ def _recv(self, _prompt): data['errLog'] = str(e) data['status'] = False return data - - def _exitConfigMode(self): - """Exit from configuration mode to privileged mode. - """ - # Set command. - exitCommand = "end" - data = {'status': False, - 'content': '', - 'errLog': ''} - try: - # Check config mode status. - if self.isConfigMode: - # Check current status - self.channel.send("%s\n" % (exitCommand)) - # Get result. - data = self._recv(self.basePrompt) - if data['status']: - # Flag config mode is False. - self.isConfigMode = False - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - self.getPrompt() - # release host prompt - return data - - def _commit(self): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - data = {'status': False, - 'content': '', - 'errLog': ''} - # Set command. - saveCommand = "copy running-config startup-config" - try: - # Check config mode status. - if self.isConfigMode: - # Exit config mode. - self._exitConfigMode() - self.channel.send('%s\n' % (saveCommand)) - # save setup to system - data = self._recv(self.prompt) - # Permission denied - if re.search('user "admin" only', data['content']): - raise ForwardError(data['content']) - else: - data['status'] = True - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def addUser(self, username, password, userLevel=1): - """Create a user on the device. - """ - data = {'status': False, - 'content': '', - 'errLog': ''} - try: - if not username or not password: - raise ForwardError('Please specify the username = your-username \ - and password = your-password') - # Specify a user name and password parameters here. - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - if self.isConfigMode: - # check terminal status - self.channel.send("""username {username} privilege {userLevel} \ - password 0 {password}\n""".format(username=username, - password=password, - userLevel=userLevel)) - # Get result. - _result = self._recv(self.prompt) - _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) - # Permission denied - if _tmp: - raise ForwardError(_tmp.group()) - elif not _result['status']: - # Message acceptance failed - raise ForwardError(_result['errLog']) - # Send the command to create an account. - self.channel.send("""username {username} terminal ssh\n""".format(username=username, - password=password, - userLevel=userLevel)) - # Get result. - _result = self._recv(self.prompt) - if _result['status']: - # Save the configuration - data = self._commit() - else: - data = _result - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def deleteUser(self, username): - """Delete a user on the device - """ - data = {'status': False, - 'content': '', - 'errLog': ''} - try: - if not username: - raise ForwardError('Please specify a username') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # Check config mode status. - if self.isConfigMode: - # check terminal status - self.channel.send("""no username {username}\n""".format(username=username)) - # Get result. - _result = self._recv(self.prompt) - # Permission denied - _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) - if _tmp: - raise ForwardError(_tmp.group()) - elif not _result['status']: - # Message acceptance failed - raise ForwardError(_result['errLog']) - if re.search('error|invalid', data['content'], flags=re.IGNORECASE): - raise ForwardError(data['content']) - if _result['status']: - # Save the configuration - data = self._commit() - else: - data = _result - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def changePassword(self, username, password, userLevel=1): - """Modify the password for the device account. - """ - data = {'status': False, - 'content': '', - 'errLog': ''} - try: - if not username or not password: - # Specify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # Check config mode stauts. - if self.isConfigMode: - # check terminal status - self.channel.send("""username {username} password 0 {password}\n""".format(username=username, - password=password, - userLevel=userLevel)) - # Get result. - _result = self._recv(self.prompt) - _tmp = re.search("""This command can be used by user "admin" only""", _result['content']) - # Permission denied - if _tmp: - raise ForwardError(_tmp.group()) - elif not _result['status']: - # Message acceptance failed - raise ForwardError(_result['errLog']) - if _result['status']: - # Save the configuration - data = self._commit() - else: - data = _result - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data diff --git a/lib/forward/devclass/s5800.py b/lib/forward/devclass/s5800.py index 78b26f6..c6f96fe 100644 --- a/lib/forward/devclass/s5800.py +++ b/lib/forward/devclass/s5800.py @@ -14,288 +14,4 @@ class S5800(BASEFENGHUO): """This is a manufacturer of fenghuo, so it is integrated with BASEFENGHUO library. """ - def isVlan(self, vlan): - """Check if the Vlan exists. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # swith to config mode - # info = self._configMode() - # if not info["status"]: - # raise ForwardError(info["errLog"]) - # switch to enable mode. - tmp = self.privilegeMode() - if not tmp: - raise ForwardError(tmp["errLog"]) - while True: - # Send command. - tmp = self.execute("show vlan {vlan} verbose".format(vlan=vlan)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - if re.search("VLAN ID:{vlan}".format(vlan=vlan), tmp["content"]): - # vlan is exists - info["status"] = True - break - elif re.search("Command is in use by", tmp["content"]): - # check failed,recheck - print 'Rechecking vlan...' - continue - else: - # vlan not is exitsts - info["status"] = False - info["errLog"] = tmp["content"] - break - return info - - def createVlan(self, vlan): - """Create a Vlan. - """ - info = {"status": False, - "content": "", - "errLog": ""} - """Warning: that vlan should be checked - by the 'self.isvlan(vlan) method - before setting up the vlan""" - # swith to config mode - info = self._configMode() - if not info["status"]: - raise ForwardError(info["errLog"]) - try: - # enter vlan - self.shell.send("vlan {vlan}\n".format(vlan=vlan)) - # Host prompt is modified - info["content"] = "" - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - self.getPrompt() - if not re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt): - raise ForwardError("Failed to enter vlan mode,command:vlan {vlan}".format(vlan=vlan)) - # exit vlan,switch to config mode - self.shell.send("quit\n") - # Host prompt is modified - info["content"] = "" - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get host prompt. - self.getPrompt() - # Failure to search for Vlan information. - if re.search('vlan.*{vlan}'.format(vlan=vlan), self.prompt): - raise ForwardError("Failed to exit vlan mode,command:quit") - # Save the configuration. - tmp = self._commit() - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the save configuration failed!") - else: - # Check is Vlan. - tmp = self.isVlan(vlan) - if not tmp["status"]: - # check vlan - raise ForwardError("Vlan has been set and has been saved, but the final\ - check found no configuration, so failed.\ - show vlan {vlan} verbose: [{content}]".format(vlan=vlan, content=tmp["errLog"])) - else: - # create successed. exit config mode - info["status"] = True - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - return info - - def isVlanInPort(self, vlan=None, port=None): - """Check that the Vlan exists in the port. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # Parameters check. - if (vlan is None) or (port is None): - raise ForwardError('Specify the `vlan` and `port` parameters') - # Execute command. - info = self.execute("show run") - if not info["status"]: - raise ForwardError(info["errLog"]) - try: - # Keyword search - tmp = re.search("\![\r\n]+interface gigaethernet {port}[\s\S]*por\ -t link-type (access|trunk)[\s\S]*port .* vlan .*{vlan}".format(vlan=vlan, port=port), info["content"]) - if tmp: - # Vlan in the port, case 1 - if tmp.group(1) == "access": - raise ForwardError("Configuration found, but port link - type is 'access', Not a trunk") - info["content"] = tmp.group().split("ABCDEFG") - info["status"] = True - else: - # No exists' - raise ForwardError('No exists') - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - return info - - def createVlanInPort(self, port=None, vlan=None): - """Create a vlan on the port. - """ - # Prameters check. - if (port is None) or (vlan is None): - raise ForwardError('Specify the `port` parameter') - info = {"status": False, - "content": "", - "errLog": ""} - try: - # switch to enable mode - tmp = self.privilegeMode() - if not tmp["status"]: - raise ForwardError(tmp['errLog']) - # else ,successed - # switch to config mode - tmp = self._configMode() - if not tmp["status"]: - raise ForwardError(tmp['errLog']) - # else ,successed - # switch to port mode - info["content"] = "" - self.shell.send("interface gigaethernet {port}\n".format(port=port)) - # Host prompt is modified - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Check the port mode - if not re.search('config.*-ge', self.prompt): - raise ForwardError('Switch to port mode is failed [%s]' % info["content"]) - # else successed. - tmp = self.execute("port link-type trunk") - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - else: - # Check the returned 'tmp['content']', which indicates failure if it contains' Failed ' - if re.search('%Failed', tmp["content"]): - raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\ - result is [%s] ' % tmp["content"]) - # else successed - tmp = self.execute("no shutdown") - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # quit port mode - self.shell.send("quit\n") - info["content"] = "" - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - self.getPrompt() - # save configuration - tmp = self._commit() - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # Verify that it is correct - tmp = self.isVlanInPort(port=port, vlan=vlan) - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the check configuration does not exist! [%s]" % tmp["errLog"]) - else: - # successed - info["content"] = "successed" - info["status"] = True - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - return info - - def isTrunkInInterface(self, port=None, vlan=None): - """Check the relationship between interface and turnk. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # Prameters check. - if (vlan is None) or (port is None): - raise ForwardError('Specify the `vlan` and `port` parameters') - while True: - # Execute command. - info = self.execute("show run") - if not info["status"]: - raise ForwardError(info["errLog"]) - try: - # Keyword search. - tmp = re.search("interface eth-trunk {port}[\r\n]+ mode .*[\r\n]+ por\ - t .*[\r\n]+ port .* vlan .*{vlan}".format(port=port, vlan=vlan), info['content']) - if tmp: - # Exists. - info["status"] = True - break - elif re.search('Command is in use by', info["content"]): - # Rechecking... - continue - else: - info["errLog"] = info['errLog'] - break - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - break - return info - - def trunkOpenVlan(self, port=None, vlan=None): - """Create a vlan on turnk. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # Parameters check. - if (vlan is None) or (port is None): - raise ForwardError('Specify the `vlan` and `port` parameters') - try: - # switch to enable mode - tmp = self.privilegeMode() - if not tmp["status"]: - raise ForwardError(tmp['errLog']) - # else ,successed - # switch to config mode - tmp = self._configMode() - if not tmp["status"]: - raise ForwardError(tmp['errLog']) - # else ,successed - # switch to port mode - self.shell.send("interface eth-trunk {port}\n".format(port=port)) - # Host prompt is modified - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # release host prompt - self.getPrompt() - # Keyword search. - if not re.search("config.*-eth.*-trunk.*-{port}".format(port=port), self.prompt): - raise ForwardError('[trunkOpenVlan] Switch to port mode is failed [%s]' % info["content"]) - # Execute command. - tmp = self.execute("port trunk allow-pass vlan {vlan}".format(vlan=vlan)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - else: - # Check the returned 'tmp['content']', which indicates failure if it contains' Failed ' - if re.search('%Failed', tmp["content"]): - raise ForwardError('Execute the command "port trunk allow-pass vlan" is failed ,\ - result is [%s] ' % tmp["content"]) - # quit port mode - self.shell.send("quit\n") - info["content"] = "" - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # save configuration - self.getPrompt() - # Save the configuration. - tmp = self._commit() - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # Verify that it is correct - tmp = self.isTrunkInInterface(port=port, vlan=vlan) - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the check configuration does not exist! [%s]" % tmp['errLog']) - info["status"] = True - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - return info + pass diff --git a/lib/forward/devclass/s9312.py b/lib/forward/devclass/s9312.py index a1b9d19..66a1217 100644 --- a/lib/forward/devclass/s9312.py +++ b/lib/forward/devclass/s9312.py @@ -14,272 +14,4 @@ class S9312(BASEHUAWEI): """This is a manufacturer of huawei, so it is integrated with BASEHUAWEI library. """ - def isVlan(self, vlan): - """Check if the Vlan exists. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # switch to enable mode. - tmp = self.privilegeMode() - if not tmp: - raise ForwardError(tmp["errLog"]) - tmp = self.execute("display vlan {vlan}".format(vlan=vlan)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # If the above fails, exit immediately - try: - if re.search("Error: The VLAN does not exist", tmp["content"]): - # vlan not is exitsts - info["status"] = False - else: - # vlan is exists - info["status"] = True - except Exception, e: - info["status"] = False - info["errLog"] = str(e) - return info - - def createVlan(self, vlan=None, ascription=None): - """Create a Vlan. - """ - info = {"status": False, - "content": "", - "errLog": ""} - if (vlan is None) or (ascription is None): - raise ForwardError("You must specify the `vlan` and `ascription` parameters") - """Warning: that vlan should be checked - by the 'self.isvlan(vlan) method - before setting up the vlan""" - # swith to config mode - info = self._configMode() - if not info["status"]: - raise ForwardError(info["errLog"]) - try: - # enter vlan - info["content"] = "" - self.shell.send("vlan {vlan}\n".format(vlan=vlan)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get host prompt - self.getPrompt() - if not re.search('.*-vlan', self.prompt): - raise ForwardError("Failed to enter vlan mode,command:vlan {vlan}".format(vlan=vlan)) - # set host's ascription - info["content"] = "" - # Send command. - self.shell.send("name {ascription}\n".format(ascription=ascription)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get host prompt. - self.getPrompt() - # save the configuration. - tmp = self._commit() - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the save configuration failed! [{info}]".format(info=info["content"])) - else: - if not self.isVlan(vlan)["status"]: - # check vlan - raise ForwardError("Vlan has been set and has been saved, but the final\ - check found no configuration, so failed.info:[%s]" % tmp["content"]) - else: - # create successed. exit config mode - info["status"] = True - except Exception, e: - info["status"] = False - info["errLog"] = str(e) - return info - - def isTrunkInInterface(self, port=None, vlan=None): - """Check the relationship between interface and turnk. - """ - info = {"status": False, - "content": "", - "errLog": ""} - if (vlan is None) or (port is None): - raise ForwardError('Specify the `vlan` and `port` parameters') - # switch to enable mode - tmp = self.privilegeMode() - if not tmp["status"]: - raise ForwardError(tmp['errLog']) - # else ,successed - while True: - tmp = self.execute("display current-configuration interface Eth-Trunk") - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - if re.search("Command is in use by", tmp["content"]): - # Recheck - continue - # Keyword search. - data = re.search("#[\r\n]+(interface Eth-Trunk{port}[\r\n]+[\s\S]*?)#".format(port=port), tmp["content"]) - if not data: - # No configuration found - raise ForwardError("Not found port(port) info".format(port=port)) - try: - if re.search("port trunk allow-pass vlan .*{vlan}".format(vlan=vlan), data.group(1)): - # found it. - info["status"] = True - else: - info["status"] = False - info["errLog"] = tmp["content"] - break - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - break - return info - - def trunkOpenVlan(self, port=None, vlan=None): - """Create a vlan on turnk. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # Parameter check. - if (vlan is None) or (port is None): - raise ForwardError('Specify the `vlan` and `port` parameters') - # get parameter - tmp = self.execute("display cur interface Eth-Trunk {port}".format(port=port)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # search parameter - data = re.search("#[\r\n]+(interface Eth-Trunk{port}[\r\n]+[\s\S]*?)#".format(port=port), tmp["content"]) - if not data: - raise ForwardError("Not found port(port) [{info}]".format(port=port, info=tmp["content"])) - else: - # Keyword search. - data = re.search("(port trunk allow-pass vlan.*)", data.group(1)) - if not data: - raise ForwardError("`Port turnk allow-pass vlan ...` is not found") - else: - # remove the end '\n' and '\r' - cmd = "{parameter} {vlan}".format(parameter=data.group(1).strip("\r\n"), vlan=vlan) - # switch to config mode - tmp = self._configMode() - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - try: - # switch to port mode - info["content"] = "" - # Send command. - self.shell.send("interface Eth-Trunk {port}\n".format(port=port)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get new host prompt. - self.getPrompt() - # Keyword search. - if not re.search('Trunk{port}'.format(port=port), self.prompt): - raise ForwardError("Failed to enter port mode,command:interface \ -Eth-Trunk {port} [{info}]".format(port=port, info=info["content"])) - # set vlan - info["content"] = "" - self.shell.send("{cmd}\n".format(cmd=cmd)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get new host prompt. - self.getPrompt() - # save configuration - tmp = self._commit() - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the save configuration failed! [{info}]".format(info=info["content"])) - # check configuration - tmp = self.isTrunkInInterface(port=port, vlan=vlan) - if not tmp["status"]: - raise ForwardError("Vlan has been set and has been saved, but the final\ - check found no configuration, so failed.info:[%s]" % tmp["errLog"]) - else: - info["status"] = True - except Exception, e: - info["errLog"] = str(e) - info["status"] = False - return info - - def isGateway(self, vlan): - """Check that the gateway exists. - """ - info = {"status": False, - "content": "", - "errLog": ""} - # switch to enable mode. - tmp = self.privilegeMode() - if not tmp: - raise ForwardError(tmp["errLog"]) - # Execute command. - tmp = self.execute("display current-configuration interface Vlanif {vlan}".format(vlan=vlan)) - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - # If the above fails, exit immediately - try: - if re.search("Error: Wrong parameter found at", tmp["content"]): - info["status"] = False - else: - info["status"] = True - except Exception, e: - info["status"] = False - info["errLog"] = str(e) - return info - - def setGateway(self, vlan=None, ascription=None, ip=None): - """Create a gateway - """ - info = {"status": False, - "content": "", - "errLog": ""} - # Parameters check. - if (vlan is None) or (ascription is None) or (ip is None): - raise ForwardError("You must specify `vlan` and `ascription` and `ip` parameters") - # Reset gateway ip address - ip = re.sub('[0-9]+$', '254', ip) - # switch to config mode - tmp = self._configMode() - if not tmp["status"]: - raise ForwardError(tmp["errLog"]) - try: - # switch to vlanif mode - info["content"] = "" - # Send command. - self.shell.send("interface Vlanif {vlan}\n".format(vlan=vlan)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get new host prompt. - self.getPrompt() - if not re.search('Vlanif', self.prompt): - raise ForwardError("Failed to enter Vlanif mode,command:port Vlanif {vlan}".format(vlan=vlan)) - # set ascription - info["content"] = "" - self.shell.send("description {ascription}\n".format(ascription=ascription)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Get new host prompt. - self.getPrompt() - # set ip - info["content"] = "" - # Send command. - self.shell.send("ip address {ip} 255.255.255.0\n".format(ip=ip)) - while not re.search(self.basePrompt, info['content'].split('\n')[-1]): - info['content'] += self.shell.recv(1024) - # Check - if re.search("Error: The specified IP address is invalid", info["content"]): - raise ForwardError("Error: The specified IP address is invalid,IP should be a network segment") - # Get new host prompt. - self.getPrompt() - # save the configuration - tmp = self._commit() - if not tmp["status"]: - raise ForwardError("The configuration command has been executed,\ - but the save configuration failed! [{info}]".format(info=info["content"])) - else: - # Check that the gateway configuration exists. - if not self.isGateway(vlan)["status"]: - # check vlan - raise ForwardError("Gateway has been set and has been saved, but the final\ - check found no configuration, so failed.info:[%s]" % tmp["content"]) - else: - # create successed. exit config mode - info["status"] = True - except Exception, e: - info["status"] = False - info["errLog"] = str(e) - return info + pass diff --git a/lib/forward/devclass/usg1000.py b/lib/forward/devclass/usg1000.py index 3d4ce7c..2febe3e 100644 --- a/lib/forward/devclass/usg1000.py +++ b/lib/forward/devclass/usg1000.py @@ -14,50 +14,6 @@ class USG1000(BASEVENUSTECH): """This is a manufacturer of venustech, so it is integrated with BASEVENUSTECH library. """ - def privilegeMode(self): - """Used to switch from normal mode to privileged mode for command line mode. - Does not apply to other modes to switch to privileged mode. - """ - # Set command. - cmd = 'enable' - # Flag privilege mode is False. - self.isPrivilegeMode = False - data = {"status": False, - "content": "", - "errLog": ""} - # Clean buffer. - self.cleanBuffer() - self.channel.write("%s\n" % (cmd)) - # Get result. - data = self._recv(self.basePrompt) - if data['status']: - # Flag privilege mode is True. - self.isPrivilegeMode = True - # Get host prompt. - self.getPrompt() - return data - - def _configMode(self, cmd='conf term'): - """Used to switch from privileged mode to config mode for command line mode. - Does not apply to other modes to switch to config mode. - """ - # Flag config mode is False. - self.isConfigMode = False - data = {"status": False, - "content": "", - "errLog": ""} - # Clean buffer. - self.cleanBuffer() - self.channel.write("%s\n" % (cmd)) - # Get result. - data = self._recv(self.basePrompt) - if data['status']: - # Flag config mode is True. - self.isConfigMode = True - # Get host prompt. - self.getPrompt() - return data - def _recv(self, _prompt): # Gets the return message after the command is executed. data = {"status": False, @@ -76,144 +32,3 @@ def _recv(self, _prompt): except ForwardError, e: data['errLog'] = str(e) return data - - def _exitConfigMode(self): - """Exit from configuration mode to privileged mode. - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # Check config mode status. - if self.isConfigMode: - # Check current status - self.channel.write("end\n") - # Get result. - data = self._recv(self.basePrompt) - if data['status']: - # Flag config mode is False. - self.isConfigMode = False - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - # Get host prompt. - self.getPrompt() - return data - - def _commit(self): - """To save the configuration information of the device, - it should be confirmed that the device is under the Config Mode before use. - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # Check config mode status. - if self.isConfigMode: - # Exit config mode. - self._exitConfigMode() - # exit config terminal mode. - self.channel.write('copy running-config startup-config\n') - # Get result. - result = self._recv(self.prompt) - """The search receives messages that contain characters - similar to "Current config" to indicate success. - """ - if re.search('Current configuration:', result['content'], flags=re.IGNORECASE): - data['status'] = True - else: - data['content'] = result['content'] - else: - raise ForwardError('Error: The current state is not configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def addUser(self, username, password, admin=False): - """Create a user on the device. - """ - # Set command. - if admin: - command = """user administrator {username} local {password} \ - authorized-table admin\n""".format(username=username, password=password) - else: - command = """user administrator {username} local {password} \ - authorized-table admsee\n""".format(username=username, password=password) - data = {"status": False, - "content": "", - "errLog": ""} - try: - # parameters check. - if not username or not password: - # Spcify a user name and password parameters here. - raise ForwardError('Please specify the username = your-username and password = your-password') - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - if self.isConfigMode: - # check terminal status - self.channel.write(command) - # adduser - data = self._recv(self.prompt) - # recv result - if not data['status']: - # break - raise ForwardError(data['errLog']) - result = data['content'] - if re.search('error|invalid|assword', result, flags=re.IGNORECASE): - # command failure - raise ForwardError(result) - # set password is successed, save the configuration. - data = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def deleteUser(self, username): - """Delete a user on the device - """ - data = {"status": False, - "content": "", - "errLog": ""} - try: - # swith to config terminal mode. - checkPermission = self._configMode() - if not checkPermission['status']: - raise ForwardError(checkPermission['errLog']) - # Check config mode status. - if self.isConfigMode: - # check terminal status - # deleteUser - self.channel.write("""no user administrator {username}\n""".format(username=username)) - # recv result - data = self._recv(self.prompt) - if not data['status']: - # break - raise ForwardError(data['errLog']) - # Get result. - result = data['content'] - # Search for keywords to determine if the command execution is successful. - if re.search('error|invalid|assword', result, flags=re.IGNORECASE): - # command failure - raise ForwardError(result) - # delete user is successed, save the configuration. - data = self._commit() - else: - raise ForwardError('Has yet to enter configuration mode') - except ForwardError, e: - data['errLog'] = str(e) - data['status'] = False - return data - - def changePassword(self, username, password): - """Modify the password for the device account. - Because the password command to modify the account on the device is consistent with the creation - of the user's command, the interface to create the account is called. - """ - return self.addUser(username=username, password=password) diff --git a/lib/forward/devclass/vlb.py b/lib/forward/devclass/vlb.py index ac702c5..19b27b7 100644 --- a/lib/forward/devclass/vlb.py +++ b/lib/forward/devclass/vlb.py @@ -16,73 +16,4 @@ class VLB(BASEBROCADE): """This is a manufacturer of brocade, so it is integrated with BASEBROCADE library. """ - def zcliMode(self): - """Execute the czli command and enter a new mode. - """ - # Flag zcli mode is False. - self.isZcliMode = False - # Set command. - cmd = "zcli\n" - # Set host prompt. - zcliPrompt = re.escape("admin@127.0.0.1 > ") - result = { - 'status': True, - 'content': '', - 'errLog': '' - } - # Clean buffer. - self.cleanBuffer() - # Login status check. - if self.isLogin: - self.shell.send(cmd) - try: - while not re.search(zcliPrompt, result["content"]): - result['content'] += self.shell.recv(1024) - # Save the host prompt before entering the zcli mode - self.oldPrompt = self.prompt - # update host prompt - self.prompt = zcliPrompt - # Flag zcli mode is True. - self.isZcliMode = True - result['status'] = True - except Exception, e: - # Error,flag zcli mode is False. - self.isZcliMode = False - result['status'] = False - result['errLog'] = '[ZCLI Error]: {info}'.format(info=str(e)) - else: - # not login - result['status'] = False - result['errLog'] = '[Execute Error]: device not login' - return result - - def exitZcli(self): - # Exit the zcli mode and return to normal mode. - cmd = "exit\n" - result = { - 'status': False, - 'content': '', - 'errLog': '' - } - # Login status check. - if self.isLogin: - if self.isZcliMode: - self.shell.send(cmd) - # Restore the host prompt - self.prompt = self.oldPrompt - try: - while not re.search(self.prompt, result["content"]): - result['content'] += self.shell.recv(1024) - # The switch mode status is False - self.isZcliMode = False - result['status'] = True - except Exception, e: - result['status'] = False - result['errLog'] = '[ZCLI Error]: {info}'.format(info=str(e)) - else: - result["errLog"] = "Error: The current state is not zcli mode" - else: - # not login - result['status'] = False - result['errLog'] = '[Execute Error]: device not login' - return result + pass diff --git a/unittests/testAdx03100.py b/unittests/testAdx03100.py index e0460d6..377029c 100644 --- a/unittests/testAdx03100.py +++ b/unittests/testAdx03100.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testAsa.py b/unittests/testAsa.py index 6778dfd..73440c6 100644 --- a/unittests/testAsa.py +++ b/unittests/testAsa.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testAsr1006.py b/unittests/testAsr1006.py index 4e2e254..5a7b1b3 100644 --- a/unittests/testAsr1006.py +++ b/unittests/testAsr1006.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseCisco.py b/unittests/testBaseCisco.py index 321199b..ff5bb28 100644 --- a/unittests/testBaseCisco.py +++ b/unittests/testBaseCisco.py @@ -23,20 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -45,22 +37,15 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASESSHV2 cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASESSHV2) - - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseHuawei.py b/unittests/testBaseHuawei.py index ade43bb..c55b254 100644 --- a/unittests/testBaseHuawei.py +++ b/unittests/testBaseHuawei.py @@ -23,20 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -45,22 +37,15 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASESSHV2 cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASESSHV2) - - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseJuniper.py b/unittests/testBaseJuniper.py index aeb84ab..fe61070 100644 --- a/unittests/testBaseJuniper.py +++ b/unittests/testBaseJuniper.py @@ -23,19 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - self.deviceClassMethod = ["_recv", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -44,12 +37,12 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1, 2, 3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASETELNET @@ -57,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASETELNET) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseLinux.py b/unittests/testBaseLinux.py index ae10b66..1585746 100644 --- a/unittests/testBaseLinux.py +++ b/unittests/testBaseLinux.py @@ -23,14 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - self.deviceClassMethod = ["addUser", - "deleteUser"] + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -39,12 +37,12 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASESSHV2 @@ -52,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASESSHV2) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testBaseRaisecom.py b/unittests/testBaseRaisecom.py index 60884f4..e0512e9 100644 --- a/unittests/testBaseRaisecom.py +++ b/unittests/testBaseRaisecom.py @@ -23,19 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - """self.deviceClassMethod = ["_recv", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"]""" + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -44,12 +37,12 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASETELNET @@ -57,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASESSHV2) - """def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testC2960.py b/unittests/testC2960.py index 2617b2d..dbb243a 100644 --- a/unittests/testC2960.py +++ b/unittests/testC2960.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC4510.py b/unittests/testC4510.py index 9fd8a5c..dc3999c 100644 --- a/unittests/testC4510.py +++ b/unittests/testC4510.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC6506.py b/unittests/testC6506.py index 1c2ff8b..0b232dd 100644 --- a/unittests/testC6506.py +++ b/unittests/testC6506.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testC6509.py b/unittests/testC6509.py index 96bd2d4..fc2d616 100644 --- a/unittests/testC6509.py +++ b/unittests/testC6509.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,4 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) + diff --git a/unittests/testE1000e.py b/unittests/testE1000e.py index f8c27e2..c4b97e1 100644 --- a/unittests/testE1000e.py +++ b/unittests/testE1000e.py @@ -29,7 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = [] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -51,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1, 2, 3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN5548.py b/unittests/testN5548.py index 07d2d6a..5976bfe 100644 --- a/unittests/testN5548.py +++ b/unittests/testN5548.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -57,10 +49,3 @@ def test_inherit_check(self): cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN5596.py b/unittests/testN5596.py index ed3830c..896aa65 100644 --- a/unittests/testN5596.py +++ b/unittests/testN5596.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7010.py b/unittests/testN7010.py index 056b8a0..c1f16f3 100644 --- a/unittests/testN7010.py +++ b/unittests/testN7010.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7018.py b/unittests/testN7018.py index f09ea9a..025b42e 100644 --- a/unittests/testN7018.py +++ b/unittests/testN7018.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7710.py b/unittests/testN7710.py index 4ee56bb..7eb23c4 100644 --- a/unittests/testN7710.py +++ b/unittests/testN7710.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -57,10 +49,3 @@ def test_inherit_check(self): cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testN7718.py b/unittests/testN7718.py index a3d891a..2a0d200 100644 --- a/unittests/testN7718.py +++ b/unittests/testN7718.py @@ -29,15 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] - def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) @@ -58,9 +49,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASECISCO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testNe40ex16.py b/unittests/testNe40ex16.py index 87bd1e1..f7a8d68 100644 --- a/unittests/testNe40ex16.py +++ b/unittests/testNe40ex16.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testNe40ex3.py b/unittests/testNe40ex3.py index 71304d7..3da7141 100644 --- a/unittests/testNe40ex3.py +++ b/unittests/testNe40ex3.py @@ -29,15 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] - def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) @@ -58,9 +49,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testR3048g.py b/unittests/testR3048g.py index e52485c..6c016e5 100644 --- a/unittests/testR3048g.py +++ b/unittests/testR3048g.py @@ -29,13 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - """self.deviceClassMethod = ["_recv", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"]""" def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -57,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASERAISECOM) - """def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testRg5510.py b/unittests/testRg5510.py index 8672d92..ca55860 100644 --- a/unittests/testRg5510.py +++ b/unittests/testRg5510.py @@ -23,13 +23,12 @@ def setUp(self): "basePrompt", "prompt", "moreFlag"] - """self.baseClassMethod = ["login", + self.baseClassMethod = ["login", "logout", "execute", "getMore", "getPrompt", - "cleanBuffer"]""" - self.deviceClassMethod = ["cleanBuffer"] + "cleanBuffer"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -38,12 +37,12 @@ def test_class_parameters(self): if not hasattr(_dev(1,2,3), parameter): raise IOError('%s not have parameter:' % (self.deviceClassName), parameter) - """def test_base_class_method(self): + def test_base_class_method(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) for method in self.baseClassMethod: if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" + raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): # Inherit from BASESSHV2 @@ -51,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASERUIJIE) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS3300.py b/unittests/testS3300.py index b17c7e1..beb0d98 100644 --- a/unittests/testS3300.py +++ b/unittests/testS3300.py @@ -45,7 +45,7 @@ def test_base_class_method(self): raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): - # Inherit from BASESSHV2 + # Inherit from BASEMAIPU cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEMAIPU) diff --git a/unittests/testS5328.py b/unittests/testS5328.py index 1e19253..e463793 100644 --- a/unittests/testS5328.py +++ b/unittests/testS5328.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS5352.py b/unittests/testS5352.py index 4780343..2b65423 100644 --- a/unittests/testS5352.py +++ b/unittests/testS5352.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS5800.py b/unittests/testS5800.py index c9cbc29..e9ab355 100644 --- a/unittests/testS5800.py +++ b/unittests/testS5800.py @@ -29,10 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "_configMode", - "_exitConfigMode"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -54,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEFENGHUO) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS8512.py b/unittests/testS8512.py index dac9306..d77d428 100644 --- a/unittests/testS8512.py +++ b/unittests/testS8512.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9303.py b/unittests/testS9303.py index ae3e8e6..34f9a62 100644 --- a/unittests/testS9303.py +++ b/unittests/testS9303.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9306.py b/unittests/testS9306.py index 096cbe4..f65656b 100644 --- a/unittests/testS9306.py +++ b/unittests/testS9306.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testS9312.py b/unittests/testS9312.py index f673925..836eaa2 100644 --- a/unittests/testS9312.py +++ b/unittests/testS9312.py @@ -29,15 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["privilegeMode", - "_commit", - "addUser", - "getUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] - def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) @@ -58,9 +49,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEHUAWEI) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testSr7750.py b/unittests/testSr7750.py index 611beb7..4cb518d 100644 --- a/unittests/testSr7750.py +++ b/unittests/testSr7750.py @@ -29,13 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - """self.deviceClassMethod = ["_recv", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"]""" def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -57,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEBAER) - """def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method)""" diff --git a/unittests/testSr7950.py b/unittests/testSr7950.py index 4c184ba..0d38d2f 100644 --- a/unittests/testSr7950.py +++ b/unittests/testSr7950.py @@ -45,7 +45,7 @@ def test_base_class_method(self): raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): - # Inherit from BASETELNET + # Inherit from BASEBAER cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEBAER) diff --git a/unittests/testSrx3400.py b/unittests/testSrx3400.py index 47ac1ff..ce507f7 100644 --- a/unittests/testSrx3400.py +++ b/unittests/testSrx3400.py @@ -28,13 +28,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["_recv", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -55,10 +48,3 @@ def test_inherit_check(self): cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEJUNIPER) - - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testUsg1000.py b/unittests/testUsg1000.py index 4c28a63..74fc393 100644 --- a/unittests/testUsg1000.py +++ b/unittests/testUsg1000.py @@ -29,14 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["_recv", - "privilegeMode", - "_commit", - "addUser", - "_configMode", - "_exitConfigMode", - "changePassword", - "deleteUser"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), @@ -58,9 +50,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEVENUSTECH) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1, 2, 3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testVlb.py b/unittests/testVlb.py index 8dd91a0..18ac5b4 100644 --- a/unittests/testVlb.py +++ b/unittests/testVlb.py @@ -29,8 +29,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.baseClassMethod = ["zcliMode", - "exitZcli"] def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), diff --git a/unittests/testVyoslinux.py b/unittests/testVyoslinux.py index 226ee58..a2572a5 100644 --- a/unittests/testVyoslinux.py +++ b/unittests/testVyoslinux.py @@ -28,8 +28,6 @@ def setUp(self): "getMore", "getPrompt", "cleanBuffer"] - self.deviceClassMethod = ["execute"] - def test_class_parameters(self): _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) @@ -50,9 +48,3 @@ def test_inherit_check(self): self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BCLINUX7) - def test_device_class_method(self): - _dev = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), - self.deviceClassName.upper()) - for method in self.deviceClassMethod: - if not hasattr(_dev(1,2,3), method): - raise IOError('%s not have parameter:' % (self.deviceClassName), method) diff --git a/unittests/testZx5952.py b/unittests/testZx5952.py index 76e6cf0..ba0d40d 100644 --- a/unittests/testZx5952.py +++ b/unittests/testZx5952.py @@ -45,7 +45,7 @@ def test_base_class_method(self): raise IOError('%s not have parameter:' % (self.deviceClassName), method) def test_inherit_check(self): - # Inherit from BASESSHV2 + # Inherit from BASEZTE cls = getattr(importlib.import_module('forward.devclass.{dev}'.format(dev=self.deviceClassName)), self.deviceClassName.upper()) self.assertEquals(cls.__bases__[0], BASEZTE) From ef057bc6e5b2dde4cd1f5e6a3be1c107e08e2417 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Fri, 9 Feb 2018 14:56:53 +0800 Subject: [PATCH 5/9] add travis --- .travis.yml | 10 ++++------ nosetests.ini | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index fb00e30..6e6b109 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,11 @@ python: install: - pip install -r requirements.txt + - python setup.py install + script: - - nosetests -v test/ --exe + - flake8 ./ --config=protocol/flake8 + - nosetests -c nosetests.ini notifications: email: @@ -14,10 +17,5 @@ notifications: on_success: always on_failure: always -branches: - only: - - master - - forward - after_success: - coveralls diff --git a/nosetests.ini b/nosetests.ini index 08484fc..2a9ec97 100644 --- a/nosetests.ini +++ b/nosetests.ini @@ -3,9 +3,9 @@ verbosity=3 where=unittests stop=1 with-xunit=1 -xunit-file=/apps/data/tomcat_8080/jenkins_file/forward/unittests/nosetests.xml +xunit-file=unittests/unittests/nosetests.xml with-coverage=1 cover-package=lib/forward cover-xml=1 -cover-xml-file=/apps/data/tomcat_8080/jenkins_file/forward/unittests/coverage.xml +cover-xml-file=unittests/unittests/coverage.xml exe=1 From 45fd7a2127fc46c4d83f54c71b1c7081658a10f5 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Fri, 9 Feb 2018 15:01:43 +0800 Subject: [PATCH 6/9] update requirements --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 6a9cba6..2dfe1f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ flake8==2.4.1 mock==2.0.0 paramiko==1.16.0 +pexpect>=4.2.0 From 20a696067ceed11d01421af9db748d86a438b213 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Fri, 9 Feb 2018 15:09:14 +0800 Subject: [PATCH 7/9] update nosetests --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6e6b109..853f980 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ install: script: - flake8 ./ --config=protocol/flake8 - - nosetests -c nosetests.ini + - nosetests -v --with-coverage --cover-package=lib/forward notifications: email: From f7e1f5aab3ced97f12a8a136e350b4cdab5eb057 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Fri, 9 Feb 2018 15:35:53 +0800 Subject: [PATCH 8/9] hi blank --- .coveralls.yml | 2 ++ README.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 .coveralls.yml diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000..0fe9728 --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,2 @@ +service_name: travis-pro +repo_token: e0vlxNxhi7UEjj1KjKbz7BSl7x2YADO6j diff --git a/README.md b/README.md index 436a0b1..7704356 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Forward - [![Build Status](http://192.168.182.52:8080/jenkins/job/Forward/job/forward.4.test.after/badge/icon)](http://192.168.182.52:8080/jenkins/job/Forward/job/forward.4.test.after/) + [![Build Status](https://travis-ci.org/tecstack/forward.svg?branch=master)](https://travis-ci.org/tecstack/forward) --- From 6ff45a2064023aecfce8533e6b6124efce0e5013 Mon Sep 17 00:00:00 2001 From: Azrael <13802880354@139.com> Date: Fri, 9 Feb 2018 15:39:10 +0800 Subject: [PATCH 9/9] no message --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7704356..ecdc1dd 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # Forward [![Build Status](https://travis-ci.org/tecstack/forward.svg?branch=master)](https://travis-ci.org/tecstack/forward) + [![Download Status](https://img.shields.io/badge/download-1024%2Fmonth-green.svg)](https://github.com/tecstack/forward) ---