python通过telnet(ciscolib和paramiko\netmiko)库批量备份交换机

第一种telnet - ciscolib备份交换机配置文件:

cisco库安装地址:从Github上面下载,进入安装目录:python setup.py install即可

[root@zabbix609 backupsw]# cat telnet_switch3560.py
# -*- coding: utf-8 -*-
import ciscolib
import time
import datetime

def main():
    PASSWORD="123567567"
    USERNAME="root"
    ENABLE_PWD="123456"

    t = datetime.datetime.now()
    ot = t.strftime("%Y-%m-%d")

    for ip in open('sw3560.txt').readlines():
        ip = ip.strip()

        if USERNAME != "":
            switch = ciscolib.Device(ip, PASSWORD, USERNAME, ENABLE_PWD)
        else:
            switch = ciscolib.Device(ip, PASSWORD, enable_password=ENABLE_PWD)

        try:
            switch.connect()
            print("Logged into %s,Successful" % ip)
        except ciscolib.AuthenticationError as e:
            print("Couldn't connect to %s: %s" % (ip, e.value))
            continue
        except Exception as e:
            print("Couldn't connect to %s: %s" % (ip, str(e)))
            continue

        switch.enable(ENABLE_PWD)
        switch.cmd("enable")
        switch.cmd("c#andphp\n")
        switch.cmd("copy running ftp:")
        switch.cmd("10.6.7.15")
        switch.cmd(ip + "-" + ot + "config.text")
        switch.disconnect()

if __name__ == '__main__':
    main()

第二种通过SSH加密验证登录备份交换机:paramiko库,基于python 2.7 -->pip install paramiko

[root@zabbix609 backupsw]# ls
py-netmiko-bakeup.py  ssh_switch2960.py  sw2960.txt  sw3560.txt  telnet_switch3560.py
[root@zabbix609 backupsw]# cat ssh_switch2960.py
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import paramiko
import time
import getpass
import datetime

username = raw_input("Username:")
password = getpass.getpass("Password:")
t = datetime.datetime.now()
ot = t.strftime("%Y-%m-%d")

f = open("sw2960.txt","r")
for line in f.readlines():
        ip = line.strip()
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip,username=username,password=password)
        print "成功登录到Cisco交换机 ", ip
        print t
        command = ssh_client.invoke_shell()
        command.send("enable\n")
        command.send("c#andphp\n")
        command.send("copy flash:config.text ftp:\n")
        command.send("10.6.7.15\n")
        command.send (ip + "-" + ot + "config.text\n")
        time.sleep(1)
        output = command.recv(65535)
        print output
f.close()
ssh_client.close

第三种:通过netmiko来管理,这个库非常强大当然也可以管理其它类型交换机

[root@zabbix609 backupsw]# cat py-netmiko-bakeup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: 2019/11/27
# 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': '1235325',
        'port': 22,  # optional, defaults to 22
        'secret': '134234234',  # 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 = [
        '10.6.110.1',
        '10.6.110.2',
        '10.6.110.3',
        '10.6.110.5',
        '10.6.110.6',
        '10.6.110.16',
    ]
    for ip in ips:
        Cisco(ip)
    # 上传文件至目标服务器
    rsync = 'rsync -auv --password-file=/etc/rsyncd.passwd *.text [email protected]::webreport'
    if os.system(rsync) == 0:
        print u'文件上传成功!'
    else:
        print u'文件上传失败!'

 

你可能感兴趣的:(交换机,Python)