使用netmiko模块连接H3C设备(闭坑——H3C设备的分屏显示)

最近一直在测试Python中通过ssh协议连接huawei、h3c等网络设备的paramiko和netmiko模块。为什么选用这两个自己去网上找答案。
有关paramiko模块连接网络设备的例子和遇到的问题,烦请参考:https://blog.51cto.com/chier11/2116155
本文只介绍使用netmiko模块连接H3C网络设备,并成功闭坑:h3c分屏显示的问题。
发发牢骚:netmiko连接huawei设备的时候,在netmiko模块中会自动去掉分屏显示功能,意思就是说所有大量信息全部显示出来,举例:display interface brief,查看400多端口的信息,系统会分屏显示,但是在netmiko的huawei模块中默认设置了取消分屏显示的指令,如下:screen-length 0 temporary(华为取消分屏显示的命令)


from __future__ import print_function
from __future__ import unicode_literals
import time
import re
from netmiko.cisco_base_connection import CiscoBaseConnection
from netmiko.ssh_exception import NetMikoAuthenticationException
from netmiko import log

class HuaweiBase(CiscoBaseConnection):
    def session_preparation(self):
        """Prepare the session after the connection has been established."""
        self._test_channel_read()
        self.set_base_prompt()
        self.disable_paging(command="screen-length 0 temporary")
        # Clear the read buffer
        time.sleep(0.3 * self.global_delay_factor)
        self.clear_buffer()

    def config_mode(self, config_command="system-view"):
        """Enter configuration mode."""
return super(HuaweiBase, self).config_mode(config_command=config_command)

这里大概猜测了下,为什么在netmiko模块在huawei的连接中有取消分屏显示功能的命令,而H3C设备没有呢,经过和厂家沟通发现,华为设备的取消分屏显示功能可以针对用户设置,而且是临时。举个例子:一个user用户登录华为设备后执行取消分屏显示命令后对设备中其他用户没影响(其他用户还是分屏显示),当user用户推出来的时候分屏显示功能就自动恢复,就像定义了 进入自己家目录的环境一样方便强大。而H3C网络设备的分屏显示针对的是全局设备,而且并不是进入退出环境那样临时性生效一样。那么如何解决这种坑呢,经过多次网上查找和多次测试,终于完美实现一次性显示完整的输出大量信息
if "---- More ----" in outp:
outp += conn1.send_command_timing(
' \n', strip_prompt=False, strip_command=False, normalize=False
) ###遇到more,就多输入几次个空格,normalize=False表示不取消命令前后空格
代码如下,


from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException

def Get_CRC():
    try:
        pynet1 = {
        'device_type': "hp_comware",
        'ip': "10.10.10.10",
        'username': "CTyunuser",
        'password': "P@ssw0rd6900",
        }
        conn1 = ConnectHandler(**pynet1)
        cmd='display counters inbound interface '
        #cmd = 'display interface brief \n'
        outp=conn1.send_command_timing(cmd)
        if "---- More ----" in outp:
            outp += conn1.send_command_timing(
                '            \n', strip_prompt=False, strip_command=False, normalize=False
            )      *###遇到more,就多输入几次个空格,normalize=False表示不取消命令前后空格*。
        outp1 = outp.split("\n")
        print (outp1)

    except (EOFError,NetMikoTimeoutException):
        print('Can not connect to Device')
    except (EOFError, NetMikoAuthenticationException):
        print('username/password wrong!')
    except (ValueError, NetMikoAuthenticationException):
        print('enable password wrong!')

if __name__=="__main__":
     Get_CRC()

以上是在实际中对华为和华三厂家的命令使用中的区别总结。如有不妥之处烦请大家指正。

猜你喜欢

转载自blog.51cto.com/chier11/2398299