Advertisement
Guest User

backup config using python

a guest
Sep 19th, 2017
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.19 KB | None | 0 0
  1. devices.py
  2. class NWDevice:
  3.         name = ''
  4.         ipaddr = ''
  5.         login = ''
  6.         password = ''
  7.         command = ''
  8.         file = ''
  9.         repo = ''
  10.  
  11. devicelist = []
  12.  
  13. def init_devices():
  14.         device = NWDevice()
  15.         device.name = 'SWAC_0801'
  16.         device.ipaddr = '192.168.8.221'
  17.         device.login = 'backupd'
  18.         device.password = 'password'
  19.         device.command = 'show configuration | display set | no-more'
  20.         device.file = 'fullconfig.cfg'
  21.         device.repo = 'ssh://git@bitbucket.loc:10999/ii/swac_0801.git'
  22.         devicelist.append(device)
  23.  
  24.         device = NWDevice()
  25.         device.name = 'SWAC_0802'
  26.         device.ipaddr = '192.168.8.222'
  27.         device.login = 'backupd'
  28.         device.password = 'password'
  29.         device.command = 'show configuration | display set | no-more'
  30.         device.file = 'fullconfig.cfg'
  31.         device.repo = 'ssh://git@bitbucket.loc:10999/ii/swac_0802.git'
  32.         devicelist.append(device)
  33.  
  34.  
  35.        
  36. backupconfig.py    
  37. from paramiko import client
  38. import time
  39. import git
  40. import os
  41. from subprocess import call
  42. import threading
  43. from devices import init_devices
  44. from devices import devicelist
  45. import logging
  46. import sys
  47.  
  48. class LogPipe(threading.Thread):
  49.     def __init__(self, level):
  50.         threading.Thread.__init__(self)
  51.         self.daemon = False
  52.         self.level = level
  53.         self.fdRead, self.fdWrite = os.pipe()
  54.         self.pipeReader = os.fdopen(self.fdRead)
  55.         self.start()
  56.  
  57.     def fileno(self):
  58.         return self.fdWrite
  59.  
  60.     def run(self):
  61.         for line in iter(self.pipeReader.readline, ''):
  62.             logging.log(self.level, line.strip('\n'))
  63.  
  64.         self.pipeReader.close()
  65.  
  66.     def close(self):
  67.         os.close(self.fdWrite)
  68.  
  69. class ssh:
  70.     client = None
  71.  
  72.     def __init__(self, address, username, password):
  73.         self.client = client.SSHClient()
  74.         self.client.set_missing_host_key_policy(client.AutoAddPolicy())
  75.         self.client.connect(address, username=username, password=password, look_for_keys=False)
  76.  
  77.     def sendCommand(self, command):
  78.         if(self.client):
  79.             stdin, stdout, stderr = self.client.exec_command(command)
  80.             while not stdout.channel.exit_status_ready():
  81.                 if stdout.channel.recv_ready():
  82.                     alldata = stdout.channel.recv(1024)
  83.                     prevdata = b"1"
  84.                     while prevdata:
  85.                         prevdata = stdout.channel.recv(1024)
  86.                         alldata += prevdata
  87.                     return (str(alldata))
  88.         else:
  89.             return ""
  90.  
  91. def backup(device):
  92.         logging.info('Backup '+device.file+' from '+device.name+' ['+device.ipaddr+']')
  93.  
  94.         #connect to device
  95.         connection = ssh(device.ipaddr,device.login,device.password)
  96.         answer = connection.sendCommand(device.command)
  97.  
  98.         #get config
  99.         configfile = '/home/python/repos/'+device.name+'/'+device.file
  100.         dir = os.path.dirname(configfile)
  101.         if not os.path.exists(dir):
  102.                 os.makedirs(dir)
  103.         f=open(configfile,'w')
  104.         f.write(answer)
  105.         f.close()
  106.         logging.info('Save config to: '+configfile)
  107.  
  108.         logpipe = LogPipe(logging.INFO)
  109.  
  110.         #check git repo
  111.         if not os.path.exists(dir+'/.git'):
  112.                 call(['git','init'],cwd=dir,stdout=logpipe,stderr=logpipe)
  113.                 call(['git','add','--all'],cwd=dir,stdout=logpipe,stderr=logpipe)
  114.                 call(['git','remote','add','origin',device.repo],cwd=dir,stdout=logpipe,stderr=logpipe)
  115.                 logging.info('Create GIT repo: '+device.repo)
  116.  
  117.         #commit changes
  118.         message =  'Changes '+time.strftime("%d %b %Y %H:%M")
  119.         call(['git','commit','-a','-m',message],cwd=dir,stdout=logpipe,stderr=logpipe)
  120.         call(['git','push','-u','origin','master'],cwd=dir,stdout=logpipe,stderr=logpipe)
  121.         logpipe.close()
  122.         return 0
  123.  
  124. #configure log
  125. logging.basicConfig(filename='/var/log/backupconfig.log', level=logging.INFO, format='%(asctime)s %(message)s')
  126. logging.info('RUN Script')
  127.  
  128. #load devices configuration
  129. init_devices()
  130.  
  131. for device in devicelist:
  132.         backup(device)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement