Setting up SSH key-based authentication is not only a secure way to connect to remote servers but also highly convenient, especially for automated tasks like crontab jobs. For instance, if you need to copy files between your local server and a remote server for regular backups, using this method ensures seamless operations without the need for manual password entry.
Step 1: Generate an SSH Key Pair
On your local machine (Linux or macOS), generate a new SSH key pair by running the following command:
Follow the prompts and press Enter to save the key to the default location (~/.ssh/id_rsa
).
Step 2: Install ssh-copy-id on macOS (If Needed)
On macOS, ssh-copy-id
may not be installed by default. You can install it using Homebrew:
Once installed, proceed with copying your public key to the remote server.
Step 3: Copy the Public Key to the Remote Server in Linux
Use the ssh-copy-id
command to copy your public key to the remote server:
If the remote server uses a non-default SSH port, specify it using the -p
flag:
Step 4: Test the Connection
Once the public key is copied, test the connection to the remote server:
For non-default SSH ports, include the -p
flag:
Additional Note: Automating Backups with Crontab
Using key-based authentication is essential for automating tasks like backups. For example, you can use scp
or rsync
in a crontab job to transfer files securely and without interruption. Here’s a simple crontab entry to copy a file from your local server to the remote server:
For non-default ports, modify the command accordingly:
Conclusion
By setting up SSH key-based authentication, you ensure a secure and hassle-free way to connect to your remote servers. This method is particularly useful for automation tasks like backups using crontab, enhancing both security and convenience.