python使用ssh登录批量备份华为交换机配置

# coding = utf-8
import paramiko
import re
from datetime import datetime
import time, os
import threading

threads = [10]

# from getpass import getpass
#now_time = str(time.localtime().tm_year) + str(time.localtime().tm_mon) + str(time.localtime().tm_mday)  # 获取当前日期时间
now = datetime.now()
now_time1 = str(now.year) + str(now.month) + str(now.day) # 获取当前日期时间
username = 'admin'
password = 'passwd'   

path = r'D:\网络配置文件备份\\' + now_time1   # 配置文件保存路径
ip_add_file = open(os.getcwd() + '\ip_add2.txt').readlines()
ip = [one for one in ip_add_file]
isExists = os.path.exists(path)     # 判断文件是否已经创建
if not isExists:
    os.makedirs(path)               # 如果没有创建,则新建文件夹
    print(path + ' 创建成功!')
else:
    print(path + ' 目录已存在')        # 已经创建提示


def back_config(ip, username, password):
    ip_add_file = open(os.getcwd() + '\ip_add2.txt')  # 打开ip地址文件,需要备份的设备IP地址txt文件
    for line in ip_add_file.readlines():  # for循环读取设备IP地址
        ip = line.strip()
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
            ssh_client.connect(hostname=ip,port=22,username=username,password=password,look_for_keys=False)  # 远程连接设备
            command = ssh_client.invoke_shell()
            print('成功登陆设备:' + ip)
            command.send('screen-length 0 temporary \n')    # 设置回显内容不分屏显示
            time.sleep(0.5)
            command.send('dis cu \n')  # 查询配置信息
            time.sleep(3)         # 等待结果输出时间,配置越多,输出时间应对应增加
            command_result = command.recv(65535).decode()
            time.sleep(1.5)
            #print(command_result)
            Sw_name = re.findall('<(\w+.*\d)>', command_result)[0]     # 提取配置文件中的设备名称
            time.sleep(0.3)
            #print(Sw_name)
            backup = open(path + '\\' + Sw_name + '-' + ip + '.txt','a+')  # 备份配置文件保存路径+文件名
            #time.sleep(0.5)
            print("成功备份:" + Sw_name + '-' + ip)
            backup.write(command_result)  # 将回显内容写入backup这个对象,相当于写入了备份文件中
            time.sleep(1)
            backup.close()
        except:
            print('%s\tError\n' % (ip))
    ip_add_file.close()
    ssh_client.close()
    print('备份完成!')

if __name__ == '__main__':
    print("Begin......")
    a = threading.Thread(target=back_config, args=(ip, username, password))
    a.start()
 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李先生在闯荡江湖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值