Перейти к содержимому

Как подключиться к гиту по ssh

  • автор:

Setting up SSH and Git on Windows 10

Welcome to my first official guide on Dev.to. Today I want to explain how you can setup SSH and Git on your Windows 10 computer.

Note: This is not about 100% securing your keys but about how to generate keys for use with GitHub.

Thanks to garethdd for his constructive feedback.

What is SSH?

SSH stands for Secure Shell and is an awesome way to authenticate yourself on remote servers (for example the Github server) without typing in a password everytime.

SSH works via two keys, the Private Key and the Public Key. While the private key should always stay private and safe, the public key can be shared around the internet without any problems.

The private key allows you to get access to servers that have your public key registered, so your access can only be stolen if the attacker somehow gets your Secret Key so keep it safe!

SSH should be preinstalled on new Windows 10 machines.

What is Git?

Git is a free version management tool that helps you to versionize your code and potentially save it on a remote server (for example Github, Gitlab or Bitbucket).

You can also install Git via chocolatey:

Create a SSH Key

The first step is to generate a new SSH key. Use cmd or Powershell and run the following command:

You can but don’t need to give it a passphrase since you should never share your secret key around but using one will secure your keys. Keep in mind that everybody can have as many private keys as they want.

This generates a new private SSH key with rsa encryption and 4096 bits. It also generates a public key from the secret key which you can share around.

There will be a new folder and files in your Windows user folder.

In general you can create as many keys as you want. The id_rsa key is the default key generated by ssh and will be automatically be used by your ssh-agent if you don’t tell it to use another key.

What is an ssh-agent?

An ssh-agent is the agent process used to actually authenticate yourself with ssh. There are a few out there (PuTTY with Pageant for example) but for this example we’ll use the ssh-agent provided by the native and default Windows 10 ssh-agent.

If you want to you can use PuTTY and Pageant to make your keys even more secure. Read this post on Digital Ocean for more information.

If you want to change the key used by your ssh-agent, you must first start the service. The service will be disabled on Windows 10 by default. Search for Services and open the Services settings and look for the «OpenSSH Authentication Agent» and Activate it:

Now you will be able to access the ssh-agent from your console via ssh-agent .

For this example we’re going to try to load another key called example into our agent and use it instead of the id_rsa key. To do this you can run the following command:

Now you will have both keys available for this session.

Register your SSH Key on Github

The next step is to register your generated SSH key on Github. For that, run the following command:

and copy the output string into your clipboard. Now go to your Github keys settings and add a new SSH key with your public key and save it.

Congratulations! You now are able to get and push code to Github without any password!

Note: There should also be a C:\Users\your_user_name\.ssh\id_rsa file. This is your private key, don’t share this around!

Setup Github in your Shell

Now it’s time to setup Git on your machine. After installing it from the link above, open a new cmd or Powershell window. Now we need to set your public Git name and Git email address. This will always be public when pushing code.

Luckily Github gives you a privatized email address for use. Go to https://github.com/settings/emails and you will find a @users.noreply.github.com email address for your account. Copy this email address.

Next register your name and email in Git:

Congratulations! Now all your Commits will be registered as being commited from your Github user.

Signing your GitHub commits (Optional Step)

To sign your commits you first must install the GPG command line tools. After you installed the GPG toolkit, you can run the following command to generate a new gpg key:

This will ask you what kind of key you want. Go for RSA and RSA.

Now you need to enter a bit length. The recommendation is 4096 bits.

After that you can specify a expiration length or if the key should never expire. Pick as you want. Expiring keys are more secure in general because you have to renew them every now and then.

Now enter your personal informations to verifying your identity with your gpg key.

When you’re done you will be asked for a passphrase. Give it a secure passphrase and you will be done with your gpg-key generation.

After that you will be able to find your key in your users .gnupg folder as specified in the success message.

If you want to list your gpg keys, simply run

Your GPG key you can share with Github is the key coming after sec rsa4096/ so for example in

the gpg key would be 3AA5C34371567BD2

To get your public key block, simply run

which will output your public GPG Key Block. Copy it and paste it to your GitHub Account here.

From now on your commits will be signed when commited.

Use Git

Now you’re ready to actually use Git. From now you can clone repositories via git clone or push new code to Github. Here is a quick reference:

Conclusion

Thanks for reading this post. I hope it helped you with the setup. If you need help or have questions let me know!

Что такое SSH-ключ в Git?

SSH-ключ — это учетные данные для доступа по сетевому протоколу Secure Shell (SSH). С помощью этого аутентифицированного и зашифрованного безопасного сетевого протокола обеспечивается удаленная связь между машинами, находящимися в незащищенной открытой сети. Протокол SSH используется для удаленной передачи файлов, управления сетью и удаленного доступа к операционной системе. Кроме того, аббревиатурой SSH описывают набор инструментов, используемых для взаимодействия по протоколу SSH.

SSH использует пару ключей, чтобы инициировать безопасное квитирование установления связи между удаленными сторонами. Пара состоит из открытого и закрытого ключей. Эти названия могут сбить с толку, поскольку оба элемента называются ключами. Лучше рассматривать открытый ключ как «замок», а закрытый ключ — как «ключ». Вы выдаете удаленным сторонам «замок» для шифрования или «запирания» данных. Затем эти данные открываются с помощью закрытого ключа, который вы храните в надежном месте.

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

SSH-ключи генерируются с помощью криптографических алгоритмов с открытым ключом (чаще всего имеют в виду RSA и DSA). Если говорить в общих чертах, SSH-ключи генерируются с помощью математической формулы, которая содержит два простых числа и случайную начальную переменную для вывода открытого и закрытого ключей. С помощью этой односторонней формулы можно получить открытый ключ из закрытого, но не наоборот.

Создать SSH-ключи можно с помощью инструмента генерации ключей. В набор инструментов командной строки SSH входит утилита keygen. Кроме того, большинство хостинг-провайдеров git предлагают руководства по созданию SSH-ключа.

Создание SSH-ключа на Mac и Linux

В операционных системах OS X и Linux доступны комплексные современные приложения-терминалы, которые поставляются с предустановленным набором инструментов SSH. Создание SSH-ключа проходит одинаково в обеих операционных системах.

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

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

2. Затем вам будет предложено указать файл, где будет сохранен ключ.
Укажите расположение файла или нажмите клавишу «Ввод», чтобы принять расположение по умолчанию.

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

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

4. Добавьте новый SSH-ключ в ssh-agent.

ssh-agent — это еще одна программа, входящая в набор инструментов SSH. В ней хранятся закрытые ключи, поэтому ее можно рассматривать как брелок. Кроме того, она обрабатывает запросы на подпись SSH-запросов с помощью закрытых ключей, чтобы такие ключи всегда передавались безопасно.

Перед добавлением нового SSH-ключа в ssh-agent убедитесь, что программа запущена выполнив следующую команду:

После запуска ssh-agent добавьте новый SSH-ключ в локальный агент SSH с помощью следующей команды.

Теперь новый SSH-ключ зарегистрирован и готов к использованию.

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

В средах Windows нет стандартной unix-оболочки, поэтому для полноценной работы с инструментом keygen вам потребуется установить сторонние программы оболочки. Самый простой вариант для этих целей — решение Git Bash. После его установки вы сможете выполнять в оболочке Git Bash те же действия, что в Linux и Mac.

Подсистема Linux для Windows

Современные среды Windows предлагают подсистему Linux для Windows с полноценной оболочкой. Если вам доступна эта подсистема, вы можете выполнить в ней те же шаги, которые были описаны выше для Linux и Mac.

Резюме

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

Clone Repository Using SSH in Git

Harish Rajora

In the previous tutorials about SSH, we have learned What SSH Authentication is and How to Generate SSH Keys in Git. By now, we hope that you have a good understanding of SSH and have generated the SSH keys on your system.

In this tutorial, we will share some thoughts on cloning a remote GitHub repository using SSH. Cloning is one of the main processes of Git. I mean, if you don’t have the code, how will you contribute? Earlier in this course, we came across cloning in Git using HTTPS. Cloning with SSH is almost similar to that with a few hidden twists. But, before cloning with SSH, you must be equipped with some of the pre-requisites:

One of the main advantages of using SSH for cloning is that you don’t have to enter the password multiple times for the hundreds of operations you do in a day. It is made possible by a tool or program called ssh-agent. Before starting the cloning process and downloading a repository on our local system, it is better to make you understand a simple yet relevant term called SSH Agent.

What is SSH Agent?

SSH Agent is a helper program for signing in to the clients, which, well, requires signing in. So why do we need an ssh-agent when we know the password? Well, for the same reason that we are interested in SSH apart from its security. Using ssh-agent for our signing purposes will require the user to sign-in only once, and the ssh-agent will handle the rest of the authentication throughout the session. SSH-Agent provides a secure way to save your passphrase and use them with the client programs. The user need not worry about the security of their passphrase as ssh-agent does not share or hand over these keys while authenticating with the client programs. SSH-Agent opens up a socket over which the client and the user can exchange the signed data. So, there is no need for the user to worry at all.

SSH-Agent comes by default in the Linux-based systems and Git Bash, of course. So, without any extra work, ssh-agent will be active and begin to play once the user opens up the terminal in the Linux-based system and Git Bash. But, if you are using some other SSH client to use it over any other operating system than Linux, you need to follow a few steps.

Setting Up SSH-Agent in the Local System

For setting up SSH-Agent, open your Git Bash in the directory.

Type the following command:

Cloning Repository using SSH - Eval ssh agent

Execute the command by pressing enter.

Cloning Repository using SSH - Agent pid

Agent Xyz will show that the ssh-agent is up and running. The number Xyz displayed on the screen is the process id of the process "ssh-agent."

Adding Keys to SSH Agent

Once we have ssh-agent running, we need to add the keys to the ssh-agent by the following command:

Cloning Repository using SSH - ssh add keys ssh agent

Execute the command by pressing enter, and the keys will add to your account.

identity-added

If you have received the same message as above, it implies the successful addition of your keys to the ssh-agent.

Now that we are all set up let’s clone the repository using ssh.

How To Clone Repository Using SSH Protocol?

Cloning a repository using SSH is very simple, especially if you are already familiar with cloning through the HTTPS protocol. Before cloning, although, you should confirm that you have checked the following steps:

    .
  • Have Generated the SSH keys.
  • Have Added the SSH keys to your GitHub account.
  • Have started SSH-Agent (For Non-Linux and Non-Git Bash Users).
  • Have added keys to your SSH-Agent (For Non-Linux and Non-Git Bash Users).

The last two steps are optional, though.

After checking the above-given steps, navigate to your GitHub account to the repository page which you want to clone.

ToolsQA-Repo-Home

Press Clone or download and press Use SSH in the panel that appears.

The panel will change to Clone with SSH with the updated link. clone-with-ssh

Copy the link by pressing the Copy To Clipboard icon.

copy-ssh-link

Open Git Bash and navigate to the directory in which you want to clone the repository.

Check the contents of the repository through ls command.

repository-content

Type the following command in the Git bash to clone the repository using SSH.

git-clone-ssh

Cloning into ToolsQA will show that the cloning is in progress.

Cloning-into-Toolsqa-ssh

The following message will appear when the cloning completes.

cloning-done-ssh

Again check the contents of the directory through ls command and notice the creation of the repository.

toolsqa-created

Simple, isn’t it? Cloning is the core part of Git. Since GitHub brings people to come together with similar interests and contribute to each other’s projects, cloning is what enables this process. Again, as I said earlier, using SSH or HTTPS is solely on the individual to use. With this tutorial, we complete the SSH section in GitHub and Git and now will move towards branches in Git.

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

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

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

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

Будет создан ключ 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 без ввода пароля от своей учетной записи.

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

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

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

Luxury Car Rental in Miami | Reserve a Premium Vehicle with RealCar