写个跟交换机相关的python脚本,利用pxssh自动向交换机上刷限速模板。
pxssh是从pexpect模块导入而来,pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块,它可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。
首先你的交换机需要支持ssh登陆。
限速模板样式如下:
1
2
3
4
5
6
7
8
9
|
policy-map 5m
class qos
police rate 5 mbps
conform-action transmit
!
!
class class-default
!
end-policy-map
|
开始前先安装pexpect:
利用交换机ssh登陆的方式,执行脚本,脚本如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
$ cat router_addXianSu.py
#!/usr/bin/env python
from pexpect import pxssh
hostname = '10.10.10.1'
username = 'admin'
password = 'mypassword'
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***********'
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()
|
以下是从开源社区里找的一个pxssh的例子代码,简单直观,供参考:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import pxssh
import getpass
try :
s = pxssh.pxssh()
hostname = raw_input ( 'hostname: ' )
username = raw_input ( 'username: ' )
password = getpass.getpass( 'password: ' )
s.login (hostname, username, password, original_prompt = '[$#>]' )
s.sendline ( 'uptime' )
s.prompt()
print s.before
s.sendline ( 'ls -l' )
s.prompt()
print s.before
s.logout()
except pxssh.ExceptionPxssh, e:
print "pxssh failed on login."
print str (e)
|
相关链接:
https://github.com/pexpect/pexpect
http://www.oschina.net/question/12_7583?fromerr=1oyKdQ4w
另外python自带telnet的模块telnetlib,相关资料:
https://docs.python.org/2/library/telnetlib.html
本文转自Jx战壕 51CTO博客,原文链接:http://blog.51cto.com/xujpxm/1737501,如需转载请自行联系原作者