最近帮同事写一段关于导出cisco交换机的脚本,发现网上的资料不是太多,仅有的几个也有不少错误,这里分享一个python操作cisco交换机的库。
经过对网上的资料查找,发现如下几个库,吐槽一下百度搜索引擎,搜索结果太一般了,求谷歌回归。
1、ciscolib 这个库使用方便,比较简洁,但是好像官方没有收录,需要自行安装。
安装方法:
下载,解压,然后使用python setup.py install安装。
使用方法(官方文档):
import ciscolib
switch = ciscolib.Device("hostname or ip", "login password", "optional login username")
switch.connect() # Defaults to port 23
# There are some helper commands for common tasks
print(switch.get_model())
print(switch.get_ios_version())
print(switch.get_neighbors())
switch.enable("enable_password")
# Or you can throw plain commands at the switch
print(switch.cmd("show run"))
switch.cmd("reload\n")
这里有一个坑,代码里面最后一行,会使交换机重启,请使用前注释掉。
缺点,只支持telnet,不支持ssh连接
2、使用pexpect,paramiko库,交互方面存在些许不足,不是太方便。
pexpect.spawn方法在windows下并不支持,所以只能在Linux下面执行。
演示代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2017/4/5
# Created by 独自等待
# 博客 http://www.waitalone.cn/
import pexpect
def ssh_cmd(user, ip, cmd, passwd, enpass):
ssh = pexpect.spawn('ssh %[email protected]%s %s' % (user, ip, cmd))
try:
i = ssh.expect(['Password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0:
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes')
ssh.expect('Password: ')
ssh.sendline(passwd)
except pexpect.EOF:
print "EOF"
except pexpect.TIMEOUT:
print "TIMEOUT"
else:
print ssh.read()
ssh.close()
存在一个问题,某些命令需要进行enable模式,这里好像也可以用,但是我没有研究好。
paramiko库比较强大,常用来ssh交互登录,当然也是可以登录cisco交换机的,演示代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2017/4/5
# Created by 独自等待
# 博客 http://www.waitalone.cn/
import paramiko
import time
hostname = 'xx.xx.xx.xx'
port = 22
username = 'xx'
password = '[email protected]'
client = paramiko.SSHClient() # 绑定实例
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password, timeout=5)
remote_conn = client.invoke_shell()
remote_conn.send('enable\n')
time.sleep(1)
remote_conn.send('[email protected]\n')
time.sleep(1)
remote_conn.send('show run\n')
time.sleep(1)
output = remote_conn.recv(65535)
print output
由于show run得到的结果比较长,这里只能获取一部分,应该也是可以全部获取的。
3、使用netmiko库操作交换机,这里强烈推荐,支持N多设备。
安装方法: pip install netmiko
演示代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2017/4/5
# Created by 独自等待
# 博客 http://www.waitalone.cn/
# https://pynet.twb-tech.com/blog/automation/netmiko.html
from netmiko import ConnectHandler
import time
import os
def Cisco(ip):
"思科交换机配置导出函数"
cisco_881 = {
'device_type': 'cisco_ios',
'ip': ip,
'username': 'xx',
'password': '[email protected]',
'port': 22, # optional, defaults to 22
'secret': '[email protected]', # optional, defaults to ''
'verbose': False, # optional, defaults to False
}
print u'正在连接交换机:%s\n' % (ip)
net_connect = ConnectHandler(**cisco_881)
net_connect.enable()
commands = [
'show arp',
'show mac address-table',
]
timestr = time.strftime('%Y-%m-%d', time.localtime(time.time()))
for cmd in commands:
filename = u'%s_%s_%s.txt' % (ip, cmd.replace(' ', '_'), timestr)
save = open(filename, 'w')
print u'正在执行命令:' + cmd
result = net_connect.send_command(cmd)
save.write(result)
print u'命令执行完毕,结果保存于当前目录%s中!\n' % filename
net_connect.disconnect()
if __name__ == '__main__':
ips = [
'xx.xx.xx.xx',
'xx.xx.xx.xx',
]
for ip in ips:
Cisco(ip)
# 上传文件至目标服务器
rsync = 'rsync -avz --password-file=rsync.passwd *.txt [email protected]::upload'
# 列出目标服务器文件列表
# 'rsync --list-only -v [email protected]::upload'
if os.system(rsync) == 0:
print u'文件上传成功!'
else:
print u'文件上传失败!'
优点:支持telnet,ssh连接。
from www.waitalone.cn.thanks for it.