python多线程,外网ftp批量备份交换机配置(需要修改~)

网上找的,目前还无法正常使用,有些问题,需要修改
注意:1、需要创建device.xls表格用户存储交换机ip 和密码信息
2、意图是连接外网ftp备份使用
3、如果再内网使用的话,需要把不用的多网卡禁用!否则连接失败
在这里插入图device.xls片描述

在这里插入代码片
```#!/usr/bin/env python3
import ftplib

import paramiko
import time
import telnetlib, sys
import xlrd
import threading
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import time
import socket
import re
from ftplib import FTP #补充!!!

listenip = []


def ftpserver(ip):
    authorizer = DummyAuthorizer()
    authorizer.add_user('admin', 'passwd', '.', perm='elradfmw')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = FTPServer((ip, 21), handler)
    server.serve_forever()
    # handler.passive_ports = range(2000, 2333) #添加被动模式端口


class ftpThread(threading.Thread):
    def __init__(self, threadID, name, x):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.x = x

    def run(self):
        ftpserver("192.168.137.1")


def get_dev(colum):
    f = xlrd.open_workbook('device.xls')
    tables = f.sheet_by_index(0)
    device_list = []
    x = 1
    while True:
        try:
            data = tables.cell(x, colum)
            x += 1
            data = str(data)
            device_list.append(data[6:][:-1])
        except IndexError:
            break
    print('devices:')
    for i in device_list:
        print(i)
    return device_list


address = socket.getaddrinfo(socket.gethostname(), None)
ip = ''
serverip = ''
for item in address:
    if ':' not in item[4][0]:
        ip = item[4][0]
        try:
            ip = re.search(r'169.254.\d*', str(ip)).group()
        except AttributeError:
            if ip != '':
                listenip.append(ip)
            serverip = ip
            print(serverip)
i = 1
'''
for x in listenip:
	locals()['thread' + str(i)] = ftpThread(i, "Thread-%s" % i, x)
	locals()['thread' + str(i)].setDaemon(True)
	locals()['thread' + str(i)].start()
	locals()['thread' + str(i)].join(timeout=1)
	#i = i+1
	'''
locals()['thread' + str(i)] = ftpThread(i, "Thread-%s" % i, i)
locals()['thread' + str(i)].setDaemon(True)
locals()['thread' + str(i)].start()
locals()['thread' + str(i)].join(timeout=1)

devlist = get_dev(1)
userlist = get_dev(2)
passlist = get_dev(3)
index = 0
for dev in devlist:
    cfgname = 'vrpcfg.zip'
    try:
        tn = telnetlib.Telnet(dev, port=23, timeout=3)
    except OSError:
        print("无法访问目标设备")
        continue
    print(tn.read_until(b'Username:', 1).decode('ascii'))
    print(tn.read_until(b'login:', 1).decode('ascii'))
    name = userlist[index]
    passwd = passlist[index]
    tn.write(str.encode(name))
    tn.write(b'\n')
    print(tn.read_until(b'Password:', 1).decode('ascii'))
    tn.write(str.encode(passwd))
    tn.write(b'\n')
    time.sleep(1)
    tn.write(b'dir\n ')
    time.sleep(1)
    result = tn.read_very_eager().decode('utf-8')
    print('dir*********' + result)
    y = re.search(r'startup.cfg', result)
    if y != None:
        print('H3C')
        cfgname = y.group()
        print('配置文件是:' + cfgname)
    else:
        y = re.search(r'vrpcfg.zip', result)
        if y != None:
            print('huawei')
            cfgname = y.group()
            print('配置文件是:' + cfgname)
        else:
            print('没有找到配置文件!')
            cfgname = ''
    cmd = "ftp " + serverip + "\n"
    tn.write(cmd.encode("utf-8"))
    print(tn.read_until(b'(none)):', 1).decode('utf-8'))
    tn.write(b'admin\n')  # 此处填入ftp用户名
    time.sleep(1)
    result = tn.read_very_eager().decode('gb2312')
    print(result)
    print(tn.read_until(b'password:', 1).decode('gb2312'))
    tn.write(b'111111\n')  # 此处填入ftp密码
    print(tn.read_until(b'ftp]', 1).decode('gb2312'))
    print(tn.read_until(b'ftp>', 1).decode('gb2312'))
    put_cli = 'put ' + cfgname + '\n'
    tn.write(put_cli.encode("utf-8"))
    print(tn.read_until(b'seconds', 1).decode('gb2312'))
    tn.close()
    print(ip, 'finish!')
    index = index + 1


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
批量备份华为、H3C交换机配置,可以使用 PythonParamiko 模块来实现。以下是实现步骤: 1. 安装 Paramiko 模块 可以使用 pip 安装 Paramiko 模块:`pip install paramiko` 2. 编写 Python 脚本 ```python import paramiko # 定义交换机信息 switches = [ {'hostname': '192.168.1.1', 'username': 'admin', 'password': '123456', 'brand': 'huawei'}, {'hostname': '192.168.1.2', 'username': 'admin', 'password': '123456', 'brand': 'h3c'} ] # 遍历交换机列表 for switch in switches: # 连接交换机 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(switch['hostname'], username=switch['username'], password=switch['password']) # 根据品牌执行备份命令 if switch['brand'] == 'huawei': # 华为交换机备份命令 command = 'save configuration to tftp 192.168.1.3 VR-Mgmt-all-backup.cfg' elif switch['brand'] == 'h3c': # H3C交换机备份命令 command = 'backup startup-configuration to 192.168.1.3' # 执行备份命令 stdin, stdout, stderr = ssh.exec_command(command) # 输出备份结果 print(f"{switch['hostname']} backup {'successful' if not stderr.read() else 'failed'}") # 关闭连接 ssh.close() ``` 以上代码中,我们定义了一个 `switches` 列表,其中包含了多个交换机的信息,包括主机名、用户名、密码和品牌。然后遍历列表,根据品牌执行相应的备份命令,并输出备份结果。最后关闭连接。 在华为交换机备份命令中,我们使用了 `save configuration to tftp` 命令将配置备份到 TFTP 服务器上,需要提前在 TFTP 服务器上安装和配置 TFTP 服务。在 H3C交换机备份命令中,我们使用了 `backup startup-configuration to` 命令将配置备份到指定地址上。 注意:在执行 SSH 连接时,需要确认 SSH 服务已经启动,并且需要在防火墙中允许 SSH 服务通过。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值