Configuring secure *nix SSH automated jobs with passphrase-less keys

Phew what a mouthful!

nn

So, you want to run some automated SSH/SCP jobs (say from another script or from the crontab) but you don’t want to use a passphrase-less SSH key? Here are instructions to help!

nn

    n

  1. n

    These instructions assume that you have the SSH package installed on your local machine. I believe its pretty much standard on all distros. If not, consult your package manager documentation to download and install it. For Debian/Raspbian/Ubuntu, the command is:

    nn

    sudo apt-get install ssh

    n

  2. n

nn

(At least, I am pretty sure that is the correct package name.)

nn

    n

  1. n

    Generate your SSH key on your local machine.

    nn

    ssh-keygen -t rsa

    n

  2. n

nn

Your new SSH private key will be stored at /home/$user/.ssh/id_rsa. The public key will be in the same directory and called /home/$user/.ssh/id_rsa.pub.

nn

    n

  1. n

    Copy the public key to the remote machine.

    nn

    ssh-copy-id -i /home/$user/.ssh/id_rsa.pub [email protected]$host

    n

  2. n

  3. n

    Install the keychain package.

    nn

    sudo apt-get install keychain

    n

  4. n

  5. n

    Add the following lines to your code before your SSH command.

    nn

    /usr/bin/keychain $HOME/.ssh/id_dsan source $HOME/.keychain/$HOSTNAME-sh

    n

  6. n

nn

These should be written to be executed as shell commands. In Perl, they would be written like this:

nn

my $keychainCommand = "/usr/bin/keychain ~/.ssh/id_rsa";nmy $environmentConfigCommand = "source ~/.keychain/raspberrypi-sh"; nmy $scpCommand = "scp ./boincstatus.txt [email protected]:~/public_html/boinc";nnsystem("bash -c '$keychainCommand; $environmentConfigCommand; $scpCommand'");n

nn

I needed to add the bash -c because the source command is only available by bash. The default interpreter in Debian is /bin/dash shell, which does not have the source command.

nn

The detailed explanation can be found in my subsequent post.

nn

You can also add these to your shell profile so that any SSH commands you manually execute in your terminal will use your SSH keys and not require a passphrase. In Debian/Raspbian/Ubunutu world, your profile is ~/.bashrc. Assuming that you use bash, of course.

nn

Thanks to NixCraft for providing this information.

Leave a Reply

Your email address will not be published. Required fields are marked *