Linux add ssh key to git

4.3 Git on the Server — Generating Your SSH Public Key

Many Git servers authenticate using SSH public keys. In order to provide a public key, each user in your system must generate one if they don’t already have one. This process is similar across all operating systems. First, you should check to make sure you don’t already have a key. By default, a user’s SSH keys are stored in that user’s ~/.ssh directory. You can easily check to see if you have a key already by going to that directory and listing the contents:

$ cd ~/.ssh $ ls authorized_keys2 id_dsa known_hosts config id_dsa.pub

You’re looking for a pair of files named something like id_dsa or id_rsa and a matching file with a .pub extension. The .pub file is your public key, and the other file is the corresponding private key. If you don’t have these files (or you don’t even have a .ssh directory), you can create them by running a program called ssh-keygen , which is provided with the SSH package on Linux/macOS systems and comes with Git for Windows:

$ ssh-keygen -o Generating public/private rsa key pair. Enter file in which to save the key (/home/schacon/.ssh/id_rsa): Created directory '/home/schacon/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/schacon/.ssh/id_rsa. Your public key has been saved in /home/schacon/.ssh/id_rsa.pub. The key fingerprint is: d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local

First it confirms where you want to save the key ( .ssh/id_rsa ), and then it asks twice for a passphrase, which you can leave empty if you don’t want to type a password when you use the key. However, if you do use a password, make sure to add the -o option; it saves the private key in a format that is more resistant to brute-force password cracking than is the default format. You can also use the ssh-agent tool to prevent having to enter the password each time.

Now, each user that does this has to send their public key to you or whoever is administrating the Git server (assuming you’re using an SSH server setup that requires public keys). All they have to do is copy the contents of the .pub file and email it. The public keys look something like this:

$ cat ~/.ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3 Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx NrRFi9wrf+M7Q== schacon@mylaptop.local

Источник

Linux add ssh key to git

  • Top developer relations trends for building stronger teams Learn about enterprise trends for optimizing software engineering practices, including developer relations, API use, community .
  • 5 noteworthy challenges of automotive software development Modern cars are loaded with technology, but creating in-vehicle applications isn’t always a cakewalk. Here are five unique .
  • New AWS service targets data security, genAI feature to come The cloud provider’s new service helps employees within organizations be more productive while securing their work. The vendor .
  • The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
  • Retail companies gain DORA metrics ROI from specialist tools DORA metrics and other measures of engineering efficiency are popping up in add-ons to existing DevOps tools. But third-party .
  • Scrum master certification exam questions and answers Are you ready for the Scrum master certification exam? Test yourself on these 10 tough Scrum master exam questions and answers.
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
  • Deploy a low-latency app with AWS Local Zones in 5 steps Once you decide AWS Local Zones are right for your application, it’s time for deployment. Follow along in this step-by-step video.
  • The history, evolution and current state of SIEM SIEM met the need for a security tool that could pinpoint threats in real time. But new threats mean that the next evolution of .
  • Chainalysis observes sharp rise in ransomware payments The rise in total ransomware payments so far this year is a reversal of the decline Chainalysis saw in 2022, when payments fell .
  • Threat actors forged Windows driver signatures via loophole Threat actors bypassed Microsoft’s driver signing policy using a technical loophole and signature timestamp forging tools .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Кали линукс установить на виндовс

Источник

Создание нового ключа SSH и его добавление в ssh-agent

После проверки наличия существующих ключей SSH можно создать ключ SSH для проверки подлинности, а затем добавить его к агенту SSH.

Сведения о парольных фразах ключа SSH

Вы можете получать доступ к данным в репозиториях и записывать их в GitHub.com с помощью SSH (протокол Secure Shell). При подключении через SSH проверка подлинности выполняется с помощью файла закрытого ключа на локальном компьютере. Дополнительные сведения см. в разделе Сведения о протоколе SSH.

При создании ключа SSH можно добавить парольную фразу для расширенной защиты ключа. При использовании ключа необходимо ввести парольную фразу. Если ключ имеет парольную фразу, и вы не хотите вводить парольную фразу при каждом использовании ключа, можно добавить ключ в агент SSH. Агент SSH управляет ключами SSH и запоминает парольную фразу.

Если у вас еще нет ключа SSH, необходимо создать новый ключ SSH для проверки подлинности. Если вы не уверены, есть ли у вас ключ SSH, можно проверить наличие существующих ключей. Дополнительные сведения см. в разделе Проверка наличия существующих ключей SSH.

Чтобы использовать аппаратный ключ безопасности для проверки подлинности в GitHub, необходимо создать новый ключ SSH для аппаратного ключа безопасности. При проверке подлинности с помощью пары ключей необходимо подключить аппаратный ключ безопасности к компьютеру. Дополнительные сведения см. в заметках о выпуске OpenSSH 8.2.

Создание нового ключа SSH

Вы можете создать новый ключ SSH на локальном компьютере. После создания ключа вы можете добавить открытый ключ в учетную запись GitHub.com, чтобы включить проверку подлинности для операций Git по протоколу SSH.

Примечание. GitHub улучшили безопасность за счет удаления старых небезопасных типов ключей 15 марта 2022 г.

Читайте также:  Copy file to same directory linux

По состоянию на эту дату ключи DSA ( ssh-dss ) больше не поддерживаются. Вы не можете добавить новые ключи DSA в личную учетную запись в GitHub.com.

Ключи RSA ( ssh-rsa ) с valid_after до 2 ноября 2021 г. могут продолжать использовать любой алгоритм подписи. Ключи RSA, созданные после этой даты, должны использовать алгоритм подписи SHA-2. Для использования сигнатур SHA-2 может потребоваться обновить некоторые старые клиенты.

  1. Откройте Терминал Терминал GIT Bash .
  2. Вставьте приведенный ниже текст, указав свой адрес электронной почты GitHub.
ssh-keygen -t ed25519 -C "your_email@example.com"

Примечание. Если вы используете устаревшую систему, которая не поддерживает алгоритм Ed25519, используйте следующую команду:

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

В результате будет создан новый ключ SSH, где в качестве метки будет использоваться указанный адрес электронной почты.

> Generating public/private ALGORITHM key pair.

При появлении запроса «Ввести файл, в котором нужно сохранить ключ», можно нажать клавишу ВВОД , чтобы принять расположение файла по умолчанию. Обратите внимание, что если вы создали ключи SSH ранее, ssh-keygen может попросить вас переписать другой ключ. В этом случае рекомендуется создать ключ SSH с пользовательским именем. Для этого введите расположение файла по умолчанию и замените id_ssh_keyname именем пользовательского ключа.

> Enter a file in which to save the key (/Users/YOU/.ssh/id_ALGORITHM): [Press enter]
> Enter a file in which to save the key (/c/Users/YOU/.ssh/id_ALGORITHM):[Press enter]
> Enter a file in which to save the key (/home/YOU/.ssh/ALGORITHM):[Press enter]
> Enter passphrase (empty for no passphrase): [Type a passphrase] > Enter same passphrase again: [Type passphrase again]

Добавление ключа SSH в ssh-agent

Перед добавлением нового ключа SSH в ssh-agent для управления ключами необходимо проверить наличие существующих ключей SSH и создать новый ключ SSH. При добавлении ключа SSH в агент используйте команду macOS ssh-add по умолчанию, а не приложение, установленное macports, homebrew или другим внешним источником.

$ eval "$(ssh-agent -s)" > Agent pid 59566
$ open ~/.ssh/config > The file /Users/YOU/.ssh/config does not exist.
Host github.com AddKeysToAgent yes UseKeychain yes IdentityFile ~/.ssh/id_ed25519 
  • Если вы решили не добавлять парольную фразу к ключу, следует опустить строку UseKeychain .
  • Если появится сообщение об ошибке Bad configuration option: usekeychain , добавьте дополнительную строку в раздел конфигурации Host *.github.com .
Host github.com IgnoreUnknown UseKeychain 
ssh-add --apple-use-keychain ~/.ssh/id_ed25519

Примечание: Параметр —apple-use-keychain сохраняет парольную фразу в связка ключей при добавлении ключа SSH в SSH-agent. Если вы решили не добавлять парольную фразу в ключ, выполните команду без параметра —apple-use-keychain . Параметр —apple-use-keychain находится в стандартной версии ssh-add Apple . В версиях MacOS до Monterey (12.0) —apple-use-keychain флаги и —apple-load-keychain использовали синтаксис -K и -A соответственно. Если у вас не установлена стандартная версия ssh-add Apple, может появись сообщение об ошибке. Дополнительные сведения см. в разделе Error: ssh-add: illegal option — K. Если вам по-прежнему будет предложено ввести парольную фразу, может потребоваться добавить команду в ~/.zshrc файл (или ~/.bashrc файл для bash).

Если у вас установлено приложение GitHub Desktop, его можно использовать для клонирования репозиториев, не прибегая к ключам SSH.

    Убедитесь, что ssh-agent запущен. Можно воспользоваться инструкциями по автоматическому запуску агента в разделе Работа с парольными фразами ключа SSH или запустить его вручную:

# start the ssh-agent in the background $ eval "$(ssh-agent -s)" > Agent pid 59566
$ eval "$(ssh-agent -s)" > Agent pid 59566

Создание нового ключа SSH для аппаратного ключа безопасности

В macOS или Linux перед созданием нового ключа SSH может потребоваться обновить клиент SSH или установить новый клиент SSH. Дополнительные сведения см. в разделе Ошибка: неизвестный тип ключа.

  1. Вставьте аппаратный ключ безопасности в компьютер.
  2. Откройте Терминал Терминал GIT Bash .
  3. Вставьте приведенный ниже текст, указав адрес электронной почты своей учетной записи GitHub.
ssh-keygen -t ed25519-sk -C "YOUR_EMAIL"

Примечание. Если команда завершается ошибкой invalid format или feature not supported, , возможно, используется аппаратный ключ безопасности, который не поддерживает алгоритм Ed25519. Введите приведенную ниже команду.

ssh-keygen -t ecdsa-sk -C "your_email@example.com"
> Enter a file in which to save the key (/Users/YOU/.ssh/id_ed25519_sk): [Press enter]
> Enter a file in which to save the key (/c/Users/YOU/.ssh/id_ed25519_sk):[Press enter]
> Enter a file in which to save the key (/home/YOU/.ssh/id_ed25519_sk):[Press enter]
> Enter passphrase (empty for no passphrase): [Type a passphrase] > Enter same passphrase again: [Type passphrase again]

Источник

Оцените статью
Adblock
detector