Start ssh-agent and Add Your Key

If you’ve already set up SSH key-based authentication with a passphrase for connecting to the remote server, you can use rsync along with ssh-agent to handle the passphrase for you. Here’s a step-by-step guide to get this working:

Step 1: Start ssh-agent and Add Your Key

The ssh-agent will keep your SSH key unlocked for the duration of your session, so you won’t need to enter the passphrase each time you use rsync.

1. Open a terminal.

2. Start the ssh-agent:

eval "$(ssh-agent -s)"

3. Add your SSH key to the agent. This will prompt you for the passphrase one time:

ssh-add /path/to/your/private_key

Replace /path/to/your/private_key with the actual path to your SSH private key file (usually ~/.ssh/id_rsa or ~/.ssh/id_ed25519).

Step 2: Use rsync to Sync Files

Now that ssh-agent is managing your key, you can use rsync without having to enter the passphrase each time.

The basic syntax for rsync to a remote server is as follows:

rsync -avz /local/directory/ user@remote_host:/remote/directory/

• Options:

• -a: Archive mode, which preserves file permissions, timestamps, and symlinks.

• -v: Verbose, to show detailed output.

• -z: Compresses data during the transfer for faster sync.

Example Command

Assuming your local directory is /var/www/html and you want to sync it to /var/www/html on the remote server:

rsync -avz /var/www/html/ user@remote_host:/var/www/html/

Replace user@remote_host with your actual username and remote server address.

Step 3: Automate with a Script (Optional)

If you need to run rsync regularly, you can create a script and schedule it with cron:

1. Create a script:

nano ~/sync_script.sh

2. Add the rsync command:

#!/bin/bash

rsync -avz /local/directory/ user@remote_host:/remote/directory/

3. Make the script executable:

chmod +x ~/sync_script.sh

4. Schedule it with cron:

Open your cron file:

crontab -e

Add a line to schedule the sync (e.g., every night at 2 a.m.):

0 2 * * * ~/sync_script.sh

This setup will use ssh-agent to avoid repeatedly asking for the passphrase and allow your script to run automatically at scheduled times.