此应用主要是通过netmiko模块,很强大可以支持很多类型交换机:
安装netmiko模块:
pip install netmiko==0.2.3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date: 2019/4/23
# @Created by Kelvin
from netmiko import ConnectHandler
import time
import os
def Cisco(ip):
"思科交换机配置导出函数"
cisco_881 = {
'device_type': 'cisco_ios',
'ip': ip,
'username': 'admin',
'password': 'wfweb2kd',
'port': 22, # optional, defaults to 22
'secret': 'c#andphp', # optional, defaults to ''
'verbose': False, # optional, defaults to False
}
print u'正在连接交换机:%s\n' % (ip)
net_connect = ConnectHandler(**cisco_881)
net_connect.enable()
commands = [
'show run',
]
timestr = time.strftime('%Y-%m-%d', time.localtime(time.time()))
for cmd in commands:
filename = u'%s_%s_%s.text' % (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 = [
'192.168.12.24',
]
for ip in ips:
Cisco(ip)
# 通过系统自带rsyncd同步工具,上传文件至目标服务器
rsync = 'rsync -auv --password-file=/etc/rsyncd.passwd *.text [email protected]::webreport'
if os.system(rsync) == 0:
print u'文件上传成功!'
else:
print u'文件上传失败!'
执行:
[root@zabbix609 backupsw]# python py-netmiko-bakeup.py