写个跟交换机相关的python脚本,利用pxssh自动向交换机上刷限速模板。
pxssh是从pexpect模块导入而来,pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块,它可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。
我的交换机型号是思科的ASR9K:
RP/0/RSP0/CPU0:MYROUTER#sh version brief Thu Jan 21 16:15:44.443 UTC Cisco IOS XR Software, Version 5.1.3[Default] Copyright (c) 2015 by Cisco Systems, Inc. ROM: System Bootstrap, Version 2.04(20140424:063844) [ASR9K ROMMON], CDS-YANFA-TEST uptime is 9 weeks, 6 days, 11 hours, 16 minutes System image file is "bootflash:disk0/asr9k-os-mbi-5.1.3.sp5-1.0.0/0x100000/mbiasr9k-rp.vm" cisco ASR9K Series (P4040) processor with 8388608K bytes of memory. P4040 processor at 1500MHz, Revision 3.0 ASR-9001 Chassis
限速模板样式如下:
policy-map 5m class qos police rate 5 mbps conform-action transmit ! ! class class-default ! end-policy-map
开始前先安装pexpect:
pip install pexpect
python脚本:
$ cat router_addXianSu.py #!/usr/bin/env python # _*_ coding: utf-8 _*_ # This script is used to add router XianSu template for YanFaTest ASR9K. from pexpect import pxssh #导入模块 #import getpass hostname = '10.10.10.1' username = 'admin' password = 'mypassword' #hostname = raw_input("Please input your hostname:").strip() #username = raw_input('Please input your username:').strip() #password = getpass.getpass('Please input your password:').strip() s = pxssh.pxssh() s.login(hostname, username, password, login_timeout=5, auto_prompt_reset=False) #注意这里的几个参数 print '******* HOST %s success login!**********'%hostname print '*******router configure excute now******' s.sendline('configure terminal') s.prompt() print s.before for size in xrange(5,205,5): print '*********add XianSu MuBan now***********'#添加从5m,10m,...,200m的限速模板 cmd = 'policy-map %sm'%size print '*****%s*****'%cmd s.sendline(cmd) s.sendline('class qos') cmd = 'police rate %s mbps'%size print '*********police rate %s mbps'%cmd s.sendline(cmd) s.sendline('conform-action transmit') s.sendline('show configuration') s.prompt() print s.before s.sendline('commit') s.prompt() print s.before continue s.sendline('exit') #交换机执行完后退出 s.close() #退出,结束
相关链接:
https://github.com/pexpect/pexpect