How to set ssh key for git

How to set ssh key for git

Using Git with SSH keys

Have you seen the ad that should be here?

Using the SSH protocol, you can connect and authenticate to servers to use their services. The three mentioned services allow Git to connect via SSH instead of HTTPS. Connecting with public key encryption dispenses typing username and password for every Git command.

You are going to see in this post how to use GitHub, GitLab and Bitbucket with SSH.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Make sure an SSH client in installed

In order to connect using the SSH protocol, an SSH client must be installed on your system. If you use openSUSE, it should be already installed by default.

Just to make sure, open the terminal and run:

That command should output the version number of the SSH client being used:

In case the system informs that the ssh command was not found, you can install the OpenSSH client running:

Check for existing SSH keys

To connect using the SSH protocol, you need an SSH key pair (one private and the other public). If you have never used SSH, you can safely skip this topic and move on to the next. If you have ever used SSH (for instance, to remotely access a server), probably you already have an SSH key pair, in which case you don’t need to generate a new key pair.

To see if existing SSH keys are present, run:

That command should list the contents of the

/.ssh folder, in which the SSH client stores its configuration files:

If you receive an error that there is no

/.ssh directory or there are no files in it, don’t worry: it means you haven’t created an SSH key pair yet. If that is the case, proceed to the next topic.

By default, public SSH keys are named:

/.ssh folder, I have an SSH key pair ( id_rsa.pub is the public key and id_rsa is the private key) created a year ago ( Jul 18 2018 ).

For security reasons, it is recommended that you generate a new SSH key pair at least once a year. If you already have an SSH key pair that was created more than a year ago, it is recommended that you proceed to the next topic.

If you already have an SSH key pair and want to reuse it, you can skip the next topic.

Generate a new SSH key pair

To generate a new SSH key pair, run the following command (replace your_email@example.com with your email address):

It asks you where to save the private key ( id_rsa ).

Press Enter to accept the default location.

If you already have a private key, it asks whether it should overwrite:

If that happens, type y and press Enter.

Then, enter and re-enter a passphrase (think of it as a kind of password):

The SSH key pair is created in

The whole interaction should look similar to the following:

Add the private SSH key to the ssh-agent

If you don’t want to type your passphrase each time you use your SSH keys, you need to add it to the ssh-agent, which is a program that runs in background while you are logged in to the system and stores your keys in memory.

To start the ssh-agent in background, run the following:

That command outputs the ssh-agent process identifier:

Then, add your SSH private key to the ssh-agent:

Type your passphrase and press Enter:

The command confirms that the private SSH key has been added to the ssh-agent:

Add the public SSH key to your account

Once you have an SSH key and have added it to the ssh-agent, you can set up connecting via SSH. Let’s see how to do that for each of the three servers: GitHub, GitLab and Bitbucket.

In all the three cases, the process is similar. Start by copying your public SSH key (

/.ssh/id_rsa.pub ) file contents to the clipboard using the xclip command:

xclip is a command line utility that allows access to the graphical interface clipboard from the terminal. If it is not installed, you can install it running:

GitHub

Using a browser, go to the GitHub home page at github.com and sign in to your account.

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

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

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

Fill in the Title field with a descriptive label for the new key (for example, the name of your computer) and paste your public key into the Key field. Finally, click Add SSH key:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Now the key appears in the list of SSH keys associated with your account:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

GitLab

Using a browser, go to the GitLab home page at gitlab.com and sign in to your account.

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

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

In the User Settings sidebar, click SSH Keys.

Paste your public key in the Key field. Fill in the Title field with a descriptive label for the new key (for example, the name of your computer). Finally, click Add key:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Now the key appears in the list of SSH keys associated with your account:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Bitbucket

Using a browser, go to the Bitbucket home page at bitbucket.org and log in to your account.

In the lower-left corner of the page, click your profile photo, then click Bitbucket settings:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

In the Settings sidebar, in the Security section, click SSH keys. Then, click Add key.

Fill in the Label field with a descriptive label for the new key (for example, the name of your computer) and paste your public key into the Key field. Finally, click Add key:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Now the key appears in the list of SSH keys associated with your account:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Test connecting via SSH

GitHub, GitLab and Bitbucket allow you to test whether SSH connection has been set up correctly before actually using it with Git.

GitHub

After you’ve added your SSH key to your GitHub account, open the terminal and run:

That command attempts an SSH remote access to GitHub.

If that is the first time you connect to GitHub via SSH, the SSH client asks you if it can trust the public key of the GitHub server:

Type yes and press Enter. The SSH client adds GitHub to the list of trusted hosts:

Once added to the list of known hosts, you won’t be asked about GitHub’s public key again.

As this remote access via SSH is provided by GitHub just for testing, not for actual use, the server informs that you have successfully authenticated and terminates the connection:

If you completed the test successfully, now you can use SSH with GitHub.

The whole interaction should look similar to the following:

GitLab

If you have added your SSH key to your GitLab account, the test is very similar:

If you completed the test successfully, now you can use SSH with GitLab.

Bitbucket

If you have added your SSH key to your Bitbucket account, the test is very similar:

If you completed the test successfully, now you can use SSH with Bitbucket.

Clone a repository using SSH

Now that we’ve got our SSH keys set up, let’s see how to clone a Git repository using SSH instead of HTTPS.

GitHub

At GitHub, go to a project’s repository, click Clone or download and copy the URL to clone the repository using SSH:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

The URL of a GitHub repository looks like:

Open the terminal and run the git clone command passing the copied URL as argument.

Tip: to paste into the terminal, use Ctrl + Shift + V.

Note that now Git clones the repository without asking for a password:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

GitLab

At GitLab, go to a project’s repository, click Clone and copy the URL to clone the repository using SSH:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

The URL of a GitLab repository looks like:

Open the terminal and run the git clone command passing the copied URL as argument:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Note that now Git clones the repository without asking for a password.

Bitbucket

At Bitbucket, go to a project’s repository, click Clone and copy the command to clone the repository using SSH:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Note that, differently from GitHub and GitLab that present the URL, Bitbucket presents the entire git clone command, including the URL.

The URL of a Bitbucket repository looks like:

Open the terminal, paste and run the command you copied from Bitbucket:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Note that now Git clones the repository without asking for a password.

Reconfigure existing repositories to use SSH

To do that, open the terminal and change the current directory to a local repository.

List the existing remote repositories and their URLs with:

That command should output something like:

Change your remote repository’s URL with:

Great. That done, Git will use SSH, instead of HTTPS, to synchronize that local repository with its remote equivalent.

References

I hope those tips can be useful to you as they have been to me since I started using Git. If you have any questions or trouble, don’t hesitate to comment! See you!

And always remember: have a lot of fun…

Did you like it? What about sharing?

Comments

About

The Linux Kamarada Project aims to spread and promote Linux as a robust, secure, versatile and easy to use operating system, suitable for everyday use be at home, at work or on the server. The project focuses mainly on distribution and documentation.

Have you seen the ad that should be here?

Donate

You can make a one-time donation quickly with PayPal:

How to Get and Configure Your Git and GitHub SSH Keys

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

If you use GitHub without setting up an SSH key, you’re really missing out. Just think–all of that time you spent entering your email address and password into the console every time you push a commit could have been spent coding.

Well no more. Here’s a quick guide to generate and configure an SSH key with GitHub so you never have to authenticate the old fashioned way again.

Check for an existing SSH key

First, check if you’ve already generated SSH keys for your machine. Open a terminal and enter the following command:

If you’ve already generated SSH keys, you should see output similar to this:

If your keys already exist, skip ahead to the Copy your public SSH key section below.

If you don’t see any output or that directory doesn’t exist (you get a No such file or directory message), then run:

Then generate a new set of keys with:

/.ssh command and ensure that the output is similar to the one listed above.

Note: SSH keys are always generated as a pair of public ( id_rsa.pub ) and private ( id_rsa ) keys. It’s extremely important that you never reveal your private key, and only use your public key for things like GitHub authentication. You can read more about how SSH / RSA key pairs work here.

Add your SSH key to ssh-agent

ssh-agent is a program that starts when you log in and stores your private keys. For it to work properly, it needs to be running and have a copy of your private key.

First, make sure that ssh-agent is running with:

Then, add your private key to ssh-agent with:

Copy your public SSH key

Next, you need to copy your public SSH key to the clipboard.

For Linux or Mac, print the contents of your public key to the console with:

Then highlight and copy the output.

Or for Windows, simply run:

Add your public SSH key to GitHub

Go to your GitHub settings page and click the «New SSH key» button:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Then give your key a recognizable title and paste in your public ( id_rsa.pub ) key:

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Finally, test your authentication with:

If you’ve followed all of these steps correctly, you should see this message:

More info on SSH:

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Use SSH key authentication

Azure DevOps Services | Azure DevOps Server 2022 | Azure DevOps Server 2020 | Azure DevOps Server 2019 | TFS 2018

Connect to your Git repos through SSH on macOS, Linux, or Windows to securely connect using HTTPS authentication. On Windows, we recommended the use of Git Credential Manager or Personal Access Tokens.

SSH URLs have changed, but old SSH URLs will continue to work. If you have already set up SSH, you should update your remote URLs to the new format:

As of Visual Studio 2017, SSH can be used to connect to Azure DevOps Git repos.

How SSH key authentication works

SSH public key authentication works with an asymmetric pair of generated encryption keys. The public key is shared with Azure DevOps and used to verify the initial ssh connection. The private key is kept safe and secure on your system.

Set up SSH key authentication

The following steps cover configuration of SSH key authentication on the following platforms:

Configure SSH using the command line. bash is the common shell on Linux and macOS and the Git for Windows installation adds a shortcut to Git Bash in the Start menu. Other shell environments will work, but are not covered in this article.

Step 1: Create your SSH keys

If you have already created SSH keys on your system, skip this step and go to configuring SSH keys.

The commands here will let you create new default SSH keys, overwriting existing default keys. Before continuing, check your

/.ssh folder (for example, /home/jamal/.ssh or C:\Users\jamal\.ssh) and look for the following files:

If these files exist, then you have already created SSH keys. You can overwrite the keys with the following commands, or skip this step and go to configuring SSH keys to reuse these keys.

Create your SSH keys with the ssh-keygen command from the bash prompt. This command will create a 3072-bit RSA key for use with SSH. You can give a passphrase for your private key when prompted—this passphrase provides another layer of security for your private key. If you give a passphrase, be sure to configure the SSH agent to cache your passphrase so you don’t have to enter it every time you connect.

This command produces the two keys needed for SSH authentication: your private key ( id_rsa ) and the public key ( id_rsa.pub ). It is important to never share the contents of your private key. If the private key is compromised, attackers can use it to trick servers into thinking the connection is coming from you.

Step 2: Add the public key to Azure DevOps Services/TFS

Associate the public key generated in the previous step with your user ID.

Open your security settings by browsing to the web portal and selecting your avatar in the upper right of the user interface. Select SSH public keys in the menu that appears.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Select + New Key.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Copy the contents of the public key (for example, id_rsa.pub) that you generated into the Public Key Data field.

Avoid adding whitespace or new lines into the Key Data field, as they can cause Azure DevOps Services to use an invalid public key. When pasting in the key, a newline often is added at the end. Be sure to remove this newline if it occurs.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Give the key a useful description (this description will be displayed on the SSH public keys page for your profile) so that you can remember it later. Select Save to store the public key. Once saved, you cannot change the key. You can delete the key or create a new entry for another key. There are no restrictions on how many keys you can add to your user profile. Also note that SSH keys stored in Azure DevOps expire after five years. If your key expires, you may upload a new key or the same one to continue accessing Azure DevOps via SSH.

Step 2: Add the public key to Azure DevOps

Associate the public key generated in the previous step with your user ID.

Open your security settings by browsing to the web portal and selecting your avatar in the upper right of the user interface. Select Security in the menu that appears.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Select + New Key.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Copy the contents of the public key (for example, id_rsa.pub) that you generated into the Public Key Data field.

Avoid adding whitespace or new lines into the Key Data field, as they can cause Azure DevOps Services to use an invalid public key. When pasting in the key, a newline often is added at the end. Be sure to remove this newline if it occurs.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Give the key a useful description (this description will be displayed on the SSH public keys page for your profile) so that you can remember it later. Select Save to store the public key. Once saved, you cannot change the key. You can delete the key or create a new entry for another key. There are no restrictions on how many keys you can add to your user profile.

Step 3: Clone the Git repository with SSH

To connect with SSH from an existing cloned repo, see updating your remotes to SSH.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

With Azure DevOps Services, the format for the project URL is dev.azure.com// . However, the previous format that references the visualstudio.com format is still supported. For more information, see Introducing Azure DevOps, Switch existing organizations to use the new domain name URL.

Run git clone from the command prompt.

SSH may display the server’s SSH fingerprint and ask you to verify it. You should verify that the displayed fingerprint matches one of the fingerprints in the SSH public keys page.

SSH displays this fingerprint when it connects to an unknown host to protect you from man-in-the-middle attacks. Once you accept the host’s fingerprint, SSH will not prompt you again unless the fingerprint changes.

To prevent problems, Windows users should run a command to have Git reuse their SSH key passphrase.

Questions and troubleshooting

Q: How can I have Git remember the passphrase for my key on Windows?

A: Run the following command included in Git for Windows to start up the ssh-agent process in PowerShell or the Windows Command Prompt. ssh-agent will cache your passphrase so you don’t have to provide it every time you connect to your repo.

If you’re using the Bash shell (including Git Bash), start ssh-agent with:

Q: I use PuTTY as my SSH client and generated my keys with PuTTYgen. Can I use these keys with Azure DevOps Services?

A: Yes. Load the private key with PuTTYgen, go to Conversions menu and select Export OpenSSH key. Save the private key file and then follow the steps to set up non-default keys. Copy your public key directly from the PuTTYgen window and paste into the Key Data field in your security settings.

Q: How can I verify that the public key I uploaded is the same key as I have locally?

A: You can verify the fingerprint of the public key uploaded with the one displayed in your profile through the following ssh-keygen command run against your public key using the bash command line. You will need to change the path and the public key filename if you are not using the defaults.

You can then compare the MD5 signature to the one in your profile. This check is useful if you have connection problems or have concerns about incorrectly pasting in the public key into the Key Data field when adding the key to Azure DevOps Services.

Q: How can I start using SSH in a repository where I am currently using HTTPS?

A: You’ll need to update the origin remote in Git to change over from a HTTPS to SSH URL. Once you have the SSH clone URL, run the following command:

Q: I’m using Git LFS with Azure DevOps Services and I get errors when pulling files tracked by Git LFS.

A: Azure DevOps Services currently doesn’t support LFS over SSH. Use HTTPS to connect to repos with Git LFS tracked files.

Q: How can I use a non-default key location, i.e. not

A: To use keys created with ssh-keygen in a different place than the default, perform these two tasks:

This command runs in both PowerShell and the Command Prompt. If you are using Git Bash, the command you need to use is:

You can find ssh-add as part of the Git for Windows distribution and also run it in any shell environment on Windows.

Q: I have multiple SSH keys. How do I use different SSH keys for different SSH servers or repos?

A: Generally, if you configure multiple keys for an SSH client and connect to an SSH server, the client can try the keys one at a time until the server accepts one.

However, this doesn’t work with Azure DevOps for technical reasons related to the SSH protocol and how our Git SSH URLs are structured. Azure DevOps will blindly accept the first key that the client provides during authentication. If that key is invalid for the requested repo, the request will fail with the following error:

For Azure DevOps, you’ll need to configure SSH to explicitly use a specific key file. One way to do this to edit your

/.ssh/config file (for example, /home/jamal/.ssh or C:\Users\jamal\.ssh ) as follows:

Q: How do I fix errors that mention «no matching key exchange method found»?

A: Git for Windows 2.25.1 shipped with a new version of OpenSSH which removed some key exchange protocols by default. Specifically, diffie-hellman-group14-sha1 has been identified as problematic for some Azure DevOps Server and TFS customers. You can work around the problem by adding the following to your SSH configuration (

Q: What notifications may I receive about my SSH keys?

A: Whenever you register a new SSH Key with Azure DevOps Services, you will receive an email notification informing you that a new SSH key has been added to your account.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Q: What do I do if I believe that someone other than me is adding SSH keys on my account?

A: If you receive a notification of an SSH key being registered and you did not manually upload it to the service, your credentials may have been compromised.

The next step would be to investigate whether or not your password has been compromised. Changing your password is always a good first step to defend against this attack vector. If you’re an Azure Active Directory user, talk with your administrator to check if your account was used from an unknown source/location.

A: Some Linux distributions, such as Fedora Linux, have crypto policies that require stronger SSH signature algorithms than Azure DevOps supports (as of January 2021). There’s an open feature request to add this support.

You can work around the issue by adding the following code to your SSH configuration (

Использование проверки подлинности с ключом SSH

Azure DevOps Services | Azure DevOps Server 2022 | Azure DevOps Server 2020 | | Azure DevOps Server 2019 г. TFS 2018

Подключение к репозиториям Git средствами SSH в macOS, Linux или Windows для безопасного подключения с помощью проверки подлинности HTTPS. В Windows мы рекомендуем использовать диспетчер учетных данных Git или личные маркеры доступа.

URL-адреса SSH изменились, но старые URL-адреса SSH будут продолжать работать. Если вы уже настроили SSH, следует обновить удаленные URL-адреса до нового формата:

По состоянию на Visual Studio 2017 SSH можно использовать для подключения к репозиториям Git Azure DevOps.

Принцип работы проверки подлинности ключа SSH

Проверка подлинности открытого ключа SSH работает с асимметричной парой созданных ключей шифрования. Открытый ключ используется совместно с Azure DevOps и используется для проверки первоначального SSH-подключения. Закрытый ключ хранится в безопасности и безопасности в системе.

Настройка проверки подлинности ключа SSH

Ниже описана настройка проверки подлинности ключа SSH на следующих платформах:

Настройте SSH с помощью командной строки. bash — это общая оболочка в Linux и macOS, а установка Git для Windows добавляет ярлык в Git Bash в меню «Пуск». Другие среды оболочки будут работать, но не рассматриваются в этой статье.

Шаг 1. Создание ключей SSH

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

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

/.ssh (например, /home/jamal/.ssh или C:\Users\jamal\.ssh) и найдите следующие файлы:

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

Создайте ключи SSH с ssh-keygen помощью команды из командной bash строки. Эта команда создаст 3072-разрядный ключ RSA для использования с SSH. Вы можете при появлении запроса предоставить парольную фразу для закрытого ключа. Эта парольная фраза обеспечивает еще один уровень безопасности для закрытого ключа. Если вы предоставляете парольную фразу, не забудьте настроить агент SSH для кэширования парольной фразы, чтобы не вводить ее при каждом подключении.

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

Шаг 2. Добавление открытого ключа в Azure DevOps Services/TFS

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

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

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Щелкните + Создать ключ.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Избегайте добавления пробелов или новых строк в поле «Данные ключа«, так как они могут привести к тому, что Azure DevOps Services использовать недопустимый открытый ключ. При вставке в ключ в конце часто добавляется новая строка. Не забудьте удалить эту новую линию, если она возникает.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Присвойте ключу полезное описание (это описание будет отображаться на странице открытых ключей SSH для профиля), чтобы его можно было запомнить позже. Нажмите кнопку «Сохранить «, чтобы сохранить открытый ключ. После сохранения ключ изменить нельзя. Вы можете удалить ключ или создать новую запись для другого ключа. Нет ограничений на количество ключей, которые можно добавить в профиль пользователя. Кроме того, обратите внимание, что срок действия ключей SSH, хранящихся в Azure DevOps, истекает через пять лет. Если срок действия ключа истек, вы можете отправить новый ключ или тот же, чтобы продолжить доступ к Azure DevOps через SSH.

Шаг 2. Добавление открытого ключа в Azure DevOps

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

Откройте параметры безопасности, перейдя на веб-портал и выбрав аватар в правом верхнем углу пользовательского интерфейса. Выберите «Безопасность » в появившемся меню.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Щелкните + Создать ключ.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

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

Избегайте добавления пробелов или новых строк в поле «Данные ключа«, так как они могут привести к тому, что Azure DevOps Services использовать недопустимый открытый ключ. При вставке в ключ в конце часто добавляется новая строка. Не забудьте удалить эту новую линию, если она возникает.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Присвойте ключу полезное описание (это описание будет отображаться на странице открытых ключей SSH для профиля), чтобы его можно было запомнить позже. Нажмите кнопку «Сохранить «, чтобы сохранить открытый ключ. После сохранения ключ изменить нельзя. Вы можете удалить ключ или создать новую запись для другого ключа. Нет ограничений на количество ключей, которые можно добавить в профиль пользователя.

Шаг 3. Клонирование репозитория Git с помощью SSH

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

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

При использовании Azure DevOps Services формат URL-адреса проекта имеет следующий dev.azure.com// формат. Однако предыдущий формат, ссылающийся на формат, по-прежнему visualstudio.com поддерживается. Дополнительные сведения см. в статье «Знакомство с Azure DevOps» для переключения существующих организаций на использование нового URL-адреса доменного имени.

Выполните git clone в командной строке.

SSH отображает этот отпечаток при подключении к неизвестному узлу и защищает вас от атак типа «злоумышленник в середине». Приняв отпечаток узла, SSH не выводит запрос повторно, пока отпечаток не изменится.

Вопросы и устранение неполадок

Вопрос. После выполнения git clone я получаю следующую ошибку. Что следует делать?

Вопрос. Как можно запомнить парольную фразу Git для моего ключа в Windows?

Ответ. Выполните следующую команду, включенную в Git для Windows, чтобы запустить ssh-agent процесс в PowerShell или командной строке Windows. ssh-agent кэширует парольную фразу, поэтому вам не нужно предоставлять ее при каждом подключении к репозиторию.

Если вы используете оболочку Bash (включая Git Bash), запустите ssh-agent с помощью:

Вопрос. Я использую PuTTY в качестве клиента SSH и создал ключи с помощью PuTTYgen. Можно ли использовать эти ключи с Azure DevOps Services?

Ответ. Да. Загрузите закрытый ключ с помощью PuTTYgen, перейдите в меню «Преобразования » и выберите «Экспорт ключа OpenSSH«. Сохраните файл закрытого ключа и выполните действия по настройке ключей, отличных от ключей по умолчанию. Скопируйте открытый ключ непосредственно из окна PuTTYgen и вставьте его в поле «Данные ключа » в параметрах безопасности.

Вопрос. Как проверить, что отправленный открытый ключ совпадает с ключом локально?

Ответ. Вы можете проверить отпечаток открытого ключа, отправленного в профиль, с помощью следующей ssh-keygen команды, выполняемой с открытым ключом, с помощью командной bash строки. Если вы не используете значения по умолчанию, необходимо изменить путь и имя файла открытого ключа.

Затем можно сравнить подпись MD5 с подписью MD5 с подписью в профиле. Эта проверка полезна при возникновении проблем с подключением или неправильной вставке открытого ключа в поле «Данные ключа» при добавлении ключа в Azure DevOps Services.

Вопрос. Как начать использовать SSH в репозитории, где сейчас используется ПРОТОКОЛ HTTPS?

Ответ. Чтобы изменить url-адрес HTTPS на SSH, необходимо обновить удаленное origin приложение в Git. Получив URL-адрес клонирования SSH, выполните следующую команду:

В: Я использую Git LFS с Azure DevOps Services, и при извлечении файлов, отслеживаемых Git LFS, возникают ошибки.

О: В настоящее время службы Azure DevOps Services не поддерживают LFS по протоколу SSH. Используйте протокол HTTPS для подключения к репозиториям с отслеживаемыми файлами Git LFS.

Вопрос. Как использовать расположение ключа, отличное от значения по умолчанию, т. е. не

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

Перед запуском ssh-add в Windows необходимо выполнить следующую команду из Git для Windows:

Эта команда выполняется как в PowerShell, так и в командной строке. Если вы используете Git Bash, необходимо выполнить следующую команду:

Вы можете найти ssh-add в составе дистрибутива Git для Windows, а также запустить его в любой среде оболочки в Windows.

Вопрос. У меня есть несколько ключей SSH. Разделы справки использовать разные ключи SSH для разных серверов или репозиториев SSH?

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

Однако это не работает с Azure DevOps по техническим причинам, связанным с протоколом SSH и структурированием URL-адресов SSH Git. Azure DevOps будет слепо принимать первый ключ, который клиент предоставляет во время проверки подлинности. Если этот ключ недопустим для запрошенного репозитория, запрос завершится ошибкой следующей ошибки:

Для Azure DevOps необходимо настроить SSH для явного использования определенного файла ключа. Один из способов сделать это для изменения

/.ssh/config файла (например, /home/jamal/.ssh или C:\Users\jamal\.ssh ) следующим образом:

Вопрос. Разделы справки исправить ошибки, которые упоминают «не найдено соответствующего метода обмена ключами»?

Ответ. Git для Windows 2.25.1 поставляется с новой версией OpenSSH, которая по умолчанию удалила некоторые протоколы обмена ключами. В частности, diffie-hellman-group14-sha1 был определен как проблематичный для некоторых клиентов Azure DevOps Server и TFS. Чтобы обойти проблему, добавьте следующую команду в конфигурацию SSH (

Вопрос. Какие уведомления можно получить о ключах SSH?

Ответ. Каждый раз, когда вы регистрируете новый ключ SSH в Azure DevOps Services, вы получите уведомление по электронной почте о том, что новый ключ SSH добавлен в вашу учетную запись.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Вопрос. Что делать, если я считаю, что кто-то, кроме меня, добавляет ключи SSH в мою учетную запись?

Ответ. Если вы получили уведомление о регистрации ключа SSH и не отправили его в службу вручную, возможно, ваши учетные данные были скомпрометированы.

Следующим шагом будет изучение того, был ли ваш пароль скомпрометирован. Изменение пароля всегда является хорошим первым шагом для защиты от этого вектора атаки. Если вы являетесь пользователем Azure Active Directory, обратитесь к администратору, чтобы проверить, использовалась ли ваша учетная запись из неизвестного источника или расположения.

Чтобы обойти эту проблему, добавьте следующий код в конфигурацию SSH (

How to Install Git on Windows and Set Up SSH Keys for GitHub

Introduction

Developers are usually more used to Unix based system to set up all environments, but there are times we have to use Windows. If this is the case, setting up Git on windows is a must. This article briefly reviews all the steps from Git installation to SSH set up. Hope you find this article helpful.

Overview

1. Install Git on Windows

First download Git for Windows on the official website: git-scm.com/downloads

Run the downloaded file and do the setup.

On the “Select Components” page, we can leave it as is, or you can change upon your own preference.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

On the “Adjusting your PATH environment” page, we want to select the first option: “Use Git from Git Bash only“, unless you really want to use Windows Command Prompt. Git Bash feels like a unix-like terminal and it is capable to do most of the work we need.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

On the “Configuration the line ending conversions” page, you can select based on your need. Again, I would recommend the third option: “Checkout as-is, commit as-is“, as this is the safest option for our code.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Next page, we can just select the first option: “Use MinTTY“.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

On the “Configuring extra options” and “Configuring experimental options” page, leave as it or select on your need.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

Now we can just hit the Install button and finish the installation.

Once it is installed, we can open the Git Bash and give it a try. Type git command.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

2. Set up SSH Keys

Now that we got Git running, it is time to set up SSH keys for Git, so that we don’t need to input password every time. It is more convenient but also safer.

The concept is we create a public/private key pair; put the public key to the remote server, and keep the private key on your local machine. The server can authenticate the client if the client has the corresponding private key.

First we need to generate key pair. Type this command on Git Bash:

For now, we can just press Enter to use default key name and empty passphrase.

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

‘id_rsa’ is the private key, and ‘id_rsa.pub’ is the public key.

then it should work out-of-the-box without any configuration.

To verify SSH is working for our Git, we can try the following command on Git Bash:

If everything works well, then the prompt would say “ You’ve successfully authenticated “.

Last thing, to use SSH login, the remote urls of repositories need to be SSH type, instead of HTTPS type. See here to change it.

3. Things need to be careful with

How to set ssh key for git. Смотреть фото How to set ssh key for git. Смотреть картинку How to set ssh key for git. Картинка про How to set ssh key for git. Фото How to set ssh key for git

End

Thanks for your reading. Please leave comments if you have any questions.

2 Replies to “How to Install Git on Windows and Set Up SSH Keys for GitHub”

Please update and perhaps a further explanation for AWS newbies.

Источники информации:

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

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