Linux eval ssh agent

How to use ssh-agent for authentication on Linux / Unix

Table of contents

Using ssh-agent command for non-interactive authentication

Open the terminal and type the following command:
$ eval $(ssh-agent)
$ eval `ssh-agent`
You will see the PID of the ssh-agent as follows on screen:

Use ssh-add to add the private key passphrase to ssh-agent

Now our ssh-agent is running, and you need to provide the passphrase for your ssh private keys. For example, run the ssh-add command:
$ ssh-add
Type the passphrase:

By default it adds the files

/.ssh/id_ed25519_sk. But, we state another private key file as follows:
$ ssh-add

Setting up a maximum lifetime for identities/private keys

Pass the -t life to the ssh-add command to s a maximum lifetime when adding identities to an agent. The lifetime may be specified in seconds or in a time format specified in sshd_config file:
$ ssh-add -t 1800 # 1800 seconds
$ ssh-add -t 45m # 45 minutes
$ ssh-add -t 3h42 # 3 hours 42 minutes
Remember, you can configure GNOME/KDE or macOS desktop to run ssh-agent and unlock keys automatically when log-in. For example:

Use ssh-agent for ssh/sftp/scp command authentication

Once you add the private key (or keys) to the ssh-agent, all you have to do is use ssh, sftp, scp, and all other ssh commands. For instance, I will execute the ssh command for my FreeBSD backup server:
$ ssh user@server
$ ssh user@hostname_or_ip
$ scp file.doc vivek@server1.cyberciti.biz:

/Documents/
# State the private key for public key authentication #
$ ssh -i

/.ssh/aws-web-servers ec2-user@rhel8-web-server
$ ssh -i

/.ssh/linode-nixcraft-servers vivek@1.2.3.4
$ ssh vivek@192.168.2.236

The ssh-agent for non-interactive ssh authentication in action on my Ubuntu Linux desktop

How to list my private keys cached by ssh-agent

Run the following command to lists fingerprints of all identities/private keys:
$ ssh-add -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Want to see list all public key parameters of all identities:
$ ssh-add -L

Deleting all cached ssh-agent private keys

Pass the -D option to the ssh-add command:
$ ssh-add -D
You will see confirmation as follows on screen:

Conclusion

In this quick tutorial, you learned how to use ssh-agent for authentication and list/clear out private keys from memory when needed under Linux or Unix-like systems. For further information, see OpenSSH documentation or use the man command to read man pages:
$ man ssh-agent
$ man ssh-add
$ man ssh
$ man sftp
$ man scp
$ man sshd_config

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Управление ключами SSH с помощью агента

Материал из Xgu.ru

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.

Источник

Читайте также:  Usb modeswitch для windows
Оцените статью