Create and Upload SSH keys

SSH is an integral part of cloud, network, and system administration as it provides secure encrypted communications between two  hosts over an insecure network. Notably, it enables the transfer of files and management of remote servers.

This article will guide you through three essential Bash commands for handling SSH tasks: Generating a new SSH key, uploading the SSH key to a server, and creating an SSH config for the server for automated login.

1. Generate a new SSH key

You can generate a new RSA SSH key pair (public and private) using the following command:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Replace "your_email@example.com" with your choosen "id". The system will prompt you for the key pair's filename (default being id_rsa), and an optional passphrase for private key security.

2. Upload the SSH key to a server

The next step involves copying your public key (id_rsa.pub) to the remote server's authorized_keys file:

ssh-copy-id -i ~/.ssh/id_rsa.pub user@server

Replace user with your username and server with the server's hostname or IP address. This lets the server authenticate your future connections using your private key.

3. Create an SSH config for automated login

Finally, set up automated login with the ~/.ssh/config file:

cat <<EOF >> ~/.ssh/config
Host server
   HostName server
   User user
   IdentityFile ~/.ssh/id_rsa
EOF

Replace server and user with your actual values. The configuration file for SSH, the ~/.ssh/config file, directs your system to use your chosen identity file (id_rsa) for server authentication.

Wrapping Up

Securing your .ssh directory and the id_rsa and id_rsa.pub files is crucial. Use the following commands to restrict permissions:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

In this way, your Bash commands can assist you with SSH tasks, including generating a new SSH key, uploading it to a server, and setting up automated logins. Secure communication between hosts has never been simpler with these steps in place.