Automating SFTP authentication with SSH keys

I spun up a VPS recently and needed to pull files down via SFTP. I automated this process by using SSH keys and a BASH script.

First, if you haven’t already, generate a public and private SSH key pair.

$ sudo mkdir ~/.ssh
$ ssh-keygen -t rsa

Next, dump the contents of the ~/.ssh/ file and copy them.

cat ~/.ssh/

Or, if you’re on OSX, you can dump the contents directly into the clipboard.

cat ~/.ssh/ | pbcopy

Using an SFTP client (like FileZilla, Cyberduck, or Transmit), create an ~/.ssh/authorized_keys file on the SFTP server. Paste the public key you just copied into that file and save it.

Now, you should be able to download files from the server without being prompted for a password.

$ sftp -r -P [port] [user]@[ip]:/directory/to/download/from/filename* /destination/directory/here