как создать ssh key github linux

Доступ к bitbucket и github по ssh ключам

Если попытка склонировать любой приватный репозиторий с bitbucket или github по ssh вызывает ошибку вида:

То это значит, что вы не прошли авторизацию по ssh-ключам. Тут 2 варианта:

Если ключи у вас уже есть, то читайте сразу как добавить ssh ключ на github или добавить ssh ключ на bitbucket.

Рассмотрим подробнее как 1. создать ssh-ключи на linux (ubuntu) и добавить ssh ключи на 2. github и 3. bitbucket.

Генерация ssh-ключей

Для генерации ssh-ключа выполняем следующие команды:

После этого будет предложено ввести имя файла с ключами, либо если имя файла не указать, ключи будут созданы в файле id_rsa. Задаём имя файла с ключами, например, как «git_rsa«. Таким образом мы будем знать, что этот ssh-ключ используется конкретно для git-авторизации. Хотя, никто не запрещает использовать один и тот же ключ id_rsa. Ключи будут храниться в домашней директории пользователя

На запрос о установке пароля на связку ключей можно нажать enter, т.е. оставить пароль пустым (это безопасно). Теперь в каталоге

/.ssh появились 2 файла ключа:

По умолчанию при подключении к серверу для ssh-авторизации используется ключ с именем id_rsa. Мы это обойдём. Чтобы не указывать имя нужного нам ключа (git_rsa) при каждом подключении к серверу, отредактируйте файл

/.ssh/config (если файла ещё нет, создайте), добавьте содержимое для идентификации bitbucket-хоста и github:

Всё, на нашем комьютере или сервере (смотря где создавали ключи) нужные ключи созданы. Остаётся сообщить (добавить) наш публичный ключ туда, где мы будем проходить авторизацию, т.е. на github и bitbucket.

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

В свежем интерфейсе github:

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

В форме добавления ключа указываем title (это название ключа, вводится для удобства, не на что не влияет) и key (это сам ключ, т.е. вставляем сюда всё содержимое файла

/.ssh/git_rsa.pub). Нажимаем Add key.

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

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Теперь вы можете клонировать свои приватные репозитории по ssh (git@github) без ввода пароля.

На что стоит обратить внимание если ssh-авторизация по ключу все еще не работает:

«Warning: Permanently added the RSA host key for IP address ‘2406:da. e9:9f55’ to the list of known hosts.
Permission denied (publickey).»

Что еще нужно, чтобы пул/пуш заработал по ssh. Я уже в депрессии полнейшей!)) Может для доступа к самому репо на битбакете отдельные ключи нужно добавлять? Типа, к аккаунту на битбаккете подключается, а к репе уже нет?

Amati2007, с виду вы все делаете верно!
на битбакет публичный ключ достаточно добавить только в аккаунт. Можно и отдельно в каждый репозиторий добавлять ключ, но не обязательно.

/.ssh/config нет ничего лишнего? Указания на какой-то левый ключ? Для чистоты эксперимента удалить файл)
4) known_hosts удалить для чистоты эксперимента, он должен сам создаваться при первом подключении (хотя возможно еще зависит от ssh-клиента).

Вообще, судя по ошибке, не нравится именно ключ: проверить что на битбакет залит нужный ключ. Может, стоит сгенерить новый ключ и проверить заново (старый удалить).

и т.д.
То есть складывается такое ощущение, что у битбакета динамический IP, хотя, по-идее, для таких подключений должен быть набор статичных. Они даже их список где-то публиковали.
4) Да, если я удаляю known_hosts, то при попытке пула / пуша в путти вначале идет запрос про ключи The authenticity of host ‘. (полный текст я приводил в основном сообщении), а когда я отвечаю на него Yes, то known_hosts на сервере создается заново.

Источник

Adding a new SSH key to your GitHub account

To configure your account on GitHub.com to use your new (or existing) SSH key, you’ll also need to add the key to your account.

Before adding a new SSH key to your account on GitHub.com, you should have:

After adding a new SSH key to your account on GitHub.com, you can reconfigure any local repositories to use SSH. For more information, see «Switching remote URLs from HTTPS to SSH.»

Note: GitHub is improving security by dropping older, insecure key types.

DSA keys ( ssh-dss ) are no longer supported. Existing keys will continue to function through March 15, 2022. You cannot add new DSA keys to your user account on GitHub.com.

RSA keys ( ssh-rsa ) with a valid_after before November 2, 2021 may continue to use any signature algorithm. RSA keys generated after that date must use a SHA-2 signature algorithm. Some older clients may need to be upgraded in order to use SHA-2 signatures.

Copy the SSH public key to your clipboard.

If your SSH public key file has a different name than the example code, modify the filename to match your current setup. When copying your key, don’t add any newlines or whitespace.

In the upper-right corner of any page, click your profile photo, then click Settings. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the user settings sidebar, click SSH and GPG keys. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click New SSH key or Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the «Title» field, add a descriptive label for the new key. For example, if you’re using a personal Mac, you might call this key «Personal MacBook Air».

Paste your key into the «Key» field. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

If prompted, confirm your GitHub password. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Copy the SSH public key to your clipboard.

If your SSH public key file has a different name than the example code, modify the filename to match your current setup. When copying your key, don’t add any newlines or whitespace.

In the upper-right corner of any page, click your profile photo, then click Settings. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the user settings sidebar, click SSH and GPG keys. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click New SSH key or Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the «Title» field, add a descriptive label for the new key. For example, if you’re using a personal Mac, you might call this key «Personal MacBook Air».

Paste your key into the «Key» field. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

If prompted, confirm your GitHub password. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Copy the SSH public key to your clipboard.

If your SSH public key file has a different name than the example code, modify the filename to match your current setup. When copying your key, don’t add any newlines or whitespace.

In the upper-right corner of any page, click your profile photo, then click Settings. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the user settings sidebar, click SSH and GPG keys. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click New SSH key or Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

In the «Title» field, add a descriptive label for the new key. For example, if you’re using a personal Mac, you might call this key «Personal MacBook Air».

Paste your key into the «Key» field. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Click Add SSH key. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

If prompted, confirm your GitHub password. как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

To learn more about GitHub CLI, see «About GitHub CLI.»

Before you can use the GitHub CLI to add an SSH key to your account, you must authenticate to the GitHub CLI. For more information, see gh auth login in the GitHub CLI documentation.

To add an SSH key to your GitHub account, use the ssh-key add subcommand, specifying your public key.

If you generated your SSH key by following the instructions in «Generating a new SSH key», you can add the key to your account with this command.

Источник

Generating a new SSH key and adding it to the ssh-agent

In this article

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

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.

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.

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.

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.

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.

Источник

Генерация SSH-ключа для работы с GitHub

Во-первых, нам нужно проверить, установлен ли у вас уже SSH-ключ. Введите это в терминал:

Если в консоли появляется сообщение с текстом «Нет такого файла или каталога», значит, у вас еще нет SSH-ключа, и вам нужно будет его создать. Если в выводе консоли не появилось никакого сообщения, значит, у вас уже есть ключ.

Добавление созданных SSH-ключей в SSH-агент

Убедимся что SSH-агент включён:

Запускаем агента, он работает в фоновном режиме. В консоли должен появиться id запущенного процесса.

Пример (у вас он будет свой)

Добавим SSH-ключ в SSH-агент.

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

В случаем использования только что созданных ключей просто вводим в консоль Git команду:

Результат который получите (у вас будет свой)

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

Сначала вы перейдете туда, где GitHub получает наш SSH-ключ. Войдите в GitHub и щелкните изображение своего профиля в правом верхнем углу. Затем нажмите на Settings в раскрывающемся меню.

Выделите и скопируйте результат, который начинается с ssh-rsa и заканчивается вашим адресом электронной почты.

Если у вас будет ошибка, то этот ключ можно найти на вашем локальном компьютере.

Откройте в любом текстовом редакторе, скопируйте ключ и добавьте на сайте.

Автор курса: Олег Данилюк (по всем вопросам)

Источник

Как создать ssh key github linux

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

На данный момент, один из самых популярных репозиториев для системы контроля версий GitHub, использует аутентификацию пользователей через открытые SSH-ключи. Это позволяет работать с сервисом без ввода логина и пароля, а также удобно производить контроль доступа к своему репозиторию.

Рассмотрим вариант создания и добавления SSH-ключей к своему GitHub аккаунту.

Подготовка

Для начала скачаем и установим клиент GitHub по ссылке https://git-scm.com

Теперь попробуем клонировать существующий репозиторий c GitHub для понимания одной из самых популярных ошибок, возникающих при начале работы с Git. Для этого откроем установленную консоль Git Bash, нажав правую кнопку мыши и выбрав пункт Git Bash Here.

Не забудем предварительно перейти в подготовленный каталог для удобства экспериментов с Git. В моем случае это будет каталог C:/domains/test.

Введем в консоли Git Bash команду клонирования удаленного репозитория с GitHub:

Именно здесь мы столкнемся с фатальной ошибкой скачивания из-за ограничения доступа к GitHub:

Решим эту проблему созданием публичного ключа для GitHub.

Генерация SSH-ключей для GitHub

Итак, мы сгенерировали SSH-ключи и теперь перейдем к следующему этапу.

Добавление созданных SSH-ключей в SSH-агент

Следующим шагом будет добавление приватного ключа в GitHub аккаунт.

Добавление нового SSH-ключа в GitHub аккаунт

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Проверим, что все нами сделано верно, опять введя в консоль Git команду клонирования удаленного репозитория:

Через несколько секунд получим на своем локальном компьютере полную копию нужного нам репозитория.

как создать ssh key github linux. Смотреть фото как создать ssh key github linux. Смотреть картинку как создать ssh key github linux. Картинка про как создать ssh key github linux. Фото как создать ssh key github linux

Таким образом единожды проведя операцию создания публичного SSH-ключа и внеся его в свой профиль на GitHub, мы обеспечим себе удобную и безопасную работу с удаленным репозиторием.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *