将ssh和telnet会话自动化到网络设备
clijocke的Python项目详细描述
network engineers的无痛屏幕抓取-使用python控制您的网络
用法
本质上,这是一个简单的pexpect包装器。标准用法:
importtimefromclijockey.traitsimportTraitTable,CUnicode,CUnicodeRegexfromclijockey.traitsimportCMacAddressCisco,CIPv4AddressStrfromclijockey.utilimportRotatingTOMLLogfromclijockey.utilimportAccountfromclijockey.libimportCLIMachine# TextFSM template...TEMPLATE="""Value INTF (\S+)\nValue IPADDR (\S+)\nValue STATUS (up|down|administratively down)\nValue PROTO (up|down)\n\nStart\n ^${INTF}\s+${IPADDR}\s+\w+\s+\w+\s+${STATUS}\s+${PROTO} -> Record"""# Interfaces() is used to map TextFSM template values to the TOML LogclassInterfaces(TraitTable):intf=CUnicode()# See the traitlets documentation for CUnicode usageaddr=CUnicode()status=CUnicode()# Usage of CUnicodeRegex illustrated below... it errors if no matchproto=CUnicodeRegex(r'down|up')_map=('intf','addr','status','proto')# TextFSM field order# Create a log named rviews_intfs, which automatically rotates at midnight# category must be unique per logging filelog=RotatingTOMLLog('rviews_intfs',category='route-views')## Define a tuple of username and password pairs here...## The first is an expected failure to illustrate how it worksaccts=(Account('itsa-mistake',''),Account('rviews','secret2'),)## You can optionally disable auto-enable mode if you like...conn=CLIMachine('route-views.routeviews.org',accts,auto_priv_mode=False,log_screen=True,debug=False,command_timeout=5,login_attempts=3)conn.execute('term len 0',wait=0.5)# Wait 0.5 seconds after the cmd# regex is a tuple with another prompt stringconn.execute('show version',regex=('test>',))conn.execute('show users',timeout=60)# 'show users' outputs slowly...## Get the result of the 'show users' command...user_output=conn.responsematching_regex=conn.matching_prompt_regex## Automatically parse with TextFSM and log to a TOML logforiiinrange(0,5):intf_list=conn.execute('show ip int brief',template=TEMPLATE)forvalsinintf_list:## NOTE: info must be a dictionary to be parsed by .write_table_list()info=dict(Interfaces(vals))# <---- This is the info table## Write a timestamped list of tables named 'rview_intf' to the loglog.write_table_list(table='rview_intf',info=info,timestamp=True)time.sleep(1)conn.logout()
安装
使用pip安装(-u自动升级到最新版本)
pip install -U clijockey
为什么
简短回答:
因为这样的库应该“正常工作”,不管你在屏幕上刮什么。
更长的答案:
我一直在写网络截屏脚本的乐趣和利润超过 过去二十年来,在这个过程中,我积累了一些关于 事情应该做。
在撰写本文时,有几个类似的python命令/响应 库…有些甚至有一个特定于供应商的插件电池。显而易见的 问题是为什么我认为需要另一个图书馆。难道我只是对 not invented here综合征?
我希望不会。
一。具有特定于供应商的cli驱动程序的流行python库是 毫无意义的挑剔,有时甚至不适用于 那个小贩。所有的功劳都归功于那些孜孜不倦的灵魂,他们书写并维护着它们,但是 我厌倦了在图书馆里胡思乱想,我只想把事情办好。
2.许多现有的库都会缓慢地使用SSH会话,因为它们使用 paramiko(纯python ssh)
三。单元测试应该是独立的,不需要真正的网络来测试它们 打开。在测试屏幕抓取时,这并不容易,但是 Samuel Abel’sexscript tests是一个很好的例子 这口井。我希望能在clijockey