rsync between hosts using commands embedded into authorized_keys (ssh-keys)

I routinely used to transfer data between systems using rsync. Since I wanted the communication to be secure I used ssh-keys, I noticed that my trick for using a command in the key isn't terribly well documented, so here is how I do it...

Goal: Keep /opt/before on machine B in sync with /opt/after on machine A.

On machine A, create an ssh key for this


$ ssh-keygen -f id_rsync

Copy id_rsync.pub from machine A to machine B, create an rsync account for the transfer, place the key into the authorized_keys file on machine B. Add a command to the key so we can transfer the command sent from machine A. We'll be taking the captured command and replacing it in the key later. This way we don't have to work out the options that rsync wants at the receiving end.

~rsync/.ssh/authorized_keys on machine B


command="echo `date` $SSH_ORIGINAL_COMMAND >> ssh.log && exec $SSH_ORIGINAL_COMMAND" ssh-rsa AAAAnotmyrealkeysadly thomas@machineA

Now on machine A


$ rsync -e 'ssh -i id_rsync' -avc /opt/before/ rsync@machineB:/opt/after
./
auth.conf
hiera.yaml -> /etc/hiera.yaml
puppet.conf
modules/

sent 5258 bytes received 61 bytes 3546.00 bytes/sec
total size is 5001 speedup is 0.94

Now on machine B we can look at the contents of the ssh.log file in ~rsync's home directory.

Tue Dec 3 01:34:41 EST 2013 rsync --server -vlogDtprce.iLsf . /opt/after

Cool, now we just have to take that rsync --server part and put that in our key.

~rsync/.ssh/authorized_keys on machine B


command="rsync --server -vlogDtprce.iLsf . /opt/after" ssh-rsa AAAAnotmyrealkeysadly thomas@machineA

Additionally we can add a from clause to make sure that only machineA can send to machineB using this key.

~rsync/.ssh/authorized_keys on machine B


command="rsync --server -vlogDtprce.iLsf . /opt/after",from="machineA" ssh-rsa AAAAnotmyrealkeysadly thomas@machineA

Incidently, if you use this syntax in the keys, you'll get this helpful message in /var/log/secure when you try from the wrong machine...

Dec 3 01:42:57 machineB sshd[22717]: Authentication tried for rsync with correct key but not from a permitted host (host=machineC, ip=192.168.100.1).

About the Author...

Slides from LISA 2019 Linux systems troubleshooting #LISA2019 https://t.co/D4dMKflK6R Tue Oct 29 05:59:30 +0000 2019

https://t.co/AGeihMALAv configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! https://t.co/IYpRyEb7Hz #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX https://t.co/v3An0miW9L Fri Jul 12 15:06:49 +0000 2019

HTML email with plain mailer plugin on Jenkins https://t.co/Z6FSDMDjy8 Thu Jul 11 21:07:25 +0000 2019