import os import sys try: import boto3 from botocore.client import Config from botocore.exceptions import ClientError except ImportError: print("Error: La biblioteca 'boto3' no está instalada.") print("Por favor, ejecute: pip install boto3") sys.exit(1) # --- CONFIGURACIÓN --- # Puedes establecer estas variables de entorno en la VPS, o pegarlas directamente aquí para probar. R2_ENDPOINT = os.getenv("R2_ENDPOINT", "https://.r2.cloudflarestorage.com") R2_ACCESS_KEY_ID = os.getenv("R2_ACCESS_KEY_ID", "TU_ACCESS_KEY_ID") R2_SECRET_ACCESS_KEY = os.getenv("R2_SECRET_ACCESS_KEY", "TU_SECRET_ACCESS_KEY") R2_BUCKET = os.getenv("R2_BUCKET", "omnioil-backups") print("=" * 60) print("PROBADOR DE CONECTIVIDAD CLOUDFLARE R2") print("=" * 60) print(f"Endpoint: {R2_ENDPOINT}") print(f"Bucket: {R2_BUCKET}") print(f"Access Key ID: {R2_ACCESS_KEY_ID[:8]}... (truncado)") print("=" * 60) # Inicializar cliente de S3 compatible con R2 s3 = boto3.client( service_name='s3', endpoint_url=R2_ENDPOINT, aws_access_key_id=R2_ACCESS_KEY_ID, aws_secret_access_key=R2_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4'), ) # 1. Intentar listar objetos try: print("\n1. Probando conexión y listado de objetos...") response = s3.list_objects_v2(Bucket=R2_BUCKET) print(" [OK] ¡Conexión exitosa al bucket!") if 'Contents' in response: print(" Objetos en el bucket:") for obj in response['Contents']: print(f" - {obj['Key']} ({obj['Size']} bytes)") else: print(" (El bucket está vacío actualmente)") except ClientError as e: error_code = e.response['Error']['Code'] print(f" [ERROR] No se pudo listar el bucket. Código de error: {error_code}") print(f" Detalle: {e}") if error_code in ['AccessDenied', 'Forbidden', 'InvalidAccessKeyId']: print("\n >>> ATENCIÓN: Si configuraste restricción de IP, es muy probable que esta IP esté bloqueada o que las credenciales sean incorrectas.") sys.exit(1) # 2. Intentar subir un archivo de prueba test_filename = "test_connection_file.txt" try: print(f"\n2. Intentando subir archivo de prueba '{test_filename}'...") s3.put_object( Bucket=R2_BUCKET, Key=test_filename, Body=b"Prueba de conexion exitosa desde la VPS a Cloudflare R2", ContentType="text/plain" ) print(" [OK] ¡Archivo subido correctamente!") except Exception as e: print(f" [ERROR] Falló la subida del archivo de prueba: {e}") sys.exit(1) # 3. Intentar eliminar el archivo de prueba try: print(f"\n3. Intentando limpiar y eliminar '{test_filename}'...") s3.delete_object(Bucket=R2_BUCKET, Key=test_filename) print(" [OK] ¡Archivo de prueba eliminado con éxito!") print("\n=== PRUEBA DE CONECTIVIDAD Y PERMISOS DE R2 COMPLETA CON ÉXITO ===") except Exception as e: print(f" [ERROR] No se pudo eliminar el archivo de prueba: {e}") sys.exit(1)