Auto login through SSH and rsync files

Local computer auto connects over SSH to remote and execute rsync command. Local user is root, remote username is backup.
  1. Create private and public certificate key on local host
    ssh-keygen -t dsa -b 1024 -f ssh_key
    
  2. Login to remote host with remote username which will be used for auto login
    cd ~
    if [ ! -d .ssh ]; then mkdir .ssh ; chmod 700 .ssh ; fi
    cd .ssh/
    if [ ! -f authorized_keys ]; then touch authorized_keys ; chmod 600 authorized_keys ; fi
  3. Copy ssh_key.pub from local to remote host to subdir .ssh in remote users home dir
     scp /root/.ssh/ssh_key.pub backup@remotehost:/home/backup/.ssh
  4. Add certificate to authorized_keys file
    cat ssh_key.pub >> authorized_keys
    
  5. Add to begining of authorized_keys file (delimited by space on end)
    from="localhost IP",command="/home/backup/.ssh/validate-rsync.sh"
  6. Create script /home/remoteuser/.ssh/validate-rsync.sh and make it executable
    #!/bin/sh
    logfile="/home/backup/.ssh/validate-rsync.log"
    date >> $logfile
    echo $SSH_ORIGINAL_COMMAND >> $logfile
    
    case "$SSH_ORIGINAL_COMMAND" in
    *\&*)
    echo "Rejected" >> $logfile
    sudo -l >> $logfile
    ;;
    *\;*)
    echo "Rejected" >> $logfile
    sudo -l >> $logfile
    ;;
    sudo\ rsync*)
    $SSH_ORIGINAL_COMMAND
    ;;
    *)
    echo "Rejected" >> $logfile
    sudo -l >> $logfile
    ;;
    esac
    chmod 600 *
    chmod +x validate-rsync.sh
    
  7. Create file /etc/sudoers.d/rsync as root on remote host (file must end with new line)
    backup ALL= NOPASSWD:/usr/bin/rsync
  8. On local host add text to ~/.ssh/config file
    Host remotehost-backup
    Hostname remoteIPorDomain
    IdentityFile /root/.ssh/ssh_key
  9. Test connection on local host running rsync command (no user password required)
    rsync --rsync-path="sudo rsync" -avz -e "ssh -i /root/.ssh/ssh_key" backup@remotehost:/root ./

© 2003-17 iNeta d.o.o. | Koroška cesta 31, SI-4000 Kranj | info@ineta.si | Pravno obvestilo
Powered by BravoCMS