initial commit

This commit is contained in:
Kevin Muñoz 2024-02-13 16:05:15 -05:00
commit f4939eada3
No known key found for this signature in database
GPG Key ID: 3CA0B9DF1BE7CE09
3 changed files with 248 additions and 0 deletions

173
.gitignore vendored Normal file
View File

@ -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

14
requirements.txt Normal file
View File

@ -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

61
respaldosql.py Normal file
View File

@ -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)