DEV Community

Cover image for How to Generate an SSH Key on macOS for Accessing a VPS Ubuntu
Parsa Roshani
Parsa Roshani

Posted on

How to Generate an SSH Key on macOS for Accessing a VPS Ubuntu

Step 1: Generate an SSH Key

  1. Open the Terminal on your macOS.
  2. Run the following command to generate a new SSH key:
   ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter fullscreen mode Exit fullscreen mode
  • -t rsa: Specifies the type of key (RSA).
  • -b 4096: Defines the key size (4096 bits).
  • -C "your_email@example.com": Adds a comment to the key (usually your email).
    1. When prompted, specify the file name for the key. Press Enter to use the default path.
    2. You can add a passphrase to the key for extra security or leave it blank by pressing Enter.

Step 2: View the Public Key

Your public SSH key is stored at:

~/.ssh/id_rsa.pub
Enter fullscreen mode Exit fullscreen mode

To view the public key, use:

cat ~/.ssh/id_rsa.pub
Enter fullscreen mode Exit fullscreen mode

Copy the public key.


Step 3: Add the Public Key to Your VPS

  1. Connect to your VPS manually using a password:
   ssh username@server_ip
Enter fullscreen mode Exit fullscreen mode
  1. On the VPS, open or create the authorized_keys file:
   mkdir -p ~/.ssh
   nano ~/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode
  1. Paste the public key you copied into the file.
  2. Save and exit the editor.
  3. Set the appropriate permissions for the file and directory:
   chmod 600 ~/.ssh/authorized_keys
   chmod 700 ~/.ssh
Enter fullscreen mode Exit fullscreen mode

Step 4: Test Password-Free Access

On your macOS, test the SSH connection without a password:

ssh username@server_ip
Enter fullscreen mode Exit fullscreen mode

Step 5: Optional Configuration

To simplify SSH access, you can configure the ~/.ssh/config file:

nano ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode

Add the following:

Host my-vps
    HostName server_ip
    User username
    IdentityFile ~/.ssh/id_rsa
Enter fullscreen mode Exit fullscreen mode

Now you can connect using:

ssh my-vps
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you can securely and conveniently access your VPS without needing to enter a password every time. This method enhances both security and efficiency in server management.

Top comments (0)