ssh key github что это

Ssh key github что это

На данный момент, один из самых популярных репозиториев для системы контроля версий 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 аккаунт

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

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

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

Источник

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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.

Источник

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.

In the user settings sidebar, click SSH and GPG keys.

Click New SSH key or Add SSH key.

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.

Click Add SSH key.

If prompted, confirm your GitHub password.

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.

In the user settings sidebar, click SSH and GPG keys.

Click New SSH key or Add SSH key.

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.

Click Add SSH key.

If prompted, confirm your GitHub password.

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.

Читайте также:  stellaris что за игра

In the upper-right corner of any page, click your profile photo, then click Settings.

In the user settings sidebar, click SSH and GPG keys.

Click New SSH key or Add SSH key.

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.

Click Add SSH key.

If prompted, confirm your GitHub password.

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.

Источник

Регистрация на Гитхабе. Работа через консоль

Гитхаб — крупнейший веб-сервис для хостинга IT-проектов и их совместной разработки. Он как раз и основан на системе контроля версий Гит. Кроме размещения кода участники могут общаться, комментировать правки друг друга, а также следить за новостями знакомых. Именно в нём работаем мы в Академии и ученики на интенсивах.

Регистрация и установка

Устанавливаем Гит

Если до этого вы не работали с Гитом, то его нужно установить. Рассмотрим, как это сделать в популярных операционных системах.

Установка в Linux

Установка на Mac

Сперва устанавливаем Homebrew если он у вас ещё не стоит. Также вы можете установить его с помощью команды:

Эта команда установит Гит на ваш компьютер.Чтобы прописать новый путь к установке Гит введите команду: export PATH=/usr/local/bin:$PATH

Установка в Windows

Здесь всё просто. Просто скачайте exe-файл инсталлятора со страницы проекта на Гитхабе и запустите его.

После установки у вас будет как консольная версия (включающая SSH-клиент, который пригодится позднее), так и стандартная графическая.

Регистрация на Гитхабе

Чтобы начать работать с Гитхабом, нужно зарегистрироваться на нём, если вы ещё этого не сделали. Регистрация предельно проста:

Начинаем работу

Устанавливаем SSH-ключи

SSH-ключ нужен чтобы быстро устанавливать соединение с Гитхабом, не вводя пароля. Кроме того, SSH — единственный из сетевых протоколов, предоставляющий доступ и на чтение, и на запись. Два других сетевых протокола (HTTP[S] и Git) в большинстве случаев дают доступ только на чтение, поэтому даже если они вам доступны, вам всё равно понадобится SSH для записи. К тому же SSH — протокол с аутентификацией и шифрованием трафика, что называется «из коробки». Недостаток SSH в том, что, используя его, вы не можете обеспечить анонимный доступ к репозиторию.

Доступ к удалённому репозиторию по SSH — самый распространённый вариант настройки удалённого доступа, быстрый, удобный и безопасный. Настроив авторизацию в SSH по ключам, вы будете избавлены от необходимости вводить пароли для доступа к репозиторию, сохраняя, однако, приемлемый уровень безопасности.

«eval» не является внутренней или внешней командой, исполняемой программой или пакетным файлом.

Если проблема осталась, то рекомендуем воспользоваться программой Git Bash.

Примечание: если вы используете macOS Sierra 10.12.2 или более позднюю версию, то вам нужно будет модифицировать ваш

/.ssh/config файл, чтобы автоматически загрузить ключи в ssh-agent и хранить пароли.

Добавляем ключ на Гитхаб

Результат проверки добавления ключа

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

Клонируем репозиторий по SSH-ссылке

Более подробное описание работы с Гитхабом мы рассмотрим в статье «Pабота с Гит через консоль»

Источник

Информ портал о технике и не только