From f4939eada3e3757588fc16b16f843da7deaf09af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Mu=C3=B1oz?= Date: Tue, 13 Feb 2024 16:05:15 -0500 Subject: [PATCH] initial commit --- .gitignore | 173 +++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 14 ++++ respaldosql.py | 61 +++++++++++++++++ 3 files changed, 248 insertions(+) create mode 100644 .gitignore create mode 100644 requirements.txt create mode 100644 respaldosql.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c914563 --- /dev/null +++ b/.gitignore @@ -0,0 +1,173 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..dece2a5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +bcrypt==4.1.2 +certifi==2024.2.2 +cffi==1.16.0 +charset-normalizer==3.3.2 +cryptography==42.0.2 +idna==3.6 +paramiko==3.4.0 +pycparser==2.21 +PyNaCl==1.5.0 +pysftp==0.2.9 +pyTelegramBotAPI==4.15.4 +python-dotenv==1.0.1 +requests==2.31.0 +urllib3==2.2.0 diff --git a/respaldosql.py b/respaldosql.py new file mode 100644 index 0000000..ddef2d8 --- /dev/null +++ b/respaldosql.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os +import hashlib +import datetime +import subprocess +import pysftp +import telebot +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + +# Set up variables from environment variables +MARIADB_HOST = os.getenv("MARIADB_HOST", default="localhost") +MARIADB_USER = os.getenv("MARIADB_USER", default="root") +MARIADB_PASSWORD = os.getenv("MARIADB_PASSWORD", default="passwd") +MARIADB_DATABASE = os.getenv("MARIADB_DATABASE", default="DBName") +SQLITE_DATABASE = os.getenv("SQLITE_DATABASE", default="/Path/to/database") +SFTP_HOST = os.getenv("SFTP_HOST", default="localhost") +SFTP_USER = os.getenv("SFTP_USER", default="user") +SFTP_PASSWORD = os.getenv("SFTP_PASSWORD", default="passwd") +SFTP_PATH = os.getenv("SFTP_PATH", default="/Paht/to/sftp") +SFTP_PORT = os.getenv("SFTP_PORT", default="22") +TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", default="TOKEN") +TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", default="ID_CHAT") + +# Generate backups +start_time = datetime.datetime.now() +mariadb_backup_filename = f"mariadb_backup_{datetime.datetime.now().strftime('%Y%m%d')}.sql.gz" +subprocess.run(f"mariadb-dump -h {MARIADB_HOST} -u {MARIADB_USER} -p{MARIADB_PASSWORD} {MARIADB_DATABASE} | gzip > {mariadb_backup_filename}", shell=True, check=True) +sqlite_backup_filename = f"sqlite_backup_{datetime.datetime.now().strftime('%Y%m%d')}.sql.gz" +subprocess.run(f"sqlite3 {SQLITE_DATABASE} .dump | gzip > {sqlite_backup_filename}", shell=True, check=True) + +# Calculate SHA512 hash of backups +mariadb_hash = hashlib.sha512(open(mariadb_backup_filename, "rb").read()).hexdigest() +sqlite_hash = hashlib.sha512(open(sqlite_backup_filename, "rb").read()).hexdigest() + +# Transfer backups to SFTP server +with pysftp.Connection(host=SFTP_HOST, username=SFTP_USER, password=SFTP_PASSWORD, port=SFTP_PORT) as sftp: + sftp.put(mariadb_backup_filename, f"{SFTP_PATH}/{mariadb_backup_filename}") + sftp.put(sqlite_backup_filename, f"{SFTP_PATH}/{sqlite_backup_filename}") + +# Delete local backup files +os.remove(mariadb_backup_filename) +os.remove(sqlite_backup_filename) + +# Send message via Telegram +bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN) +message = f""" + Respaldo completado! + +* **MariaDB:** *{mariadb_backup_filename}* (hash: {mariadb_hash}) +* **SQLite:** ️ *{sqlite_backup_filename}* (hash: {sqlite_hash}) + +⏱️ Tiempo de transferencia: {datetime.datetime.now() - start_time} + + Disponible en SFTP: {SFTP_PATH} +""" +bot.send_message(TELEGRAM_CHAT_ID, message) \ No newline at end of file