Backup Python Script

Aus xinux.net
Version vom 13. Dezember 2017, 10:23 Uhr von Thomas (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „<pre> #!/usr/bin/python import sys import re import os import datetime import paramiko mandant = sys.argv[1] configdir = "/share/backup/config/" configfile = c…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Zur Navigation springen Zur Suche springen
#!/usr/bin/python
import sys
import re
import os
import datetime
import paramiko
mandant = sys.argv[1]
configdir = "/share/backup/config/"
configfile = configdir + mandant + ".cfg"
backupdir  = "/share/backup/"
logdir = "/var/log/backup"

class mandant_class(object):
 def __init__(self,man,bdir,ldir,cdir):
   self.man = man
   self.cdir = cdir
   self.datei = self.cdir + self.man + ".cfg"
   self.dat = open(self.datei,"r")
   self.bdir = bdir
   self.ldir = ldir

 def computer(self):
  self.dat.seek(0)
  comp_array = []
  for line in self.dat:
     compi,dirs = line.split(":")
     comp_array.append(compi)
  return comp_array

 def dirs(self,comp):
   self.dat.seek(0)
   return_value = ""
   for zeile in self.dat:
     line = zeile.rstrip()
     pattern = re.match(comp,line)
     if pattern:
         compi,dirs = line.split(":")
         dir_array = dirs.split(";")
         return_value = dir_array
   return return_value

 def today(self):
    today = datetime.date.today()
    str_today = str(today)
    return str_today

 def source(self,r,v):
    src = "rsync -azx " + r + ":" + v + "/ "
    return src

 def dest(self,r,v):
    mod_y = v.replace("/","-")
    mod_v = mod_y[1:]
    dst =  self.bdir + self.man + "/" + r + "/" + self.today() + "/" + mod_v
    if not os.path.isdir(dst):
      os.makedirs(dst)
    return dst

 def log(self,r,v):
    mod_y = v.replace("/","-")
    mod_v = mod_y[1:]
    manlogdir = self.ldir + "/" + self.man  + "/" + r + "/" + mod_v + "/"
    if not os.path.isdir(manlogdir):
      os.makedirs(manlogdir)
    return  manlogdir + self.today()

 def ssh_check(self,r):
    client = paramiko.SSHClient()
    client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    try:
      client.connect(r, username="root",port="8472")
      return True
    except Exception, e:
      return False

def __del__(self):
     self.dat.close()

x = mandant_class(mandant,backupdir,logdir,configdir)

for rechner in x.computer():
  for verzeichnis in x.dirs(rechner):
    if x.ssh_check(rechner):
      cmd = x.source(rechner,verzeichnis) + x.dest(rechner,verzeichnis) + " > " + x.log(rechner,verzeichnis) + ".0"
    else:
      cmd = "echo ssh error > " + x.log(rechner,verzeichnis) + ".1"
    print cmd
    os.system(cmd)