利用Python通过telnet、ssh连接交换机、路由器等设备配置备份 第2版(粗略版)...

数据库设计:(主要存储设备信息如IP等)

164259_FKDq_1168635.jpg

164303_oke6_1168635.jpg

164307_bfcc_1168635.jpg

164312_W5zw_1168635.jpg

164316_sqnJ_1168635.jpg

164319_jVQb_1168635.jpg

164321_81KZ_1168635.jpg

164332_Xgfm_1168635.jpg

164334_Up9U_1168635.jpg

164336_yd5O_1168635.jpg

164338_4aKT_1168635.jpg

164341_yOoY_1168635.jpg164620_pFZx_1168635.jpg

TFTP服务器准备:

165444_hwNR_1168635.jpg


备份连接设备备份配置的代码:

import sys
import telnetlib
import time
import pymysql
import os
import shutil
import logging
import paramiko

def sqlconnect():
    cur_host = conn.cursor()
    sql_host = "select host_name,host_ip,area_id,host_model_id,host_protocol from hosts"
    n_host = cur_host.execute(sql_host)
    for row_host in cur_host.fetchall():
        host_name = row_host[0]
        host_ip = row_host[1]
        host_area = row_host[2]
        host_model_id = row_host[3]
        host_protocol = row_host[4]
        if host_protocol == 1:
            backup_telnet(host_name, host_ip, host_area, host_model_id)
        elif host_protocol == 2:
            backup_ssh(host_name, host_ip, host_area, host_model_id)
            
def backup_telnet(b_name, b_ip, b_area, b_model):
    if 2 <= b_model <= 3 or b_model == 5 or b_model == 47:
        backup_telnet_h3_1(b_name, b_ip, b_area)
    elif b_model == 4 or 7 <= b_model <= 8:
        backup_telnet_h3_2(b_name, b_ip, b_area)
    elif 10 <= b_model <= 14 or b_model == 17 or 48 <= b_model <=50:
        backup_telnet_hw_1(b_name, b_ip, b_area)
    elif b_model == 6 or 15 <= b_model <= 16:
        backup_telnet_hw_2(b_name, b_ip, b_area)
    elif 19 <= b_model <= 38 or 40 <= b_model <= 44 or b_model == 46:
        backup_telnet_rg_1(b_name, b_ip, b_area)
    elif b_model == 18:
        backup_telnet_rg_2(b_name, b_ip, b_area)
    elif b_model == 39:
        backup_telnet_rg_3(b_name, b_ip, b_area)
    elif b_model == 1:
        backup_telnet_jp_1(b_name, b_ip, b_area)
    elif b_model ==9 :
        backup_telnet_at_1(b_name, b_ip, b_area)
    else:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
        
def backup_ssh(b_name, b_ip, b_area, b_model): 
    if 2 <= b_model <= 3 or b_model == 5 or b_model == 47:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif b_model == 4 or 7 <= b_model <= 8:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif 10 <= b_model <= 14 or b_model == 17 or 48 <= b_model <=50:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif b_model == 6 or 15 <= b_model <= 16:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif 19 <= b_model <= 38 or 40 <= b_model <= 44 or b_model == 46:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif b_model == 18:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif b_model == 39:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    elif b_model == 1:
        backup_ssh_jp_1(b_name, b_ip, b_area)
    elif b_model ==9 :
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
    else:
        logging.warning(b_name + "(" + b_ip + ") 暂不支持该设备!")
        
def backup_telnet_jp_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['configure'] = b"configure"
    host['show_config'] =  b"show | display set"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"login:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['configure']+b"\n")
        tn.read_until(b"#", timeout=2)
        tn.write(host['show_config']+b"\n                                ")
        time.sleep(6)
        read_show = tn.read_very_eager()
        if str(read_show).index("[edit]")>0:
            read_file_temp = open(tftp_dir + 'config-tmp.txt','wb')
            read_file_temp.write(read_show)
            read_file_temp.close()
            replace_1 = b"---(more)---"
            read_file_input = open(tftp_dir + 'config-tmp.txt','rb')
            read_file_output = open(tftp_dir + 'config.txt','wb')
            for read_line in read_file_input:
                read_file_output.write((read_line.replace(replace_1, b"").lstrip()))
            read_file_input.close()
            os.remove(tftp_dir + "config-tmp.txt")
            read_file_output.close()
            movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份 show | display set !")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except ValueError:
        logging.warning(name + "(" + ip + ") ValueError: substring not found 备份失败,可能是由于密码错误导致。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_ssh_jp_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['cmd'] = b"configure;show | display set"
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host['ip'], 22, host['user'], host['password'], timeout=3)
        stdin, stdout, stderr = ssh.exec_command(host['cmd'])
        read_show = stdout.read()
        ssh.close()
        if str(read_show).index("host-name")>0:
            read_file_temp = open(tftp_dir + 'config-tmp.txt','wb')
            read_file_temp.write(read_show)
            read_file_temp.close()
            replace_1 = b"---(more)---"
            read_file_input = open(tftp_dir + 'config-tmp.txt','rb')
            read_file_output = open(tftp_dir + 'config.txt','wb')
            for read_line in read_file_input:
                read_file_output.write((read_line.replace(replace_1, b"").lstrip()))
            read_file_input.close()
            os.remove(tftp_dir + "config-tmp.txt")
            read_file_output.close()
            movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份 show | display set !")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except ValueError:
        logging.warning(name + "(" + ip + ") ValueError: substring not found 备份失败,可能是由于密码错误导致。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_at_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['show_config'] =  b"show config dynamic"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"login:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['show_config']+b"\n                                ")
        time.sleep(6)
        read_show = tn.read_very_eager()
        if str(read_show).index(">")>0:
            read_file_temp = open(tftp_dir + 'config-tmp.txt','wb')
            read_file_temp.write(read_show)
            read_file_temp.close()
            replace_1 = b"---(more)---"
            read_file_input = open(tftp_dir + 'config-tmp.txt','rb')
            read_file_output = open(tftp_dir + 'config.txt','wb')
            for read_line in read_file_input:
                read_file_output.write((read_line.replace(replace_1, b"").lstrip()))
            read_file_input.close()
            os.remove(tftp_dir + "config-tmp.txt")
            read_file_output.close()
            movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份 show | display set !")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except ValueError:
        logging.warning(name + "(" + ip + ") ValueError: substring not found 备份失败,可能是由于密码错误导致。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
 
def backup_telnet_h3_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"tftp <TFTP服务器IP> put startup.cfg config.txt"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"successfully", timeout=6)
        movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份startup.cfg!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_h3_2(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"tftp <TFTP服务器IP> put config.cfg config.txt"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"successfully", timeout=6)
        movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份config.cfg!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_hw_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"tftp <TFTP服务器IP> put vrpcfg.zip config.zip"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"successfully", timeout=6)
        movefile_zip(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份config.txt!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_hw_2(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"tftp <TFTP服务器IP> put vrpcfg.cfg config.txt"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b">", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"successfully", timeout=6)
        movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份vrpcfg.cfg!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_rg_1(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"copy flash:config.text tftp://<TFTP服务器IP>/config.txt"
    host['config'] = b"configure terminal"
    host['user_config'] = b"no username heqijun"
    host['exit'] = b"exit"
    host['wr'] = b"wr"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b"#", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"length", timeout=6)
        movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份config.txt!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def backup_telnet_rg_2(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"copy flash:ap-config.text tftp://<TFTP服务器IP>/ap-config.txt"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b"#", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"length", timeout=6)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份ap-config.txt!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
    backup_telnet_rg_1(name, ip, area)
    
def backup_telnet_rg_3(name, ip, area):
    host = {}
    host['name'] = name.encode(encoding="utf-8")
    host['ip'] = ip.encode(encoding="utf-8")
    host['user'] = b"用户名"
    host['password'] = b"密码"
    host['tftp'] = b"copy flash:config.text tftp://<TFTP服务器IP>/config.txt"
    try:
        tn = telnetlib.Telnet(host['ip'])
        tn.set_debuglevel(2)
        tn.read_until(b"Username:", timeout=2)
        tn.write(host['user']+b"\n")
        tn.read_until(b"Password:", timeout=2)
        tn.write(host['password']+b"\n")
        tn.read_until(b"#", timeout=2)
        tn.write(host['tftp']+b"\n")
        tn.read_until(b"length", timeout=6)
        movefile_txt(name, ip, area)
    except TimeoutError:
        logging.warning(name + "(" + ip + ") TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。")
    except FileNotFoundError:
        logging.error(name + "(" + ip + ") FileNotFoundError: 未成功备份config.txt!")
    except ConnectionResetError:
        logging.warning(name + "(" + ip + ") ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。")
    except:
        logging.error(name + "(" + ip + ") 发生未知错误!") 
        
def movefile_zip(file_name, file_ip, file_area):
    cur_file_area = conn.cursor()
    sql_file_area = "select area_name_cn from areas where area_id=" + str(file_area)
    n_file_area = cur_file_area.execute(sql_file_area)
    for row_area in cur_file_area.fetchall():
        file_area_name = row_area[0]
    move_dir = backup_dir + file_area_name + "\\" + file_year + "\\" + file_mon + "\\" + file_mday
    if not os.path.isdir(move_dir):
        os.makedirs(move_dir)
    shutil.move(tftp_dir + "config.zip", move_dir + "\\" + file_name  + "(" + file_ip + ")_" + file_time + ".zip")
    logging.info(file_name + "(" + file_ip + "): *.zip 配置备份成功!")
def movefile_txt(file_name, file_ip, file_area):
    cur_file_area = conn.cursor()
    sql_file_area = "select area_name_cn from areas where area_id=" + str(file_area)
    n_file_area = cur_file_area.execute(sql_file_area)
    for row_area in cur_file_area.fetchall():
        file_area_name = row_area[0]
    move_dir = backup_dir + file_area_name + "\\" + file_year + "\\" + file_mon + "\\" + file_mday
    if not os.path.isdir(move_dir):
        os.makedirs(move_dir)
    shutil.move(tftp_dir + "config.txt", move_dir + "\\" + file_name  + "(" + file_ip + ")_" + file_time + ".txt")
    logging.info(file_name + "(" + file_ip + "): *.txt 配置备份成功!")
    try:
        shutil.move(tftp_dir + "ap-config.txt", move_dir + "\\" + file_name  + "(" + file_ip + ")_AP_" + file_time + ".txt")
        logging.info(file_name + "(" + file_ip + "): ap-config.text 配置备份成功!")
    except:
        print()
        
conn = pymysql.connect(host='127.0.0.1', user='数据库用户名', passwd='数据库密码', db='devices', charset='utf8')
file_year = time.strftime("%Y", time.localtime())
file_mon = time.strftime("%m", time.localtime())
file_mday = time.strftime("%d", time.localtime())
file_time = time.strftime("%Y%m%d", time.localtime())
backup_dir = os.getcwd() + "\\备份路径\\"
tftp_dir = os.getcwd() + "\\TFTP\\Root\\"
logging_dir = os.getcwd() + "\\备份路径\\备份程序执行日志"
logging_name = "log_" + file_time + ".txt"
if not os.path.isdir(logging_dir):
    os.makedirs(logging_dir)
logging.basicConfig(filename = os.path.join(logging_dir, logging_name), level = logging.INFO, filemode = "a", format = "%(asctime)s - %(levelname)s: %(message)s")  
#logging.debug("debug")
#logging.info("info")
#logging.warning("warn")
#logging.error("error")
sqlconnect()
logging.shutdown()


转载请注明原文链接:http://my.oschina.net/caiyuanbo/blog/501358

暂时没时间添加注解及详细解释说明,代码比较简单,可能有些纰漏,如果有问题可以跟我一起研究。

PS:其实是人懒不想注释&优化

QQ:384152164

E-mail:384152164@qq.com


转载于:https://my.oschina.net/caiyuanbo/blog/501358

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值