====== Ubuntu - RSync - Rsync Files Securely With and Without a Password ======
To automate backups or avoid storing passwords within scripts, etc.
rsync -avz -e ssh [Source File/Folder] --progress username@example.com:/[Destination Directory]
----
===== Generate private/public key pairs =====
mkdir ~/my-ssh-keys
ssh-keygen -t rsa -b 2048 -f ~/my-ssh-keys/mykey -q -P ""
----
===== Place the public key in the authorized_keys file on the remote server =====
cat my-ssh-keys/mykey.pub | ssh cooluser@remote.example.com 'cat >> . ssh/authorized_keys'
cooluser@remote.example.com's password: [Enter your password]
----
===== Set permissions =====
Make sure the .ssh folder and authorized keys have the proper permissions on the remote server:
chmod 0700 ~/.ssh
chmod 0644 ~/.ssh/authorized_keys
----
===== Log into the remote server =====
ssh -i my-ssh-keys/mykey cooluser@remote.example.com
Keep in mind if you don’t have you use the "-i" option if you store your private key as ~/.ssh/id_rsa.
----
===== Security restrict =====
In order to provide a bit of security, we want to restrict this automation by source connection and authorized commands. Edit the .ssh/authorized_keys file:
From:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCWPasgSOp0CxIvp6
kj0f0syDXLl55RAXNMkKz2K6FhYwbDMDIVWBemtKICHmaC5dtLBMSIT
ozO4+CZvM2EdrCBALOnas93zpeMdpexkae3dItq7eTmSCd+AzVJdaRw
lKXIrAgyzhlaHCEbfmbScPR6EEKxKasF9vd4ZaH1nYN8h7DZjmyzEGR
To:
from="source.example.com",command="/usr/bin/cooluser-commands",
no-pty,no-port-forwarding,no-agent-forwarding,
no-X11-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCWPasg
SOp0CxIvp6kj0f0syDXLl55RAXNMkKz2K6FhYwbDMDIVWBemtKICHmaC5dtLBM
SITozO4+CZvM2EdrCBALOnas93zpeMdpexkae3dItq7eTmSCd+AzVJdaRwlKX
----
===== Create a script =====
We need to create the script to ensure only the rsync command is allowed for this user:
sudo vim /usr/bin/cooluser-commands
#!/bin/sh
set $SSH_ORIGINAL_COMMAND
case "$1" in
rsync)
;;
*)
logger -s -t invalid-command -- "Invalid command $@"
exit 1
;;
esac
logger -t invalid-command -- "Running $@"
exec "$@"
----
===== Setting the proper permissions =====
sudo chmod +x /usr/bin/cooluser-commands
sudo chown root:root .ssh/authorized_keys
sudo chmod 0644 .ssh/authorized_keys
----
===== Test it =====
touch testfile.txt
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i my-ssh-keys/mykey" --progress testfile.txt cooluser@remote.example.com:/home/cooluser/