python netmiko实现cisco网络设备配置备份

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python netmiko实现cisco网络设备配置备份相关的知识,希望对你有一定的参考价值。

import time
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException
import sys
import getpass
from datetime import datetime
import os

def NetworkDevice(username,password,iplist,enablepass):
    rt = {
        ‘device_type‘:‘cisco_ios‘,
        ‘username‘:username,
        ‘password‘:password,
        ‘ip‘: iplist,
        ‘secret‘:enablepass
    }
    print(‘-‘ * 50)
    print(u‘[+] connecting to network device {0}...‘.format(iplist))
    net_connect = ConnectHandler(**rt)
    net_connect.enable()

    hostname = net_connect.find_prompt().replace("#", "")
    print (u‘[+] hostname:{0}‘.format(hostname))

    timestr = time.strftime(‘%Y-%m-%d-%H-%M-%S‘,time.localtime(time.time()))
    cmd = ‘show running‘
    filename = (u‘{0}_{1}_{2}.txt‘.format(iplist,cmd,timestr))
    filepath = r‘C:
etpy5pyresult/‘
    if os.path.exists(filepath):
        message = ‘OK,the  "%s" dir exists.‘
    else:
        message =  "Now, I will create the %s"
        os.makedirs(filepath)
    save = open(filepath + filename,‘w‘)
    print(u‘[+] executing {0} command‘.format(cmd))
    output = net_connect.send_command(cmd)
    time.sleep(2)
    save.write(output)
    print(u‘[+] {0} command executed,result was saved at {1}!‘.format(cmd,filename))
    save.close()
    net_connect.disconnect()

if __name__ == ‘__main__‘:
    print "[+] The Program is running......."
    username = raw_input(‘Username:‘)
    password = getpass.getpass()
    enablepass = raw_input(‘enable:‘)
    filepath2 = r‘C:
etpy\‘
    if os.path.exists(filepath2):
        message = ‘OK,the  "%s" file exists.‘
    else:
        message =  "Now, I will create the %s"
        os.makedirs(filepath2)
    for ips in open(r‘C:
etpyiplist.txt‘,‘r‘):
        start_time = datetime.now()
        iplist = ips.replace(‘
‘, ‘‘)
        try:
            NetworkDevice(username,password,iplist,enablepass)
        except (EOFError, NetMikoTimeoutException):
            print (‘Can not connect to Device‘)
        except (EOFError, NetMikoAuthenticationException):
            print (‘username/password wrong!‘)
        except (ValueError,NetMikoAuthenticationException):
            print (‘enable password wrong!‘)

        print "Time elapsed: {0}
".format(datetime.now() - start_time)
        time.sleep(2)

技术分享图片
技术分享图片

https://blog.csdn.net/u012703479/article/details/79837161

以上是关于python netmiko实现cisco网络设备配置备份的主要内容,如果未能解决你的问题,请参考以下文章

Python与Cisco的事儿之四

Python与Cisco 的事儿

Python与Cisco 的事儿之二

Python与Cisco的事儿之五

python自动获取cisco配置信息

netmiko初窥