利用ftp连接与ssh 进行交换机备份

本文介绍了一种针对不同型号交换机的配置备份方法,包括华为设备通过FTP连接备份及烽火设备通过SSH方式备份的具体实现过程。通过Python脚本自动化收集配置文件,支持多种备份类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据交换机的不同型号进行不同的连接进行交换机的文件备份,
华为的是通过ftp连接的方式进行备份,而烽火的交换机是通过ssh方式进行备份。

#!/usr/bin/python
# encoding:utf-8

'''collect config of switch
@author : wd
'''
import time
import get_ip_list
import os
import re
import sys
import socket
import paramiko
from ftplib import FTP
plugins_path = os.getenv('INSPECTOR_HOME') + '/plugins'
sys.path.append(plugins_path + '/common/')
from encrypt_util import AES_ENCRYPT
import tools
import telnetlib 
config = tools.get_file_config_from_type('install')
host_ip = config.get('dispatcher', 'tftp_server')
tftp_file_path = config.get('dispatcher', 'tftp_server_dir')
equipment_final_map = {}
def build_equipment_message(ip_list):
        ip_list_str = ''
        for ip in ip_list:
            ip_list_str = ip_list_str + "'" + ip + "',"
        ip_list_str = ip_list_str.rstrip(',')
        query_sql = "SELECT a.manage_ip,a.ssh_user,a.ssh_password,b.backup_type,b.backup_cmd,a.ftp_user,a.ftp_password,a.ftp_dir FROM data.Equipment A LEFT JOIN resource.equipment_model b ON A.model_Id = b.ID where a.manage_ip in ("+ ip_list_str+")"
        rows = tools.get_sql_select_data(query_sql)
        aes_key = '1234567812345678'
        encryptor = AES_ENCRYPT(aes_key)
        for row in rows:
            manage_ip=str(row[0])
            equipment_message_map={
                'ssh_user':str(row[1]),
                'ssh_password':(str(row[2]) if  str(row[2]) is None else encryptor.decrypt( str(row[2]))),
                'backup_type':str(row[3]).lower(),
                'backup_cmd':str(row[4]),
                'ftp_user':str(row[5]),
                'ftp_password':(str(row[2]) if  str(row[6]) is None else encryptor.decrypt( str(row[6]))),
                'ftp_dir':str(row[7])
            }
            equipment_final_map[manage_ip]=equipment_message_map
def collect_config_ftp(ip, host_ip, timestamp):
    global equipment_final_map
    file_name='startup.cfg'
    ftp_user = equipment_final_map[ip]['ftp_user']
    ftp_passwd = equipment_final_map[ip]['ftp_passwd']
    ftp_dir= equipment_final_map[ip]['ftp_dir']
    try:
        ftp = FTP()
        #ftp.set_debuglevel(2)
        ftp.connect(ip,21)
        ftp.login(ftp_user,ftp_passwd)
        ftp.cwd(ftp_dir)
        file_list =ftp.nlst()
        new_file_name = '{0}_{1}.cfg'.format(
                ip,
                timestamp
        )
        for file in file_list :
            if file == file_name:
                write_file = os.path.join(tftp_file_path, new_file_name)
                with open(write_file, "wb") as f:
                   ftp.retrbinary('RETR %s' % file_name,f.write,blocksize=1024) 
                   f.close()
                print '{0}\t{1}\t{2}'.format(ip, 'OK', new_file_name)
            else:
                pass    
    except Exception as e:
        print(str(e))
    finally:
       # ftp.set_debuglevel(0)
        ftp.close()
        sys.exit(0)     
def collect_config_cmd(ip, host_ip, timestamp):
    global equipment_final_map
    cmd=equipment_final_map[ip]['backup_cmd']
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(ip, 22, username=equipment_final_map[ip]['ssh_user'], password=equipment_final_map[ip]['ssh_password'], timeout=4)
    new_file_name = '{0}_{1}.cfg'.format(ip, timestamp)
    stdin, stdout, stderr = client.exec_command(cmd)
    time.sleep(float(1))
    response = stdout.read().decode()
    if  response :
            with open(os.path.join(tftp_file_path, new_file_name),'w') as f:
                f.write(response)
            print '{0}\t{1}\t{2}'.format(ip, 'OK', new_file_name)
    else:
            pass
    client.close()
        
def main(ip='', timestamp=''):
    if ip == '':
        switch_ip_list = get_ip_list.get_ip_list('switch')
    else:
        switch_ip_list = [ip]
    build_equipment_message(switch_ip_list)
    if timestamp == '':
        timestamp = time.strftime('%s', time.localtime())
    for ip in switch_ip_list:
        backup_type = equipment_final_map[ip]['backup_type']
        if backup_type == 'ftp':
            collect_config_ftp(ip, host_ip, timestamp)
        elif backup_type == 'cmd':
            collect_config_cmd(ip, host_ip, timestamp)
        else:
            pass


if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值