1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- from shara.smb_path_creator import smb_path_creator as spc
- from shara.works_with_smb import works_with_smb
- from datetime import date
- from dotenv import load_dotenv
- from email.message import EmailMessage
- from email.headerregistry import Address
- import smtplib
- import os
- import socket
- # Load variable from .env
- dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
- if os.path.exists(dotenv_path):
- load_dotenv(dotenv_path=dotenv_path)
- SERVER_DOMAIN = os.getenv('SERVER_DOMAIN')
- PATH_DIR_LOCAL_BACKUP = os.getenv('PATH_LOCAL_BACKUP')
- # SMB_CONFIG
- wws = works_with_smb(os.getenv('SMB_USER'), os.getenv('SMB_PASSWORD'),
- remote_name_machine=os.getenv('SMB_NAME_MACHIME'),
- ip=os.getenv('SMB_SERVER'),
- share_name=os.getenv('SMB_SHARA_NAME'),
- my_hostname=socket.gethostname())
- wws.connect()
- def get_date():
- return date.today().strftime('%Y%m%d')
- def filter_files(list_files, filter):
- return [file for file in list_files if filter in file]
- def get_last_backups():
- list_files = sorted(os.listdir(PATH_DIR_LOCAL_BACKUP))
- last_db_backup = filter_files(list_files, '-db-')[-1]
- last_site_backup = filter_files(list_files, '-site-')[-1]
- last_data_backup = filter_files(list_files, '-data-')[-1]
- return [last_db_backup, last_site_backup, last_data_backup]
- def del_old_backup(file):
- if '-db-' in file:
- wws.delete_files(spc(SERVER_DOMAIN, '*-db-*'))
- elif '-site-' in file:
- wws.delete_files(spc(SERVER_DOMAIN, '*-site-*'))
- elif '-data-' in file:
- wws.delete_files(spc(SERVER_DOMAIN, '*-data-*'))
- def create_message(file):
- msg = EmailMessage()
- msg['Subject'] = F"Copy backup: {file}"
- from_addr = os.getenv('SMTP_USER').split("@")
- msg['From'] = Address("Program: open_kbsu", from_addr[0], from_addr[1])
- to_addr = os.getenv("ADDRESS_TO").split("@")
- msg['To'] = Address(os.getenv("NAME"), to_addr[0], to_addr[1])
- msg.set_content(F"Copy backup {file} from {SERVER_DOMAIN}")
- return msg
- def send_massage(msg):
- try:
- smtp = smtplib.SMTP_SSL(host=os.getenv(
- "SMTP_SERVER"), port=os.getenv("SMTP_PORT"), timeout=20)
- smtp.login(os.getenv("SMTP_USER"), os.getenv("SMTP_PASSWORD"))
- smtp.send_message(msg)
- except smtplib.SMTPSenderRefused:
- pass
- except smtplib.SMTPAuthenticationError:
- pass
- def main():
- wws.create_dir(SERVER_DOMAIN)
- last_backups = get_last_backups()
- for file in filter_files(last_backups, get_date()):
- if file not in wws.get_listfiles(spc(SERVER_DOMAIN)):
- del_old_backup(file)
- wws.copy_files_to_smb(
- spc(PATH_DIR_LOCAL_BACKUP, file), spc(SERVER_DOMAIN, file))
- send_massage(create_message(file))
- wws.close()
- if __name__ == "__main__":
- main()
|