乐闻世界logo
搜索文章和话题

How to permanently add a private key with ssh-add on Ubuntu?

1个答案

1
  1. Generate an SSH Key Pair (if you don't have one yet):
    If you don't have an SSH key pair, you can create a new one by running the following command:

    bash
    ssh-keygen -t rsa -b 4096

    Follow the prompts to complete the key generation process. You can set a passphrase or leave it empty.

  2. Add the Private Key to the SSH Agent:
    To have the SSH key automatically loaded at system startup, add it to the ssh-agent. First, ensure that ssh-agent is running:

    bash
    eval "$(ssh-agent -s)"

    Then, use the ssh-add command to add the private key:

    bash
    ssh-add ~/.ssh/id_rsa

    This assumes your private key file is ~/.ssh/id_rsa. If your key file name or path differs, modify the command accordingly.

  3. Configure the ~/.ssh/config File:
    You can create or edit the ~/.ssh/config file to help manage and automate SSH connection settings. For example, you can specify which private key to use for a specific host:

    bash
    Host example.com IdentityFile ~/.ssh/id_rsa

    This ensures that the specified private key is used every time you connect to example.com.

  4. Make the Key Automatically Load at System Startup:
    To have the private key automatically loaded at each system startup, add the ssh-add command to your .bashrc or .profile file:

    bash
    if [ -z "$(pgrep ssh-agent)" ]; then eval $(ssh-agent -s) ssh-add ~/.ssh/id_rsa fi

    This script checks if ssh-agent is running; if not, it starts ssh-agent and adds your private key.

By following these steps, your SSH private key will be automatically loaded at each login or system startup on Ubuntu, simplifying the SSH connection process. This is particularly useful when managing multiple servers or performing automated deployments.

2024年7月22日 20:48 回复

你的答案