\x89PNG\r\n\x1a\n\x00\x00\x00\x0DIHDR\x00\x00\x00\x01\x00 \x00\x00\x01\x08\x06\x00\x00\x00\x1F\x15\xC4\x89\x00\x00\x00 \x0AIDATx\x9Ccb\x00\x00\x00\x06\x00\x03\x1A\x05\x9D\x00\x00 \x00\x00IEND\xAE\x42\x60\x82
| Path : /var/www/html/yedekledb24/DatabaseBackupMasterv7/ |
|
B-Con CMD Config cPanel C-Rdp D-Log Info Jump Mass Ransom Symlink vHost Zone-H |
| Current File : /var/www/html/yedekledb24/DatabaseBackupMasterv7/integrate_compression.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Veritabanı yedekleme işlemlerine sıkıştırma özelliğini entegre eden script.
"""
import os
import sys
import logging
import shutil
from pathlib import Path
# Logging yapılandırması
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def update_backup_utils():
"""
backup_utils.py dosyasını sıkıştırma özelliğini ekleyecek şekilde günceller.
"""
# Güncellenecek dosya
file_path = "backup_utils.py"
if not os.path.exists(file_path):
logger.error(f"Dosya bulunamadı: {file_path}")
return False
# Yedek oluştur
backup_path = f"{file_path}.bak"
shutil.copy2(file_path, backup_path)
logger.info(f"Yedek oluşturuldu: {backup_path}")
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# import bölümüne database_compression modülünü ekle
if "import logging" in content and "import database_compression" not in content:
content = content.replace(
"import logging",
"import logging\nimport database_compression"
)
# Yedekleme işlemi sonrasında sıkıştırma ekleniyor
if "def run_backup(" in content:
run_backup_end = """ # Başarılı bir şekilde tamamlandı
log.status = 'success'
log.message = f"Backup completed successfully. Backup file: {backup_file}"
log.backup_file = backup_file
log.backup_size = os.path.getsize(backup_file) if os.path.exists(backup_file) else 0
# Yedeği şifrele (eğer yapılandırıldıysa)
if job.encrypt_backup and (job.encryption_type == 'symmetric' or job.encryption_type == 'asymmetric'):
from encryption_utils import encrypt_file
encryption_key_id = None
encryption_passphrase = None
if job.encryption_type == 'asymmetric' and job.encryption_key_id:
# Asimetrik şifreleme için anahtar ID'sini al
from models import EncryptionKey
key = EncryptionKey.query.get(job.encryption_key_id)
if key:
encryption_key_id = key.fingerprint
else:
log.message += ". WARNING: Encryption key not found, backup was not encrypted."
elif job.encryption_type == 'symmetric':
# Simetrik şifreleme için şifreyi al
encryption_passphrase = job.encryption_passphrase
if encryption_key_id or encryption_passphrase:
encrypted_file = encrypt_file(
backup_file,
recipients=[encryption_key_id] if encryption_key_id else None,
passphrase=encryption_passphrase
)
if encrypted_file:
log.message += f". Backup was encrypted: {encrypted_file}"
log.encrypted = True
log.encryption_type = job.encryption_type
# Şifrelenmemiş yedeği sil
if os.path.exists(backup_file):
os.remove(backup_file)
# Yedek dosya yolunu güncelle
log.backup_file = encrypted_file
log.backup_size = os.path.getsize(encrypted_file)
else:
log.message += ". WARNING: Encryption failed."
# Yedeği sıkıştır (opsiyonel)
if hasattr(job, 'compress_backup') and job.compress_backup:
compression_type = getattr(job, 'compression_type', 'zip')
compressed_file = database_compression.compress_file(
log.backup_file,
compression_type=compression_type
)
if compressed_file:
# Sıkıştırma başarılı
original_size = log.backup_size
compressed_size = os.path.getsize(compressed_file)
compression_ratio = database_compression.get_compression_ratio(log.backup_file, compressed_file)
log.message += f". Backup was compressed: {os.path.basename(compressed_file)}, "
log.message += f"compression ratio: {compression_ratio:.2f}% "
log.message += f"({original_size:,} bytes -> {compressed_size:,} bytes)"
# Sıkıştırılmamış yedeği sil
if os.path.exists(log.backup_file):
os.remove(log.backup_file)
# Yedek dosya yolunu güncelle
log.backup_file = compressed_file
log.backup_size = compressed_size
# Tamamlanan işlemi kaydet
db.session.add(log)
db.session.commit()
# E-posta bildirimi gönder
if send_email:
from email_utils import send_backup_notification
send_backup_notification(log.id)
return True"""
original_run_backup_end = """ # Başarılı bir şekilde tamamlandı
log.status = 'success'
log.message = f"Backup completed successfully. Backup file: {backup_file}"
log.backup_file = backup_file
log.backup_size = os.path.getsize(backup_file) if os.path.exists(backup_file) else 0
# Yedeği şifrele (eğer yapılandırıldıysa)
if job.encrypt_backup and (job.encryption_type == 'symmetric' or job.encryption_type == 'asymmetric'):
from encryption_utils import encrypt_file
encryption_key_id = None
encryption_passphrase = None
if job.encryption_type == 'asymmetric' and job.encryption_key_id:
# Asimetrik şifreleme için anahtar ID'sini al
from models import EncryptionKey
key = EncryptionKey.query.get(job.encryption_key_id)
if key:
encryption_key_id = key.fingerprint
else:
log.message += ". WARNING: Encryption key not found, backup was not encrypted."
elif job.encryption_type == 'symmetric':
# Simetrik şifreleme için şifreyi al
encryption_passphrase = job.encryption_passphrase
if encryption_key_id or encryption_passphrase:
encrypted_file = encrypt_file(
backup_file,
recipients=[encryption_key_id] if encryption_key_id else None,
passphrase=encryption_passphrase
)
if encrypted_file:
log.message += f". Backup was encrypted: {encrypted_file}"
log.encrypted = True
log.encryption_type = job.encryption_type
# Şifrelenmemiş yedeği sil
if os.path.exists(backup_file):
os.remove(backup_file)
# Yedek dosya yolunu güncelle
log.backup_file = encrypted_file
log.backup_size = os.path.getsize(encrypted_file)
else:
log.message += ". WARNING: Encryption failed."
# Tamamlanan işlemi kaydet
db.session.add(log)
db.session.commit()
# E-posta bildirimi gönder
if send_email:
from email_utils import send_backup_notification
send_backup_notification(log.id)
return True"""
content = content.replace(original_run_backup_end, run_backup_end)
# Değişiklikleri kaydet
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Dosya güncellendi: {file_path}")
return True
except Exception as e:
logger.error(f"Dosya güncellenirken hata oluştu: {str(e)}")
# Hata durumunda yedeği geri yükle
if os.path.exists(backup_path):
shutil.copy2(backup_path, file_path)
logger.info(f"Yedek geri yüklendi: {backup_path} -> {file_path}")
return False
def update_models():
"""
models.py dosyasına sıkıştırma özelliği için sütunlar ekler.
"""
# Güncellenecek dosya
file_path = "models.py"
if not os.path.exists(file_path):
logger.error(f"Dosya bulunamadı: {file_path}")
return False
# Yedek oluştur
backup_path = f"{file_path}.bak"
shutil.copy2(file_path, backup_path)
logger.info(f"Yedek oluşturuldu: {backup_path}")
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# BackupJob modeline sıkıştırma alanlarını ekle
if "class BackupJob(db.Model):" in content:
encryption_fields = """ encrypt_backup = db.Column(db.Boolean, default=False)
encryption_type = db.Column(db.String(16), nullable=True) # symmetric, asymmetric
encryption_key_id = db.Column(db.Integer, db.ForeignKey('encryption_key.id', name='fk_backup_job_encryption_key'), nullable=True)
encryption_passphrase = db.Column(db.String(256), nullable=True)"""
compression_fields = """ encrypt_backup = db.Column(db.Boolean, default=False)
encryption_type = db.Column(db.String(16), nullable=True) # symmetric, asymmetric
encryption_key_id = db.Column(db.Integer, db.ForeignKey('encryption_key.id', name='fk_backup_job_encryption_key'), nullable=True)
encryption_passphrase = db.Column(db.String(256), nullable=True)
# Sıkıştırma ayarları
compress_backup = db.Column(db.Boolean, default=True)
compression_type = db.Column(db.String(16), default='zip') # zip, gzip, tar.gz"""
content = content.replace(encryption_fields, compression_fields)
# Değişiklikleri kaydet
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Dosya güncellendi: {file_path}")
return True
except Exception as e:
logger.error(f"Dosya güncellenirken hata oluştu: {str(e)}")
# Hata durumunda yedeği geri yükle
if os.path.exists(backup_path):
shutil.copy2(backup_path, file_path)
logger.info(f"Yedek geri yüklendi: {backup_path} -> {file_path}")
return False
def update_forms():
"""
forms.py dosyasına sıkıştırma seçeneklerini ekler.
"""
# Güncellenecek dosya
file_path = "forms.py"
if not os.path.exists(file_path):
logger.error(f"Dosya bulunamadı: {file_path}")
return False
# Yedek oluştur
backup_path = f"{file_path}.bak"
shutil.copy2(file_path, backup_path)
logger.info(f"Yedek oluşturuldu: {backup_path}")
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# BackupJobForm formuna sıkıştırma alanlarını ekle
if "class BackupJobForm(FlaskForm):" in content:
encryption_fields = """ encrypt_backup = BooleanField('Yedekleri Şifrele', default=False,
description="GPG şifreleme kullanarak yedekleri güvenli bir şekilde şifreleyin")
encryption_type = SelectField('Şifreleme Türü', choices=[
('', 'Şifreleme Yok'),
('symmetric', 'Simetrik (Şifre ile)'),
('asymmetric', 'Asimetrik (GPG Anahtarı ile)')
], default='', validators=[Optional()])
encryption_key_id = SelectField('Şifreleme Anahtarı', coerce=int, validators=[Optional()])
encryption_passphrase = PasswordField('Şifreleme Şifresi', validators=[Optional(), Length(min=8, max=128)],
description="Simetrik şifreleme için güçlü bir şifre girin")"""
compression_fields = """ encrypt_backup = BooleanField('Yedekleri Şifrele', default=False,
description="GPG şifreleme kullanarak yedekleri güvenli bir şekilde şifreleyin")
encryption_type = SelectField('Şifreleme Türü', choices=[
('', 'Şifreleme Yok'),
('symmetric', 'Simetrik (Şifre ile)'),
('asymmetric', 'Asimetrik (GPG Anahtarı ile)')
], default='', validators=[Optional()])
encryption_key_id = SelectField('Şifreleme Anahtarı', coerce=int, validators=[Optional()])
encryption_passphrase = PasswordField('Şifreleme Şifresi', validators=[Optional(), Length(min=8, max=128)],
description="Simetrik şifreleme için güçlü bir şifre girin")
# Sıkıştırma Seçenekleri
compress_backup = BooleanField('Yedekleri Sıkıştır', default=True,
description="Disk alanından tasarruf etmek için yedekleri sıkıştırın")
compression_type = SelectField('Sıkıştırma Formatı', choices=[
('zip', 'ZIP (.zip)'),
('gzip', 'GZIP (.gz)'),
('tar.gz', 'TAR.GZ (.tar.gz)')
], default='zip', validators=[Optional()])"""
content = content.replace(encryption_fields, compression_fields)
# Değişiklikleri kaydet
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Dosya güncellendi: {file_path}")
return True
except Exception as e:
logger.error(f"Dosya güncellenirken hata oluştu: {str(e)}")
# Hata durumunda yedeği geri yükle
if os.path.exists(backup_path):
shutil.copy2(backup_path, file_path)
logger.info(f"Yedek geri yüklendi: {backup_path} -> {file_path}")
return False
def create_db_migration():
"""
Veritabanı şemasına sıkıştırma alanlarını eklemek için migration script oluşturur.
"""
# Migration script dosyası
file_path = "add_compression_columns.py"
try:
# Daha önce oluşturulmuş mu kontrol et
if os.path.exists(file_path):
logger.warning(f"Migration dosyası zaten mevcut: {file_path}")
return True
# Migration script içeriğini oluştur
content = """#!/usr/bin/env python
# -*- coding: utf-8 -*-
\"\"\"
yedekleDB24 için veritabanı şeması güncelleme scripti.
Bu script, yedeklerin sıkıştırılması için gerekli sütunları ekler.
\"\"\"
import os
import sys
import logging
import sqlalchemy
from sqlalchemy import create_engine, MetaData, Table, Column, Boolean, String
from sqlalchemy.exc import SQLAlchemyError
# Logging yapılandırması
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def get_database_url():
\"\"\"Veritabanı URL'sini çevre değişkeninden alır.\"\"\"
db_url = os.environ.get('DATABASE_URL')
if not db_url:
logger.error("DATABASE_URL çevre değişkeni bulunamadı.")
sys.exit(1)
return db_url
def add_compression_columns():
\"\"\"Sıkıştırma için gerekli sütunları ekler.\"\"\"
try:
# Veritabanı bağlantısı
db_url = get_database_url()
engine = create_engine(db_url)
metadata = MetaData()
metadata.reflect(bind=engine)
# BackupJob tablosuna sıkıştırma sütunlarını ekle
if 'backup_job' in metadata.tables:
backup_job = metadata.tables['backup_job']
with engine.begin() as connection:
# compress_backup sütunu ekle (varsa kontrol et)
if 'compress_backup' not in backup_job.columns:
connection.execute(sqlalchemy.text(
"ALTER TABLE backup_job ADD COLUMN compress_backup BOOLEAN DEFAULT TRUE"
))
logger.info("compress_backup sütunu eklendi.")
else:
logger.info("compress_backup sütunu zaten mevcut.")
# compression_type sütunu ekle (varsa kontrol et)
if 'compression_type' not in backup_job.columns:
connection.execute(sqlalchemy.text(
"ALTER TABLE backup_job ADD COLUMN compression_type VARCHAR(16) DEFAULT 'zip'"
))
logger.info("compression_type sütunu eklendi.")
else:
logger.info("compression_type sütunu zaten mevcut.")
logger.info("Yedek işleri tablosuna sıkıştırma sütunları başarıyla eklendi.")
return True
else:
logger.error("backup_job tablosu bulunamadı!")
return False
except SQLAlchemyError as e:
logger.error(f"Veritabanı hatası: {str(e)}")
return False
except Exception as e:
logger.error(f"Beklenmeyen hata: {str(e)}")
return False
def main():
\"\"\"Ana fonksiyon\"\"\"
try:
logger.info("Veritabanı şemasına sıkıştırma sütunları ekleniyor...")
if add_compression_columns():
logger.info("Veritabanı şeması başarıyla güncellendi.")
return 0
else:
logger.error("Veritabanı şeması güncellenemedi!")
return 1
except Exception as e:
logger.error(f"İşlem sırasında hata oluştu: {str(e)}")
return 1
if __name__ == "__main__":
sys.exit(main())
"""
# Dosyayı oluştur
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Migration dosyası oluşturuldu: {file_path}")
return True
except Exception as e:
logger.error(f"Migration dosyası oluşturulurken hata oluştu: {str(e)}")
return False
def main():
"""Ana fonksiyon"""
logger.info("Veritabanı yedeklerine sıkıştırma özelliği entegrasyonu başlatılıyor...")
success = True
# backup_utils.py dosyasını güncelle
if update_backup_utils():
logger.info("backup_utils.py güncellendi.")
else:
logger.error("backup_utils.py güncellenemedi!")
success = False
# models.py dosyasını güncelle
if update_models():
logger.info("models.py güncellendi.")
else:
logger.error("models.py güncellenemedi!")
success = False
# forms.py dosyasını güncelle
if update_forms():
logger.info("forms.py güncellendi.")
else:
logger.error("forms.py güncellenemedi!")
success = False
# Veritabanı migration dosyası oluştur
if create_db_migration():
logger.info("Veritabanı migration dosyası oluşturuldu.")
else:
logger.error("Veritabanı migration dosyası oluşturulamadı!")
success = False
if success:
logger.info("Sıkıştırma özelliği entegrasyonu başarıyla tamamlandı.")
logger.info("Veritabanı şemasını güncellemek için 'python add_compression_columns.py' komutunu çalıştırın.")
return 0
else:
logger.error("Sıkıştırma özelliği entegrasyonu sırasında hatalar oluştu.")
return 1
if __name__ == "__main__":
sys.exit(main())