示例#1
0
def checkforrestores():
    db = dbmanager(True)
    # Fetch all tasks from database
    query = db.query('SELECT c.path AS source, '
                     'd.path AS dest, '
                     'a.schedule, '
                     'a.id, '
                     'a.last_run, '
                     'a.backupfilesid, '
                     'a.backupid, '
                     'c.system AS source_fs, '
                     'd.system AS dest_fs, '
                     'c.host AS host, '
                     'c.username AS user, '
                     'c.password AS password, '
                     'a.state, '
                     'b.compression, '
                     'a.backuptyp as type, '
                     'b.last_full_run, '
                     'a.action '
                     'FROM \'143_tasks\' AS a '
                     'JOIN \'143_backups\' AS b ON a.backupid = b.id '
                     'JOIN \'143_pool\' AS c ON b.pool_src = c.id '
                     'JOIN \'143_pool\' AS d ON b.pool_dst = d.id '
                     'WHERE a.action = \'restore\'')

    tasks = query.fetchall()
    for task in tasks:
        # Import correct script for filesystem
        if task['source_fs'] == 'ftp':
            from bin.both.restore.fs_ftp import Restore
        elif task['source_fs'] == 'sftp':
            from bin.both.restore.fs_sftp import Restore
        else:
            from bin.both.restore.fs_local import Restore

        # Check if task is running and not finished
        if task['state'] != 'finished' and task['state'] != 'running':
            print('Starting normal for task ' + str(task['id']))
            startrestore(task['id'])
            # Initialize restore task
            restore = Restore(task)
            # Start restore
            #try:
            result = restore.restore()
            finishrestore(result)
            print('Restore for task ' + str(task['id']) + ' created')
示例#2
0
 def __init__(self, task):
     self.db = dbmanager()
     self.task = task
     self.restores = []
示例#3
0
from bin.both.dbcon import dbmanager

db = dbmanager()


def recordbackupfile(taskid, date, status, path):
    query = f'INSERT INTO \'143_backupfiles\' (taskid, date, state, path) ' \
            f'VALUES (\'{taskid}\', \'{date}\', \'{status}\', \'{path}\')'
    db.query(query)
示例#4
0
def checkforbackups():
    db = dbmanager(True)
    # Fetch all tasks from database
    query = db.query('SELECT c.path AS source, '
                     'd.path AS dest, '
                     'a.schedule, '
                     'a.id, '
                     'a.last_run, '
                     'c.system AS source_fs, '
                     'd.system AS dest_fs, '
                     'c.host AS host, '
                     'c.username AS user, '
                     'c.password AS password, '
                     'a.state, '
                     'b.compression, '
                     'a.backuptyp as type, '
                     'b.last_full_run, '
                     'a.action, '
                     'b.id as backupid '
                     'FROM \'143_tasks\' AS a '
                     'JOIN \'143_backups\' AS b ON a.backupid = b.id '
                     'JOIN \'143_pool\' AS c ON b.pool_src = c.id '
                     'JOIN \'143_pool\' AS d ON b.pool_dst = d.id '
                     'WHERE a.action = \'backup\'')

    tasks = query.fetchall()
    for task in tasks:
        # Import correct script for filesystem
        if task['source_fs'] == 'ftp':
            from bin.both.backup.fs_ftp import Backup
        elif task['source_fs'] == 'sftp':
            from bin.both.backup.fs_sftp import Backup
        else:
            from bin.both.backup.fs_local import Backup

        # Check if task is running
        if task['state'] is not 'running':
            # Calculate start date from last run
            if task['last_run'] is not None:
                schedule = CronTab(task['schedule'])
                diff = schedule.next()
                # Start backup if cron matches
                if diff < threshold:
                    print('Starting normal for task ' + str(task['id']))
                    startbackup(task['id'])
                    # Initialize backup task
                    backup = Backup(task)
                    # Start backup
                    # try:
                    result = backup.backup()
                    finishbackup(result)
                    print('Backup for task ' + str(task['id']) + ' created')
                    # except Exception as e:
                    #     backupfailed(task['id'], e)
                    #     print('Backup failed')
                    #     print(e)

            # Start backup immediately if never ran before
            else:
                print('Starting immediately for task ' + str(task['id']))
                startbackup(task['id'])
                # Initialize backup task
                backup = Backup(task)
                # Start backup
                try:
                    result = backup.backup()
                    finishbackup(result)
                    print('Backup for task ' + str(task['id']) + ' created')
                except Exception as e:
                    backupfailed(task['id'], e)
                    print('Backup failed')
                    print(e)
        else:
            print('Backup already running')
示例#5
0
from bin.both.dbcon import dbmanager
from crontab import CronTab
from datetime import datetime
import time
from bin.both.utils import recordbackupfile

db = dbmanager(True)
threshold = 10


def startbackup(task):
    db.log(task, '=============STARTING=============')
    updatetaskstate(task, 'running')


def finishbackup(data):
    db.log(data['task'], '=============FINIHSED=============')
    updatelastrundate(data['task'], data['date'])
    updatetaskstate(data['task'], 'waiting')
    recordbackupfile(data['task'], data['date'], data['status'], data['path'])


def backupfailed(task, err):
    db.log(task, '=============FAILED=============')
    db.log(task, f"{err}".replace("'", '"'))
    updatetaskstate(task, 'failed')
    updatelastrundate(task, str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S')))


def updatelastrundate(task, date):
    db.query('UPDATE \'143_tasks\' SET \'last_run\' = \'' + date + '\' WHERE id = ' + str(task))
示例#6
0
def dbconf(value):
    db = dbmanager()
    qry = db.query("SELECT value FROM '143_options' WHERE option = '"+ value +"' LIMIT 1;")
    result = qry.fetchone()
    return result[0]
    
示例#7
0
    def do_POST(self):

        log = logsys('http')
        log.write(
            str(self.client_address[0]) + ' - "' + str(self.requestline) + '"')

        if self.path == "/login":
            form = cgi.FieldStorage(fp=self.rfile,
                                    headers=self.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        self.headers['Content-Type'],
                                    })

            passwordhash = hashlib.sha512(
                str(form['password'].value).encode('utf8')).hexdigest()

            db = dbmanager()
            qry = db.query(
                "SELECT id, username, password FROM '143_users' WHERE username='******'username'].value) + "' AND password='******';")
            result = qry.fetchone()
            if result != None:
                date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                db = dbmanager()
                qry = db.query("UPDATE '143_users' SET last_login='******' WHERE id='" + str(result[0]) +
                               "';")
                self.send_response(301)
                self.create_session('userid', result[0], 86400)
                self.create_session('username', result[1], 86400)
                self.send_header('Location', '/panel/index.html')
                self.end_headers()
            else:
                self.send_response(301)
                self.send_header('Location', 'index.html')
                self.end_headers()
            return
        elif self.path == "/forgotten":
            form = cgi.FieldStorage(fp=self.rfile,
                                    headers=self.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        self.headers['Content-Type'],
                                    })

            username = form['username'].value

            code = random.randint(100000, 1000000)
            date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            db = dbmanager()
            qry = db.query(
                "SELECT COUNT(*) FROM '143_users' WHERE username='******' OR email = '" + str(username) + "';")
            result = qry.fetchone()
            if result[0] > 0:
                qry = db.query(
                    "SELECT id,email FROM '143_users' WHERE username='******' OR email = '" + str(username) + "';")
                result = qry.fetchone()
                db.query(
                    "INSERT INTO '143_pwreset' (userid, authcode, req_date) VALUES ('"
                    + str(result[0]) + "','" + str(code) + "','" + str(date) +
                    "');")
                mail(str(result[1]), "Password Reset",
                     "Your Reset Code is: " + str(code))
                self.send_response(301)
                self.send_header('Location', 'forgot_password_auth.html')
                self.create_session('reset_userid', str(result[0]), 1200)
                self.end_headers()
                return
            else:
                self.send_response(301)
                db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                         self.get_session('reset_userid') + "';")
                self.remove_session('reset_userid')
                self.remove_session('reset_auth')
                self.send_header('Location', 'index.html')
                self.end_headers()
        elif self.path == "/forgottenauth":
            form = cgi.FieldStorage(fp=self.rfile,
                                    headers=self.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        self.headers['Content-Type'],
                                    })

            if self.get_session('reset_userid') != False:
                code = form['code'].value

                db = dbmanager()
                qry = db.query(
                    "SELECT COUNT(*) FROM '143_pwreset' WHERE userid = '" +
                    self.get_session('reset_userid') + "' AND authcode = '" +
                    str(code) + "';")
                result = qry.fetchone()
                if result[0] > 0:
                    qry = db.query(
                        "SELECT req_date FROM '143_pwreset' WHERE userid = '" +
                        self.get_session('reset_userid') +
                        "' AND authcode = '" + str(code) + "';")
                    result = qry.fetchone()
                    crdatetime = datetime.strptime(result[0],
                                                   '%Y-%m-%d %H:%M:%S')
                    timebetween = datetime.now() - crdatetime
                    if timebetween.seconds < 1200:
                        self.send_response(301)
                        self.send_header('Location',
                                         'forgot_password_set.html')
                        self.create_session('reset_auth', "True", 1200)
                        self.end_headers()
                        return
                    else:
                        print("REQUEST TOO OLD!")
                        self.send_response(301)
                        db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                                 self.get_session('reset_userid') + "';")
                        self.remove_session('reset_userid')
                        self.remove_session('reset_auth')
                        self.send_header('Location', 'index.html')
                        self.end_headers()
                else:
                    self.send_response(301)
                    db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                             self.get_session('reset_userid') + "';")
                    self.remove_session('reset_userid')
                    self.remove_session('reset_auth')
                    self.send_header('Location', 'index.html')
                    self.end_headers()
            else:
                self.send_response(301)
                db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                         self.get_session('reset_userid') + "';")
                self.remove_session('reset_userid')
                self.remove_session('reset_auth')
                self.send_header('Location', 'index.html')
                self.end_headers()
        elif self.path == "/forgottenset":
            form = cgi.FieldStorage(fp=self.rfile,
                                    headers=self.headers,
                                    environ={
                                        'REQUEST_METHOD':
                                        'POST',
                                        'CONTENT_TYPE':
                                        self.headers['Content-Type'],
                                    })

            if self.get_session('reset_userid') != False:
                if self.get_session('reset_auth') != False:
                    db = dbmanager()
                    qry = db.query(
                        "SELECT req_date FROM '143_pwreset' WHERE userid = '" +
                        self.get_session('reset_userid') + "';")
                    result = qry.fetchone()
                    crdatetime = datetime.strptime(result[0],
                                                   '%Y-%m-%d %H:%M:%S')
                    timebetween = datetime.now() - crdatetime
                    if timebetween.seconds < 1200:
                        password = form['password'].value
                        passwordhash = hashlib.sha512(
                            str(password).encode('utf8')).hexdigest()
                        db = dbmanager()
                        db.query("UPDATE '143_users' SET password = '******' WHERE id = '" +
                                 self.get_session('reset_userid') + "';")
                        db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                                 self.get_session('reset_userid') + "';")
                        self.send_response(301)
                        self.remove_session('reset_userid')
                        self.remove_session('reset_auth')
                        self.send_header('Location', 'index.html')
                        self.end_headers()
                    else:
                        print("REQUEST TOO OLD!")
                        self.send_response(301)
                        db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                                 self.get_session('reset_userid') + "';")
                        self.remove_session('reset_userid')
                        self.remove_session('reset_auth')
                        self.send_header('Location', 'index.html')
                        self.end_headers()
                else:
                    self.send_response(301)
                    db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                             self.get_session('reset_userid') + "';")
                    self.remove_session('reset_userid')
                    self.remove_session('reset_auth')
                    self.send_header('Location', 'index.html')
                    self.end_headers()
            else:
                self.send_response(301)
                db.query("DELETE FROM '143_pwreset' WHERE userid='" +
                         self.get_session('reset_userid') + "';")
                self.remove_session('reset_userid')
                self.remove_session('reset_auth')
                self.send_header('Location', 'index.html')
                self.end_headers()
        else:
            script_dir = os.path.dirname(__file__)
            rel_path = "../../web/error_docs/404.html"
            abs_file_path = os.path.join(script_dir, rel_path)
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(open(abs_file_path, "rb").read())
示例#8
0
 def __init__(self, task):
     self.db = dbmanager()
     self.task = task
     self.conn = sftp.Connection(host=task['host'],
                                 username=task['user'],
                                 password=task['password'])
示例#9
0
 def __init__(self, task):
     self.db = dbmanager()
     self.task = task
示例#10
0
 def __init__(self, source, dest, task):
     self.db = dbmanager()
     self.source = source
     self.dest = dest
     self.task = task