Git добавить ssh key windows

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 passphrases

You can access and write data in repositories on GitHub.com using SSH (Secure Shell Protocol). When you connect via SSH, you authenticate using a private key file on your local machine. For more information, see «About SSH.»

When you generate an SSH key, you can add a passphrase to further secure the key. Whenever you use the key, you must enter the passphrase. If your key has a passphrase and you don’t want to enter the passphrase every time you use the key, you can add your key to the SSH agent. The SSH agent manages your SSH keys and remembers your passphrase.

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.

Generating a new SSH key

You can generate a new SSH key on your local machine. After you generate the key, you can add the public key to your account on GitHub.com to enable authentication for Git operations over SSH.

Note: GitHub improved security by dropping older, insecure key types on March 15, 2022.

As of that date, DSA keys (ssh-dss) are no longer supported. You cannot add new DSA keys to your personal 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.

  1. Open TerminalTerminalGit Bash.

  2. Paste the text below, substituting in your GitHub email address.

    ssh-keygen -t ed25519 -C "your_email@example.com"
    

    Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:

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

    This creates a new SSH key, using the provided email as a label.

    > Generating public/private ALGORITHM key pair.
    

    When you’re prompted to «Enter a file in which to save the key», you can press Enter to accept the default file location. Please note that if you created SSH keys previously, ssh-keygen may ask you to rewrite another key, in which case we recommend creating a custom-named SSH key. To do so, type the default file location and replace id_ssh_keyname with your custom key name.

  3. At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»

    > Enter passphrase (empty for no passphrase): [Type a passphrase]
    > Enter same passphrase again: [Type passphrase again]
    

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.

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.»

  1. Insert your hardware security key into your computer.

  2. Open TerminalTerminalGit Bash.

  3. 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.

     ssh-keygen -t ecdsa-sk -C "your_email@example.com"
    
  4. When you are prompted, touch the button on your hardware security key.

  5. When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.

  6. When you are prompted to type a passphrase, press Enter.

    > Enter passphrase (empty for no passphrase): [Type a passphrase]
    > Enter same passphrase again: [Type passphrase again]
    
  7. Add the SSH public key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»

Инструменты

Git SSH Windows — пошаговое руководство

Дата размещения статьи 08/12/2019 👁31067

Git SSH Windows — пошаговое руководство

Настроим пошагово Git SSH для Windows 10. Это позволит вам выполнять команды git без ввода пароля от своей учетной записи GitHub.

Порядок действий:

  1. Генерация ключа SSH.
  2. Добавление SSH-ключа в ssh-agent.
  3. Добавление ключа SSH в учетную запись GitHub.

Git SSH Windows

Генерация ключа SSH

Откройте bash/терминал. Добавьте следующий текст, подставив свой адрес электронной почты GitHub.

ssh-keygen -t rsa -b 4096 -C "ваша@почта.com"

Будет создан ключ ssh, используя e-mail в качестве метки.

Когда вам будет предложено «Введите файл, в котором вы хотите сохранить ключ», нажмите Enter. Это установит в местоположение по умолчанию.

Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]

Далее введите безопасную фразу-пароль дважды или просто нажмите Enter.

Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

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

Чтобы запустить ssh-агент введите следующую команду.

На экране отобразится похожая строка.

Agent pid 31724

Добавим свой закрытый ключ SSH в ssh-agent. Если вы создали свой ключ с другим именем (или добавляете существующий ключ с другим именем), замените в команде id_rsa на имя вашего файла закрытого (приватного) ключа.

Ключ будет успешно добавлен в ssh-агент.

Добавление ключа SSH в учетную запись GitHub

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

Сейчас нам необходимо скопировать SSH ключ в буфер обмена.

Способов есть несколько, но я же вам предлагаю следующее решения для Windows 10: введите команду ниже.

Прямо в терминале вы увидите содержимое необходимого файла с ключем. Скопируйте его в буфер.

Теперь зайдите на вашу страницу GitHub » Settings.

GitHub SSH Windows 10

Перейдите во вкладку SSH and GPG keys и нажмите на кнопку New SSH key для добавления SSH ключа в вашу учетную запись GitHub.

Добавление SSH ключа для GitHub

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

В поле Key добавьте свой ssh-ключ, который вы скопировали в буфер обмена на предыдущем шаге.

Нажмите Add SSH key.

Добавление SSH ключа для GitHub

Для подтверждения вам потребуется ввести свой пароль от учетной записи GitHub.

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

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

JavaScript: Window Location Checkbox Checked — Проверка Состояния Чекбокса ✔️

Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.

  • Настройка Gulp Babel
  • Микроразметка сайта
  • Как перенести сайт WordPress на хостинг
  • Настройте показ всего текста во время загрузки веб-шрифтов
  • Сниппеты в VS Code
  • Не удается проверить так как не задан исполняемый PHP-файл

4.3 Git на сервере — Генерация открытого SSH ключа

Генерация открытого SSH ключа

Как отмечалось ранее, многие Git-серверы используют аутентификацию по открытым SSH-ключам.
Для того чтобы предоставить открытый ключ, каждый пользователь в системе должен его сгенерировать, если только этого уже не было сделано ранее.
Этот процесс аналогичен во всех операционных системах.
Сначала вам стоит убедиться, что у вас ещё нет ключа.
По умолчанию пользовательские SSH ключи сохраняются в каталоге ~/.ssh домашнем каталоге пользователя.
Вы можете легко проверить наличие ключа перейдя в этот каталог и посмотрев его содержимое:

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

Ищите файл с именем id_dsa или id_rsa и соответствующий ему файл с расширением .pub.
Файл с расширением .pub — это ваш открытый ключ, а второй файл — ваш приватный ключ.
Если указанные файлы у вас отсутствуют (или даже нет каталога .ssh), вы можете создать их используя программу ssh-keygen, которая входит в состав пакета SSH в системах Linux/Mac, а для Windows поставляется вместе с Git:

$ 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

Сначала программа попросит указать расположение файла для сохранения ключа (.ssh/id_rsa), затем дважды ввести пароль для шифрования.
Если вы не хотите вводить пароль каждый раз при использовании ключа, то можете оставить его пустым или использовать программу ssh-agent.
Если вы решили использовать пароль для приватного ключа, то настоятельно рекомендуется использовать опцию -o, которая позволяет сохранить ключ в формате, более устойчивом ко взлому методом подбора, чем стандартный формат.

Теперь каждый пользователь должен отправить свой открытый ключ вам или тому, кто администрирует Git-сервер (подразумевается, что ваш SSH-сервер уже настроен на работу с открытыми ключами).
Для этого достаточно скопировать содержимое файла с расширением .pub и отправить его по электронной почте.
Открытый ключ выглядит примерно так:

$ 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

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

The third-party Git Credential Manager (GCM) can be used as alternative method of connecting to Bitbucket Cloud from the Git CLI. If you do not want to configure SSH access for your Bitbucket Cloud account, you can use the GCM, which is installed by default with Git for Windows, or you can download and install it from Git Credential Manager on GitHub. Note that the GCM works over HTTPS, not SSH. Ensure your Git remotes are using HTTPS, such as:
git clone https://{username}@bitbucket.org/{workspace}/{repository}.git

The Secure Shell protocol (SSH) is used to create secure connections between your device and Bitbucket Cloud. The connection is authenticated using public SSH keys, which are derived from a private SSH key (also known as a private/public key pair). The secure (encrypted) connection is used to securely transmit your source code between your local device and Bitbucket Cloud. To set up your device for connecting Bitbucket Cloud using SSH, you need to:

  1. Install OpenSSH on your device.

  2. Start the SSH service.

  3. Create an SSH key pair.

  4. Add your key to the SSH agent.

  5. Provide Bitbucket Cloud with your public key.

  6. Check that your SSH authentication works.

Install OpenSSH on Microsoft Windows

There are 3 methods for installing OpenSSH on Microsoft Windows:

  • Download and run the Git for Windows installer.

  • Use winget to run the Git for Windows installer.

  • Install the Windows version of OpenSSH.

Download and install Git for Windows

  1. Download and run the installer from https://gitforwindows.org/. The options at each step should be suitable. When you reach the step about choosing the SSH executable, ensure the bundled OpenSSH is selected.

  2. Once the installation is complete, open Git Bash from the Start menu.

In the terminal, check that OpenSSH has been successfully installed by running the following command:

1
ssh -V

The output should show the installed version of OpenSSH.

Install Git for Windows with winget

To install OpenSSH as part of Git for Windows with the Windows package manager winget:

  1. Check that winget is installed. Open PowerShell and run:

    1
    winget -v

  2. To install Git for Windows using winget install, run:

    1
    winget install --id Git.Git -e --source winget

  3. Once the installation is complete, open Git Bash from the Start menu.

In the terminal, check that OpenSSH has been successfully installed by running the following command:

1
ssh -V

The output should show the installed version of OpenSSH.

Install the Windows version of OpenSSH

This procedure assumes Git is already installed and accessible in PowerShell. If Git is installed and not accessible in PowerShell, you may need to add Git to the PATH environmental variable.

To install the Windows version of OpenSSH, follow the instructions in the Microsoft Docs Get Started with OpenSSH for Windows guide. Once OpenSSH is installed, you need to configure Git to use OpenSSH.

In PowerShell, check that OpenSSH has been successfully installed by running the following command:

1
ssh -V

The output should show the installed version of OpenSSH.

To find where ssh was installed, run Get-Command. For example:

1
2
3
4
5
> Get-Command ssh

CommandType Name Version Source
----------- ---- ------- ------
Application ssh.exe 8.1.0.1 C:\Windows\System32\OpenSSH\ssh.exe

To configure Git to use the Windows version of OpenSSH, update the SSH command with git config, such as:

1
git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe

Start the SSH agent

To allow git to use your SSH key, an SSH agent needs to be running on your device. The method for starting the SSH agent depends on how OpenSSH was installed.

Git for Windows users (including Winget-based Git installations)

From a git bash terminal, check if the SSH agent is running using the ps command. If the ssh-agent is already running, it should appear in the output, such as:

1
2
$ ps -a | grep ssh-agent
tkelly 3291 0.0 0.0 6028 464 ? Ss 07:29 0:00 ssh-agent

To start the agent:

1
eval $(ssh-agent)

You may need to add this command to your ~/.bashrc to ensure the agent starts when you open a Git Bash terminal.

Windows OpenSSH users

From a PowerShell, check if the SSH Agent is running using the Get-Service command. For example:

1
2
3
4
5
> Get-Service ssh-agent

Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent

To start the agent:

1
> Start-Service ssh-agent

To configure the SSH agent to start each time the device is started, use the Set-Service command, such as:

1
> Set-Service -Name sshd -StartupType 'Automatic'

Create an SSH key pair

To create an SSH key pair:

  1. Open a terminal and navigate to your home or user directory using cd, for example:

    1
    cd ~

  2. Generate a SSH key pair using ssh-keygen, such as:

    1
    ssh-keygen -t ed25519 -b 4096 -C "{username@emaildomain.com}" -f {ssh-key-name}

    Where:

    • {username@emaildomain.com} is the email address associated with the Bitbucket Cloud account, such as your work email account.

    • {ssh-key-name} is the output filename for the keys. We recommend using a identifiable name such as bitbucket_work.

  3. When prompted to Enter passphrase, you can either provide a password or leave the password empty. If you input a password, you will be prompted for this password each time SSH is used, such as using Git command that contact Bitbucket Cloud (such as git push, git pull, and git fetch). Providing a password will prevent other users with access to the device from using your keys.

Once complete, ssh-keygen will output two files:

  • {ssh-key-name} — the private key.

  • {ssh-key-name}.pub — the public key.

These files will be stored in your user folder, such as C:\Users\<username>\<ssh-key-name>.

Add your key to the SSH agent

To add the SSH key to your SSH agent (ssh-agent):

  1. Run the following command, replacing the {ssh-key-name} with the name of the private key:

    1
    ssh-add ~/{ssh-key-name}

  2. To ensure the correct SSH key is used when connecting to Bitbucket, update or create your SSH configuration file (~/.ssh/config) with the following settings:

    1
    2
    3
    Host bitbucket.org
    AddKeysToAgent yes
    IdentityFile ~/.ssh/{ssh-key-name}

    Where {ssh-key-name} is the location of the private key file once it has been added to the ssh-agent.

Provide Bitbucket Cloud with your public key

To add an SSH key to your user account:

  1. Select the Settings cog on the top navigation bar.

  2. From the Settings dropdown menu, select Personal Bitbucket settings.

  3. Under Security, select SSH keys.

  4. Select Add key.

  5. In the Add SSH key dialog, provide a Label to help you identify which key you are adding. For example, Work Laptop <Manufacturer> <Model>. A meaning full label will help you identify old or unwanted keys in the future.

  6. Open the public SSH key file (public keys have the .pub file extension) in a text editor. The public key should be in the .ssh/ directory of your user (or home) directory. The contents will be similar to:

    1
    ssh-ed25529 LLoWYaPswHzVqQ7L7B07LzIJbntgmHqrE40t17nGXL71QX9IoFGKYoF5pJKUMvR+DZotTm user@example.com

  7. Copy the contents of the public key file and paste the key into the Key field of the Add SSH key dialog.

  8. Select Add key.

    • If the key is added successfully, the dialog will close and the key will be listed on the SSH keys page.

    • If you receive the error That SSH key is invalid, check that you copied the entire contents of the public key (.pub file).

Check that your SSH authentication works

To test that the SSH key was added successfully, open a terminal on your device and run the following command:

1
ssh -T git@bitbucket.org

If SSH can successfully connect with Bitbucket using your SSH keys, the command will produce output similar to:

1
2
3
authenticated via ssh key.

You can use git to connect to Bitbucket. Shell access is disabled

Время на прочтение
2 мин

Количество просмотров 107K

Много статей (в том числе и на Хабре) посвящено подключению к Git по SSH-ключам. Почти во всех из них используется один из двух способов: либо с помощью puttygen.exe, либо командами ssh-keygen или ssh-add.

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

Как я решил эту проблему — под катом.

BitBucket всё время ругался на то, что ему требуется подключение с помощью ключа:

Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

Мои попытки сгенерировать ключи, указать пути в переменных среды, привязать ключи к гиту были бесполезны. Либо гит ругался крякозябрами (в случае ssh-agent cmd.exe), либо просто игнорировал всё предложенное.

Решение оказалось куда удобнее и проще. Достаточно запустить в локальном репозитории GIT GUI Here, и в меню перейти в
Help -> Show SSH Key:

Скрины

image

image

Если вы столкнулись с такой проблемой, то скорее всего у вас там ни чего не будет:

Окно генерации SSH Key

image

Ну а дальше читать будут, скорее всего, только самые педантичные… Жмём Generate key, видим окно запроса пароля (два раза) для приватного ключа:

Запрос пароля

image

И видим сгенерировавшийся публичный ключ:

Публичный ключ

image

Копируем его, и добавляем вэб-морду ГИТа (в моём случае это BitBucket; ключи там можно добавить в двух местах — в настройках аккаунта и в настройках проекта, нам первый вариант, ибо второй — для деплоя проекта) [Аккаунт]Управление аккаунтомSSH-ключиДобавить ключ:

Добавление ключа в BitBucket

image

Ну, а дальше — просто делаем что нужно — или пуш, или клон (предполагается, что git remote add вы уже сделали сами). Git спросит, можно ли добавить хост к доверенным, и запросит passphrase (пароль приватного ключа). Всё, можно работать.

Удачных разработок!

PS: Большое спасибо за наводку на решение моему коллеге Ивану!

  • Git для windows как пользоваться
  • Git для windows visual studio
  • Git для windows 10 установка
  • Git windows use ssh key
  • Git windows crlf to lf