根据配置文件登录网络设备,读取配置并备份配置
可以批量备份多个网络设备

import paramiko
import os
import sys
import json
import time
import datetime

 
def ssh_get(hostname, port, username, password, command, pslists, enpass):
    # 实例化SSHClient
    sclient = paramiko.SSHClient()
    # 自动添加策略,保存服务器的主机名和密钥信息
    sclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接SSH服务端,以用户名和密码进行认证
    sclient.connect(hostname=hostname, username=username, password=password, look_for_keys=False)
    session = sclient.invoke_shell()
    # 设置会话回显超时时间
    session.settimeout(3600)
 
    # 获取登陆后的消息
    welcomeinfo = ''
    while True:
        line = session.recv(4096).decode('utf-8')
        welcomeinfo += line
        # 当有pslists回显标识的时候执行下一步
        if pslists is not None and len(pslists) > 0:
            getps = False;
            for i in pslists:
                if i in line:
                    getps = True
            if getps == True:
                break;

    # 判断是否需要输出enable密码
    if enpass != "":
        session.send('enable\n')
        session.send(enpass+'\n')
        # 获取特权后的消息
        eninfo = ''
        while True:
            line = session.recv(4096).decode('utf-8')
            eninfo += line
            # 当有pslists回显标识的时候执行下一步
            if pslists is not None and len(pslists) > 0:
                getps = False;
                for i in pslists:
                    if i in line:
                        getps = True
                if getps == True:
                    break;
 
    session.send(command+'\n')
    result = ''
    rebuff = ''
    getcha = 0
    more = ['-- More --','--More--','<--- More --->','-- more --']
    #  循环获取配置回显数据
    while True:
        bcache = session.recv(4096)
        scache = bcache.decode('utf-8')
        rebuff = rebuff+scache
        # 由于前面都是输入命令的回显,所以需要过滤掉输入的命令
        # 需要回显中出现两次命令才开始读取回显中的配置信息
        if getcha <= 1 and command in rebuff:
            getcha+=1
        if getcha == 2:
            caches = (scache.replace("\r","\n")).split("\n")
            for line in caches:
                # 过滤掉More字样的回显
                if more[0] in line or more[1] in line or more[2] in line or more[3] in line:
                    pass
                # 过滤掉空格或单独换行符或空字符的回显
                elif line == "" or line == "\n" or line.isspace():
                    pass
                else:
                    result += line+"\n"
        # 判断有More字样的时候输入空格,继续获取配置回显
        if more[0] in scache or more[1] in scache or more[2] in scache or more[3] in scache:
            session.send(" ")
            continue;
        # 当有pslists回显标识的时候结束
        if pslists is not None and len(pslists) > 0:
            getps = False;
            for i in pslists:
                if i in scache:
                    result = result.replace(i, "")
                    getps = True
            if getps == True:
                break;
    
    return result


def writeconfig(fapath,filename,content):
    date = datetime.datetime.now()
    path = fapath+"/"+date.strftime('%Y')+"/"+date.strftime('%m')+"/"+date.strftime('%d')+"/"
    if not os.path.exists(path):
        os.makedirs(path) 
    file = open(path+filename, 'w')
    file.write(content)
    file.close()

def mainfunction(path):
    file = open("config.json", "rb")
    switch = json.load(file)["switch"]
    for i in switch:
        if i["protocol"] == "ssh":
            content = ssh_get(i["hostname"],i["port"],i["username"],i["password"],i["command"],i["pslists"],i["enpass"])

        writeconfig(path,i["svname"],content)
    sys.exit(0)

mainfunction("/tmp")

Last modification:February 28th, 2021 at 02:50 pm
硬币投入口