To rsync files to a remote server with a password in a bash script, you can use sshpass to provide the password non-interactively.

1. Install sshpass (if not already installed):

Code

<em># For Debian/Ubuntu</em><br>sudo apt-get install sshpass<br><br><em># For CentOS/RHEL</em><br>sudo yum install sshpass

2. Create the bash script:

Code

<em>#!/bin/bash</em><br><br><em># Define variables</em><br>SOURCE_PATH="/path/to/local/directory/"  <em># Local source directory</em><br>REMOTE_USER="remote_username"           <em># Remote username</em><br>REMOTE_HOST="remote_server_ip_or_hostname" <em># Remote server IP or hostname</em><br>REMOTE_PATH="/path/to/remote/directory/" <em># Remote destination directory</em><br>SSH_PASSWORD="your_remote_password"     <em># Remote server password</em><br><br><em># Perform rsync with sshpass</em><br>sshpass -p "$SSH_PASSWORD" rsync -avz --progress "$SOURCE_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"<br><br><em># Check the exit status of rsync</em><br>if [ $? -eq 0 ]; then<br>    echo "rsync completed successfully."<br>else<br>    echo "rsync encountered an error."<br>fi

Explanation:

  • #!/bin/bash: Specifies the interpreter for the script.
  • SOURCE_PATHREMOTE_USERREMOTE_HOSTREMOTE_PATHSSH_PASSWORD: These variables store the necessary information for the rsync operation. Replace the placeholder values with your actual details.
  • sshpass -p "$SSH_PASSWORD": This command provides the password to ssh (which rsync uses for remote connections) non-interactively. Caution: Storing passwords directly in scripts is generally not recommended for security reasons. Consider using SSH keys for better security in production environments.
  • rsync -avz --progress "$SOURCE_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH": This is the rsync command itself.
    • -a: Archive mode, which preserves permissions, ownership, timestamps, and other attributes.
    • -v: Verbose output, showing details of the transfer.
    • -z: Compresses file data during transfer, which can speed up transfers over slow connections.
    • --progress: Displays a progress bar during the transfer.
    • "$SOURCE_PATH": The local directory to be synchronized.
    • "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH": The remote destination, specifying the username, hostname, and target directory.
  • if [ $? -eq 0 ]; then ... else ... fi: This block checks the exit status of the rsync command. An exit status of 0 indicates success, while any other value indicates an error.

3. Make the script executable:

Code

chmod +x your_script_name.sh

4. Run the script:

Code

./your_script_name.sh

Leave a Reply