Skip to content

[Actualizado a 9 de noviembre de 2026]

T3c. Rsync🔗

Es un servicio cliente-servidor nativo Gnu/linux y que no existe para Windows... pero algmo podemos hacer.

Gnu/Linux🔗

El formato es rsync origen destino, donde uno de los dos debe ser local.

Ejemplo rsync ~/path_a_dir/www ubuntu@mi-dominio.es:/home/ubuntu/ copiará el directorio www local al directorio del usuario ubuntu remoto.

En Windows🔗

Podemos copiar con scp mediante scp -i key.pem ~/path_a_dir/www ubuntu@mi-dominio.es:/home/ubuntu/, pero scp está "deprecado".

Un pequeño script que realiza la función rsync

rsync.py
import argparse
import sys
import subprocess
from pathlib import Path

# Constantes para la interfaz con códigos ANSI de color
CHECK_OK = "\033[92m[✔]\033[0m"
CROSS_ERR = "\033[91m[❌]\033[0m"


# ==============================================================================
# FASE 1: Comprobar conectividad SSH
# ==============================================================================
def check_ssh_connectivity(remote_host: str) -> bool:
    """Verifica si el servidor SSH remoto responde a una conexión de prueba."""
    print(f"\n[Fase 1] Verificando conectividad SSH con '{remote_host}'...")
    cmd = ["ssh", "-o", "ConnectTimeout=5", remote_host, "echo OK"]
    res = subprocess.run(cmd, capture_output=True, text=True)
    if res.returncode == 0 and "OK" in res.stdout:
        print("  --> Conexión SSH establecida correctamente.")
        return True
    else:
        print(f"  --> Error al conectar por SSH: {res.stderr.strip()}")
        return False


# ==============================================================================
# FASE 2: Comprobar y crear directorio remoto (resolviendo ~)
# ==============================================================================
def ensure_remote_directory(remote_host: str, remote_dir_raw: str) -> str:
    """Resuelve la ruta remota (expande ~ si existe) y crea la carpeta destino si no existe."""
    print(f"\n[Fase 2] Verificando existencia de la ruta destino...")

    # Resolver expansión de tilde (~) o rutas relativas en Linux
    ssh_expand_cmd = ["ssh", remote_host, f"eval echo {remote_dir_raw}"]
    res_expand = subprocess.run(ssh_expand_cmd, capture_output=True, text=True)

    if res_expand.returncode == 0 and res_expand.stdout.strip():
        remote_dir = res_expand.stdout.strip().splitlines()[-1]
    else:
        remote_dir = remote_dir_raw

    print(f"  --> Ruta resuelta: '{remote_dir}'")

    # Verificar si el directorio existe
    check_dir_cmd = ["ssh", remote_host, f"test -d '{remote_dir}'"]
    res_check = subprocess.run(check_dir_cmd)

    if res_check.returncode != 0:
        print(f"  --> El directorio '{remote_dir}' no existe. Creando directorio...")
        mkdir_cmd = ["ssh", remote_host, f"mkdir -p '{remote_dir}'"]
        res_mkdir = subprocess.run(mkdir_cmd, capture_output=True, text=True)
        if res_mkdir.returncode == 0:
            print("  --> Directorio creado con éxito.")
        else:
            print(f"  --> Error al crear directorio remoto: {res_mkdir.stderr.strip()}")
            sys.exit(1)
    else:
        print("  --> El directorio destino existe y está listo.")

    return remote_dir


# ==============================================================================
# FASE 3: Obtener inventario local y remoto
# ==============================================================================
def get_local_inventory(local_dir: str) -> dict:
    """Escanea el directorio local obteniendo tamaño y mtime de los archivos."""
    local_path = Path(local_dir).resolve()
    manifest = {}
    if not local_path.exists():
        print(f"Error: El directorio local '{local_dir}' no existe.")
        sys.exit(1)

    for p in local_path.rglob("*"):
        if p.is_file():
            rel_path = p.relative_to(local_path).as_posix()
            st = p.stat()
            manifest[rel_path] = {"size": st.st_size, "mtime": st.st_mtime}
    return manifest


def get_remote_inventory(remote_host: str, remote_dir: str) -> dict:
    """Obtiene metadatos remotos (tamaño y fecha) usando find en Linux."""
    print(f"\n[Fase 3] Obteniendo inventario de archivos remotos...")
    ssh_cmd = f"test -d '{remote_dir}' && find '{remote_dir}' -type f -printf '%P\\t%s\\t%T@\\n'"
    res = subprocess.run(["ssh", remote_host, ssh_cmd], capture_output=True, text=True)

    manifest = {}
    if res.returncode == 0 and res.stdout.strip():
        for line in res.stdout.strip().split("\n"):
            parts = line.split("\t")
            if len(parts) == 3:
                rel_path, size_str, mtime_str = parts
                manifest[rel_path.replace("\\", "/")] = {
                    "size": int(size_str),
                    "mtime": float(mtime_str),
                }
    print(f"  --> Inventario remoto obtenido: {len(manifest)} archivos en destino.")
    return manifest


# ==============================================================================
# FASE 4: Copia interactiva de archivos y manejo de conflictos
# ==============================================================================
def apply_remote_touch(remote_host: str, remote_file_path: str, local_mtime: float):
    """Establece la marca de tiempo exacta del archivo local en el servidor remoto."""
    touch_cmd = f"touch -c -m -d '@{local_mtime:.6f}' '{remote_file_path}'"
    subprocess.run(["ssh", remote_host, touch_cmd], capture_output=True)


def copy_file_scp(local_base: Path, rel_path: str, remote_host: str, remote_dir: str, target_rel_path: str, local_mtime: float):
    """Copia un archivo por SCP asegurando la creación previa de carpetas y ajustando timestamp."""
    src = local_base / rel_path
    target_dest_path = f"{remote_dir}/{target_rel_path}"

    # Crear subdirectorio si es necesario
    parent_dir = Path(target_rel_path).parent.as_posix()
    if parent_dir != ".":
        subprocess.run(["ssh", remote_host, f"mkdir -p '{remote_dir}/{parent_dir}'"], capture_output=True)

    # SCP y touch
    print(f"  --> Transferiendo: {rel_path} -> {target_rel_path}")
    subprocess.run(["scp", "-q", str(src), f"{remote_host}:{target_dest_path}"], check=True)
    apply_remote_touch(remote_host, target_dest_path, local_mtime)

def decide_sync_actions(local_files: dict, remote_files: dict) -> list:
    """Fase 1: Decisión. Evalúa los archivos y determina qué acción realizar con cada uno."""
    print(f"\n[Fase 1] Evaluando archivos y decidiendo acciones...")

    always_action = None
    always_suffix = "_new"
    sync_plan = []

    for rel_path, l_info in local_files.items():
        r_info = remote_files.get(rel_path)
        action = None
        custom_suffix = None

        if not r_info:
            # Archivo nuevo: Se copia directamente
            action = "s"
        else:
            diff_mtime = l_info["mtime"] - r_info["mtime"]
            size_diff = l_info["size"] != r_info["size"]

            same_size = not size_diff
            same_time = abs(diff_mtime) <= 2.0

            if same_size and same_time:
                # Mismo tamaño y fecha: Se omite
                action = "i"
            elif diff_mtime > 2.0:
                # El local es más moderno: Se copia directamente
                action = "s"
            else:
                # Resto de casos (Conflictos): Preguntar al usuario
                if always_action:
                    action = always_action
                    custom_suffix = always_suffix
                else:
                    print(f"\n[!] Conflicto detectado en: '{rel_path}'")
                    print(f"    Local  -> Tamaño: {l_info['size']}B | mtime: {l_info['mtime']:.2f}")
                    print(f"    Remoto -> Tamaño: {r_info['size']}B | mtime: {r_info['mtime']:.2f}")

                    while True:
                        opt = input("    Seleccione [i]gnorar / [s]obreescribir / [r]enombrar / [I]gnorar siempre / [S]obreescribir siempre / [R]enombrar siempre: ").strip()
                        if opt in ["i", "s", "r", "I", "S", "R"]:
                            break
                        print("    Opción inválida. Intente de nuevo.")

                    if opt in ["I", "S", "R"]:
                        always_action = opt.lower()
                        action = always_action
                        if opt == "R":
                            suf = input("    Sufijo para renombrar siempre (por defecto '_new'): ").strip()
                            always_suffix = suf if suf else "_new"
                            custom_suffix = always_suffix
                    else:
                        action = opt
                        if opt == "r":
                            suf = input("    Sufijo para renombrar (por defecto '_new'): ").strip()
                            custom_suffix = suf if suf else "_new"

        # Calcular la ruta de destino (target_path) si aplica rename
        target_path = rel_path
        if action == "r":
            p = Path(rel_path)
            suf = custom_suffix if custom_suffix else "_new"
            target_path = (p.parent / f"{p.stem}{suf}{p.suffix}").as_posix()

        # Guardar la decisión en el plan de sincronización
        sync_plan.append({
            "rel_path": rel_path,
            "target_path": target_path,
            "action": action,
            "l_info": l_info
        })

    return sync_plan


def execute_sync_actions(local_dir: str, remote_host: str, remote_dir: str, sync_plan: list) -> list:
    """Fase 2: Ejecución. Aplica las operaciones seleccionadas en el plan."""
    print(f"\n[Fase 2] Ejecutando transferencias y operaciones...")
    local_base = Path(local_dir).resolve()
    transferred_targets = []

    for item in sync_plan:
        action = item["action"]
        rel_path = item["rel_path"]
        target_path = item["target_path"]
        l_info = item["l_info"]

        if action == "i":
            print(f"  --> Omitido / Ignorado: {rel_path}")
            continue

        # Aquí se ejecuta la operación seleccionada (copia por SCP)
        copy_file_scp(local_base, rel_path, remote_host, remote_dir, target_path, l_info["mtime"])
        transferred_targets.append(target_path)

    return transferred_targets


def sync_files_interactive(local_dir: str, remote_host: str, remote_dir: str, local_files: dict, remote_files: dict) -> list:
    """Función principal que coordina la fase de decisión y la fase de ejecución."""
    # 1. Fase de decisión
    plan = decide_sync_actions(local_files, remote_files)

    # 2. Fase de ejecución
    transferred_targets = execute_sync_actions(local_dir, remote_host, remote_dir, plan)

    return transferred_targets


# ==============================================================================
# FASE 5: Verificación post-sincronización y reporte
# ==============================================================================
def verify_synchronization(local_dir: str, remote_host: str, remote_dir: str, local_files: dict):
    """Verifica que todos los archivos transferidos coincidan en tamaño y fecha en remoto."""
    print(f"\n[Fase 5] Verificando sincronización y generando reporte final...")
    remote_files = get_remote_inventory(remote_host, remote_dir)

    print("\n" + "=" * 60)
    print(" REPORTE DE SINCRONIZACIÓN")
    print("=" * 60)

    for rel_path, l_info in local_files.items():
        r_info = remote_files.get(rel_path)
        if not r_info:
            print(f"{CROSS_ERR} {rel_path} (El archivo no existe en remoto)")
            continue

        size_ok = l_info["size"] == r_info["size"]
        mtime_ok = abs(l_info["mtime"] - r_info["mtime"]) <= 2.0

        if size_ok and mtime_ok:
            print(f"{CHECK_OK} {rel_path}")
        else:
            reasons = []
            if not size_ok:
                reasons.append(f"Tamaño distinto (L: {l_info['size']}B vs R: {r_info['size']}B)")
            if not mtime_ok:
                reasons.append(f"Fecha distinta (dif: {l_info['mtime'] - r_info['mtime']:+.2f}s)")
            print(f"{CROSS_ERR} {rel_path} -> {', '.join(reasons)}")


# ==============================================================================
# MÉTODO PRINCIPAL (MAIN)
# ==============================================================================
def main():
    parser = argparse.ArgumentParser(
        description="Simulador interactivo de rsync de Windows a Linux en 5 fases."
    )
    parser.add_argument("local_dir", help="Directorio origen local en Windows")
    parser.add_argument("remote_target", help="Destino SSH (ejemplo: usuario@host:~/backup)")

    args = parser.parse_args()

    if ":" not in args.remote_target:
        print("Error: El parámetro de destino debe tener el formato 'usuario@host:ruta'")
        sys.exit(1)

    remote_host, remote_dir_raw = args.remote_target.split(":", 1)

    # Fase 1: Conectividad SSH
    if not check_ssh_connectivity(remote_host):
        sys.exit(1)

    # Fase 2: Comprobar/crear directorio destino
    remote_dir = ensure_remote_directory(remote_host, remote_dir_raw)

    # Fase 3: Inventarios
    local_files = get_local_inventory(args.local_dir)
    remote_files = get_remote_inventory(remote_host, remote_dir)

    # Fase 4: Copia interactiva
    sync_files_interactive(args.local_dir, remote_host, remote_dir, local_files, remote_files)

    # Fase 5: Verificación final
    verify_synchronization(args.local_dir, remote_host, remote_dir, local_files)


if __name__ == "__main__":
    main()