# 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()