您的位置:首页 > 编程语言 > Python开发

python3 网络设备备份配置文件(可跨平台)

2020-02-03 15:49 204 查看

安装 paramiko

pip3 install paramiko

作用:使用SSH协议对远程服务器操作

代码:

import paramiko, time ,os
a = os.getcwd()   #当前的绝对路径
b = os.listdir()     #显示文件下的列表
time_1 = time.strftime('%Y-%m-%d')   #定义时间
if time_1 in b:   #判断是否创建了文件夹,否就创建
print('文件夹已创建')
else:
C_dir = os.mkdir(time_1)   #创建目录
def bak_file(date):     #定义函数,存放备份的信息
path = os.path.join(a, time_1, ip_addr + '.txt')    #路径拼接,方便备份文件存到固定的文件里
with open(path,mode='w',encoding='utf-8') as f:   #创建文件
f.write(date)
f.close()
ip = [('11.11.11.11',22,'yang','yangshxx'),    #列表,放服务器信息,ip,端口,用户,密码
('22.22.22.22',22,'yang','yangshxx'),
('33.33.33.33',22,'yang','yangshxx')
]
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for ip_addr,port,user,passw in ip:
try:               #考虑登入失败后能给到具体的报错
ssh.connect(hostname=ip_addr,port=port,username=user,password=passw,timeout=20)
except Exception as e:
print(ip_addr,e)
continue
stdin, stdout, stderr = ssh.exec_command('show full-configuration')  #飞塔设备的命令。查看全部配置
conf = stdout.read().decode('utf-8')
bak_file(conf)
a1 = os.getcwd()
b1 = os.listdir(os.path.join(a1, time_1))
print(b1)    #打印已经备份的文件

需要修改的部分:

1、列表,存放服务器链接信息—14行
2、命令-----26行

还可以结合sys.argv传参数,但是这样不方便设备很多的时候

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Y。S。H。 发布了45 篇原创文章 · 获赞 14 · 访问量 3782 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: