溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python3備份juniper交換機(jī)

發(fā)布時間:2020-08-01 08:31:58 來源:網(wǎng)絡(luò) 閱讀:712 作者:xiye3719 欄目:開發(fā)技術(shù)

#!/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數(shù)據(jù)
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'#交換機(jī)IP地址列表存放位置 注意要把最后一個IP以后的空格和回車全部刪除
filename2='./ssg.txt' 
def fc_srx(p2): #文件處理部分的函數(shù)
 if os.path.getsize(p2)==0:
  
  '''
  密碼不對時候 telnet的執(zhí)行是成功的只是read_all的時候沒有結(jié)尾的標(biāo)記所以無法讀出返回值
  但仍然會建立空txt文檔所以需要在此再進(jìn)行一次判斷并把需要的值寫入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的執(zhí)行是成功的只是read_all的時候沒有結(jié)尾的標(biāo)記所以無法讀出返回值
  但仍然會建立空txt文檔所以需要在此再進(jìn)行一次判斷并把需要的值寫入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函數(shù)
 user='這里是交換機(jī)帳號'
 password='這里是交換機(jī)密碼'
 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函數(shù)
 user='這里是ssg設(shè)備帳號'
 password='這里是ssg設(shè)備密碼'
 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) :#看具體設(shè)備有些設(shè)備輸入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):#發(fā)送郵件函數(shù)
 def _format_addr(s): #注意此函數(shù)實(shí)際傳入的S格式為‘字符串 <郵箱地址>’
  name, addr = parseaddr(s)
  return formataddr((Header(name, 'utf-8').encode(), addr)) 
 from_addr = '這里是發(fā)送郵件的郵箱地址'
 password = '這里是郵箱密碼'
 to_addr = '接收郵件的地址1'
 to_addr2='接收郵件的地址2'
 smtp_server = 'SMT服務(wù)的域名要寫這里'
 
 msg = MIMEText(tx, 'plain', 'utf-8')

 msg['From'] = _format_addr('郵件相關(guān)的格式不要細(xì)究 <%s>' % from_addr)
 msg['To'] = _format_addr('郵件相關(guān)的格式不要細(xì)究 <%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的執(zhí)行是成功的只是read_all的時候沒有結(jié)尾的標(biāo)記所以無法讀出返回值
  但仍然會建立空txt文檔所以需要在文本處理環(huán)節(jié)再進(jìn)行一次判斷并把需要的值寫入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+'總計(jì)成功'+str(csu)+'個'+'\n\n'
 if len(fa)!=0:
  cfa=0
  for i in fa:
   cfa=cfa+1
  txfa='備份失敗\n'+''.join(fa)
  tx=tx+txfa+'總計(jì)失敗'+str(cfa)+'個'+'\n\n'
 sendmail_cxr(tx)
 
 
 
 
 
 
 


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI