- How to use ssh-agent for authentication on Linux / Unix
- Using ssh-agent command for non-interactive authentication
- Use ssh-add to add the private key passphrase to ssh-agent
- Setting up a maximum lifetime for identities/private keys
- Use ssh-agent for ssh/sftp/scp command authentication
- How to list my private keys cached by ssh-agent
- Deleting all cached ssh-agent private keys
- Conclusion
- Управление ключами SSH с помощью агента
- Материал из Xgu.ru
- Generating a new SSH key and adding it to the ssh-agent
- Help us make these docs great!
- Generating a new SSH key and adding it to the ssh-agent
- Help us make these docs great!
How to use ssh-agent for authentication on Linux / Unix
Tutorial requirements | |
---|---|
Requirements | Linux, macOS, *BSD and Unix-like |
Root privileges | No |
Difficulty | Easy |
Est. reading time | 5m |
|
Данная страница находится в разработке. Эта страница ещё не закончена. Информация, представленная здесь, может оказаться неполной или неверной. |
Если вы считаете, что её стоило бы доработать как можно быстрее, пожалуйста, скажите об этом.
Автор: Игорь Чубин
Короткий URL: ssh-agent
На этой странице описывается что такое ssh-agent, зачем он нужен и как правильно его использовать.
Вводить парольную фразу каждый раз, когда используется ssh не очень удобно. Было бы намного проще ввести ее один раз при входе в систему, сохранить где-нибудь, а затем все время пользоваться. Такую задачу позволяет решить специальная программа — ssh-agent.
ssh-agent хранит секретные ключи и, когда нужно, пользуется ими. Программа (например, ssh), когда ей понадобится воспользоваться секретным ключом, не делает этого сама, а обращается к ssh-agent ‘у, который в свою очередь уже сам пользуется известными только ему данными о секретных ключах. Таким образом, секретные ключи не разглашаются никому, даже программам принадлежащим самому пользователю.
Программу ssh-agent можно использовать двумя разными способами:
В обоих случаях ssh-agent создает файл-сокет с именем /tmp/ssh-XXXXXXXX/agent.ppid, через который осуществляется взаимодействие с агентом. Всем дочерним процессам агент при помощи переменных окружения SSH_AUTH_SOCK (в которой хранится имя файла-сокета) и SSH_AGENT_PID (в которой хранится идентификатор процесс агента) сообщает информацию о том, как с ним можно связаться.
В первом случае агент выдает информацию в виде, удобном для использования командным интерпретатором.
При указании ключа -c агент использует синтаксис C Shell. По умолчанию (и при явном указании ключа -s) используется синтаксис Bourne Shell. Эти переменные следует установить в текущем командном интерпретаторе, поэтому обычно вызов ssh-agent комбинируется с командой eval.
Во втором случае агент экспортирует значения переменных в среду окружения и порождает дочерний процесс, выполняя в нем команду. Достигается аналогичный результат, только при этом порождается дополнительный процесс.
Для того чтобы использовать ssh-agent в системе X Window, нужно добавить строку
eval `ssh-agent -s`; ssh-add %$ ssh-add options file
При вызове без параметров ssh-add сообщает агенту информацию о ключах из файлов identity, id_dsa и id_rsa. При этом программа спрашивает парольную фразу для каждого из ключей (или, если фразы совпадают, всего один раз). Ключ, для которого правильно была введена парольная фраза передается агенту.
Если в качестве аргумента командной строки указан файл, программа сообщает агенту информацию только о том ключе, который находится в файле.
Список известных агенту секретных ключей можно посмотреть той же командой ssh-add с ключом командной строки -l. Команда сообщит и отпечаток для каждого ключа.
Опции командной строки программы ssh-add
- -l — Показать список отпечатков известных агенту ключей
- -L — Показать информацию обо всех открытых ключах, соответствующих секретным ключам, известным ssh-add
- -d — Удалить ключ у агента
- -D — Удалить все ключи у агента
- -x — Заблокировать агента паролем
- -X — Разблокировать агента
Источник
Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key generation
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
If you don’t want to reenter your passphrase every time you use your SSH key, you can add your key to the SSH agent, which manages your SSH keys and remembers your passphrase.
Generating a new SSH key
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
This creates a new SSH key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key,» press Enter. This accepts the default file location.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
First, check to see if your
/.ssh/config file exists in the default location.
If the file doesn’t exist, create the file.
/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.
Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
Note: If you see an error like this
add an additional config line to your Host * section:
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
Ensure the ssh-agent is running. You can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
Insert your hardware security key into your computer.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error invalid format or feature not supported, you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.
When you are prompted, touch the button on your hardware security key.
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
When you are prompted to type a passphrase, press Enter.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Источник
Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key generation
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
If you don’t want to reenter your passphrase every time you use your SSH key, you can add your key to the SSH agent, which manages your SSH keys and remembers your passphrase.
Generating a new SSH key
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
This creates a new SSH key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key,» press Enter. This accepts the default file location.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
First, check to see if your
/.ssh/config file exists in the default location.
If the file doesn’t exist, create the file.
/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.
Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
Note: If you see an error like this
add an additional config line to your Host * section:
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
Ensure the ssh-agent is running. You can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
Insert your hardware security key into your computer.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error invalid format or feature not supported, you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.
When you are prompted, touch the button on your hardware security key.
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
When you are prompted to type a passphrase, press Enter.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Источник