python3备份juniper交换机
admin
2023-07-29 05:00:07
0

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
  Author:  Linxy -- <592901071@qq.com>
  Purpose: Juniper备份脚本
  Created: 2017-6-23
"""

import datetime
import sys
import os
import telnetlib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
su=[]
fa=[]


#获取年月日的str数据
def getymd (ymd):
 d=datetime.datetime.now()
 if ymd=='y':
  return str(d.year)
 elif ymd=='m':
  return str(d.month)
 elif ymd=='d':
  return str(d.day)

#p1='./switch/'+getymd('y')+'/'+getymd('m')+'/'+getymd('d')
l1=[getymd('y'),getymd('m'),getymd('d')]
#print(l1)
p1='./switch'
if os.path.isdir(p1):
  pass
else: 
  os.mkdir(p1)
for i in l1:
 p1=p1+'/'+i
 if os.path.isdir(p1):
  pass
 else: 
  os.mkdir(p1)


filename1='./sw.txt'#交换机IP地址列表存放位置 注意要把最后一个IP以后的空格和回车全部删除
filename2='./ssg.txt' 
def fc_srx(p2): #文件处理部分的函数
 if os.path.getsize(p2)==0:
  
  '''
  密码不对时候 telnet的执行是成功的只是read_all的时候没有结尾的标记所以无法读出返回值
  但仍然会建立空txt文档所以需要在此再进行一次判断并把需要的值写入fa[]中
  '''
  fa.append(host+'\n')
  print(host+" is failed")
 else:
  with open(p2,'r') as f:
   lines=f.readlines()
  with open(p2,'w') as w:
   for I in lines:
    I=I.replace('---(more)---','')
    I=I.replace('                                        ','')
    I=I.replace('\r','')
    I=I.replace('\n','')
    if I=='':
     pass
    else :
     w.write(I+'\r\n') 
     
     
     
     
def fc_ssg(p2):
 if os.path.getsize(p2)==0:
  #print(host+' is failed')
  '''
  密码不对时候 telnet的执行是成功的只是read_all的时候没有结尾的标记所以无法读出返回值
  但仍然会建立空txt文档所以需要在此再进行一次判断并把需要的值写入fa[]中
  '''
  fa.append(host+'\n')
  print(host+" is failed")
 else:
  with open(p2,'r') as f:
   lines=f.readlines()
  with open(p2,'w') as w:
   for I in lines:
    I=I.replace('--- more ---','')
    I=I.replace(' ','')
    I=I.replace('\r','')
    I=I.replace('\n','')
    if I=='':
     pass
    else :
     w.write(I+'\r\n') 
 
def juniper_bak (host):#备份juniper函数
 user='这里是交换机帐号'
 password='这里是交换机密码'
 print ('Backing up:'+host)
 tn=telnetlib.Telnet(host.encode('utf-8'),port=23,timeout=4)
 tn.read_until(b"login:")
 tn.write(user.encode('utf-8')+'\n'.encode('utf-8'))
 tn.read_until(b"Password:")
 tn.write(password.encode('utf-8')+'\n'.encode('utf-8'))
 tn.read_until(b'> ')
 tn.write(b'show configuration | display set '+'\n'.encode('utf-8'))
 for i in range(300) :
  tn.write(b' ')
 tn.write(b'q\n')
 tn.write(b'q\n')

 p2=p1+'/'+host+'/'+host+'.txt'
 if os.path.isdir(p1+'/'+host):
  pass
 else: 
  os.mkdir(p1+'/'+host)


 with open(p2,'w') as f:
  f.write(tn.read_all().decode())
 tn.close()
 fc_srx(p2)
def ssg_bak (host):#备份ssg函数
 user='这里是ssg设备帐号'
 password='这里是ssg设备密码'
 print ('Backing up:'+host)
 tn=telnetlib.Telnet(host.encode('utf-8'),port=23,timeout=4)
 tn.read_until(b"login:")
 tn.write(user.encode('utf-8')+'\n'.encode('utf-8'))
 tn.read_until(b"password:")
 tn.write(password.encode('utf-8')+'\n'.encode('utf-8'))
 tn.read_until(b'>')
 tn.write(b'get config'+'\n'.encode('utf-8'))
 for i in range(50000) :#看具体设备有些设备输入200个空格即可获取到全部回显
  tn.write(b' ')
 tn.write(b'exit\n')
 p2=p1+'/'+host+'/'+host+'.txt'
 if os.path.isdir(p1+'/'+host):
  pass
 else: 
  os.mkdir(p1+'/'+host)
 
 with open(p2,'w') as f:
  f.write(tn.read_all().decode(encoding='gbk'))
 tn.close()
 fc_ssg(p2)

def sendmail_cxr(tx):#发送邮件函数
 def _format_addr(s): #注意此函数实际传入的S格式为‘字符串 <邮箱地址>’
  name, addr = parseaddr(s)
  return formataddr((Header(name, 'utf-8').encode(), addr)) 
 from_addr = '这里是发送邮件的邮箱地址'
 password = '这里是邮箱密码'
 to_addr = '接收邮件的地址1'
 to_addr2='接收邮件的地址2'
 smtp_server = 'SMT服务的域名要写这里'
 
 msg = MIMEText(tx, 'plain', 'utf-8')

 msg['From'] = _format_addr('邮件相关的格式不要细究 <%s>' % from_addr)
 msg['To'] = _format_addr('邮件相关的格式不要细究 <%s>'% to_addr)
 msg['Subject'] = Header('今日备份情况', 'utf-8').encode()  #邮件主题

 server = smtplib.SMTP(smtp_server, 25)
 #server.set_debuglevel(1)
 server.login(from_addr, password)
 server.sendmail(from_addr, [to_addr,to_addr2], msg.as_string())
 server.quit() 
 

if __name__=='__main__':
 with open (filename2,'r')as fo:
  for line in fo.readlines():
   if line.split(' ')[0]!='':
    line=line.replace('\n','')
    host=line.split(' ')[0]
    try:
     ssg_bak(host)
     su.append(host+'\n')
    except:
     print(host+" is failed")
     fa.append(host+'\n')



 with open (filename1,'r')as fo:
  for line in fo.readlines():
   if line.split(' ')[0]!='':
    line=line.replace('\n','')
    host=line.split(' ')[0]
    try:
     juniper_bak(host)
     su.append(host+'\n')
    except:
     print(host+" is failed")
     fa.append(host+'\n')
  '''
  密码不对时候 telnet的执行是成功的只是read_all的时候没有结尾的标记所以无法读出返回值
  但仍然会建立空txt文档所以需要在文本处理环节再进行一次判断并把需要的值写入fa[]中
  '''
 #print(su)
 #print(fa)
 tx=''
 if len(su)!=0:
  txsu='备份成功\n'+''.join(su)
  csu=0
  for i in su:
   csu=csu+1
  tx=tx+txsu+'总计成功'+str(csu)+'个'+'\n\n'
 if len(fa)!=0:
  cfa=0
  for i in fa:
   cfa=cfa+1
  txfa='备份失败\n'+''.join(fa)
  tx=tx+txfa+'总计失败'+str(cfa)+'个'+'\n\n'
 sendmail_cxr(tx)
 
 
 
 
 
 
 


相关内容

热门资讯

日印又提“旗舰项目”,印度首条... 【文/观察者网 王恺雯】被视为日印合作“旗舰项目”的印度首条高铁,在经历了十多年征地受阻、工期延迟、...
阿根廷宣布撤销内政部 新华社布宜诺斯艾利斯7月3日电(记者张铎 王钟毅)阿根廷政府2日宣布撤销内政部,将其职能转移至内阁首...
热浪期间,法国家中死亡人数激增... 6月18日,在法国巴黎,人们在圣马丁运河水域消暑。新华社发上个月,欧洲遭遇了史上罕见的热浪袭击。根据...
日印各有所求,专家:双方的目标... 如何分析高市早苗此次访问中日印双方展现出的态度?两国关系可能面临哪些变量?凤凰卫视连线上海国际问题研...
二七区开展胡大白先进事迹专题宣... 7月1日,二七区邀请我校马克思主义学院党委副书记、工会主席韩树栋走进区委党校,开展胡大白董事长先进事...
台媒:谷立言与特朗普立场渐行渐... 前不久,台湾《中国时报》刊发社论指出,“美国在台协会”台北办事处处长谷立言对民进党“新两国论”几乎照...
中国共产党党员队伍稳步壮大 组... 党员10128.6万名 基层党组织543.1万个中国共产党党员队伍稳步壮大 组织体系日趋严密新华社北...
演上了!美议员当众举起手机:去... 据美国印度战略伙伴关系论坛(USISPF)近日发布的一段视频,美国共和党联邦参议员史蒂夫·戴恩斯在一...
15岁少年在家中和同学饮酒后裸... 早前报道:15岁少年家中和同学饮酒后身亡,全身赤裸,屋内有火烧痕迹大象新闻(2026年7月3日)端午...
3秒钟,差点毁了韩红基金会 图为韩红/图源:@韩红工作室韩红,最近有点麻烦。先是为冯小刚新片《抓特务》宣传,一句“走面儿”引发大...