Git SSH Windows — пошаговое руководство
Настроим пошагово Git SSH для Windows 10. Это позволит вам выполнять команды git без ввода пароля от своей учетной записи GitHub.
- Генерация ключа SSH.
- Добавление SSH-ключа в ssh-agent.
- Добавление ключа SSH в учетную запись 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-агент введите следующую команду.
На экране отобразится похожая строка.
Добавим свой закрытый ключ SSH в ssh-agent . Если вы создали свой ключ с другим именем (или добавляете существующий ключ с другим именем), замените в команде id_rsa на имя вашего файла закрытого (приватного) ключа.
Ключ будет успешно добавлен в ssh-агент .
Добавление ключа SSH в учетную запись GitHub
Мы сгенерировали у себя на компьютере закрытый ключ SSH и добавили его в ssh-агент . Теперь нам необходимо добавить SSH ключ в учетную запись GitHub.
Сейчас нам необходимо скопировать SSH ключ в буфер обмена.
Способов есть несколько, но я же вам предлагаю следующее решения для Windows 10: введите команду ниже.
Прямо в терминале вы увидите содержимое необходимого файла с ключем. Скопируйте его в буфер.
Теперь зайдите на вашу страницу GitHub Settings .
Перейдите во вкладку SSH and GPG keys и нажмите на кнопку New SSH key для добавления SSH ключа в вашу учетную запись GitHub.
В поле Title добавьте заголок для данного ключа. Например, если вы захотите настроить SSH доступ на нескольких устройствах, то вы будите понимать какой ключ принадлежит какому устройству.
В поле Key добавьте свой ssh-ключ, который вы скопировали в буфер обмена на предыдущем шаге.
Нажмите Add SSH key .
Для подтверждения вам потребуется ввести свой пароль от учетной записи GitHub .
На этом настройка SSH для вашего устройства завершена, теперь вы можете работать с git без ввода пароля от своей учетной записи.
Если вам понравилась данная статья, можете прочитать как настроить моментальную загрузку сайта на хостинг и синхронизацию файлов.
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.
how to add existing key to openssh on windows?
I have been using putty/plink/pageant + tortoiseGIT on many computers, and found it difficult and painful and does not work with eclipse.
So I decided to install tortoiseSVN and windowsGIT selecting the openssh version instead of the putty version.
I have an existing key installed in github, and I have the ppk file which was generated which I would had to manually load each time I wanted to use it in pagaent.
But Now I am stuck. How do I do this using openssh? What is the openSSH equivalent of pageant?
I suspect I have to convert the ppk into id_rsa.pub or simlar, but they what do I do with them to be usable on the local machine?
Do I have to install something called openSSH in the same way I installed putty? Does it have something like pageant?
Or should I give up and go back to using putty for SSH (and having to manually load keys every time)
Edit 1. Not found anything in 2h of googling this. Im going to take a wild guess that openssh is not something I need to install, but is something which came with git install. Im going to guess that because there is no mention of it, that windows uses the same scheme as unix, i.e. put the keys
/.ssh/. So I used puttygen to load my ppk, then «export openSSH key». Then i tried saving it as both
/.ssh/mykey.rsa and mykey.dsa (no idea which it should be). This did not work — tortoise git still says
The problem I guess is that there is no way to know if puttygen is exporting the public or private key — it doesnt give you the option.
I also tried saving as id_rsa and id_dsa, no luck.
2 Answers 2
Some background
OpenSSH has no equivalent of pageant. Well, almost. It has an ssh-agent.exe program (man page) and an accompanying ssh-add.exe program (man page) to add keys to the agent.
The unfortunate (for Windows) thing is that the workflow assumed by ssh-agent is like this:
You run it, it prints some information about how it can be reached (by ssh-add ) then detaches from the terminal and goes to the background.
The information it prints is presented in the form of a Unix shell code which sets some environment variables, so most of the time it’s supposed to be run like this:
While this sounds complicated, on any sensible Unix-like system, your Desktop Environment will make sure the SSH agent is spawned early at startup and the environment variables handed off by it are used and are inherited by all the programs later started by the user. So it just works™ without you even noticing.
You run ssh-add to feed keys to a running instance of ssh-agent .
This program locates the agent using the environment variables set on step one.
As you can see, this model does not need to know about graphical user environments etc so you won’t get any fancy tray icon and some sort of GUIs to feed your keys to the agent.
Since this obviously doesn’t play well with the way a user’s session is created in Windows, PuTTY implements its own approach to provide an SSH agent, its own means to locate the running agent and its own protocol to talk with it.
What you can do about this
Continue using PuTTY.
I don’t use Eclipse but I know it uses JGit to work with the repository and talk with remote servers. So if you’ll find a way to tell JGit how to use your own SSH client program to set up an SSH tunnel (like Git for Windows does with its GIT_SSH environment variable) you’ll be able to use Eclipse with PuTTY.
Forfeit the security of your SSH key and work without the need for SSH agent.
Select private key to use with Git
I have 2 Git servers that require 2 different SSH keys.
git clone user1@server1:blahblahblah uses
/.ssh/id_rsa , but I need to specify which key to use depending on the server I am connecting to.
What Git command-line parameter does this job? (I am running Linux.)
9 Answers 9
If you are connecting via SSH then the key will be controlled by an SSH parameter, not a git parameter.
/.ssh/config file for configuration parameters. Modify that file and add IdentityFile entries for the two Git servers like this:
This article has some more details.
There is another possibility. That’s to set core.sshCommand , e.g.
There’s one particular scenario when this strategy is particularly useful: that’s when you have multiple accounts on Github, as all accounts ssh to Github as git@github.com and it uses the ssh key to determine which Github user you are. In this case neither .ssh/config nor ssh-agent will do what you want.
Update — You cannot run the above until you have a local repository, so if you’re trying to clone a remote repository, you’ll need to specify the key manually as per drewbie18’s answer:
Once you’ve cloned the repository you can use the git config command to set this permanently.
/.ssh/config (and even /etc/hosts, in case of multiple accounts on the GitHub). – mr.b Aug 15 ’17 at 8:21
Generally, you want to use
/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:
Host * denotes any server, so I use it to set
/.ssh/id_rsa as the default key to use.
In my scenario, similar to @Richard Smith scenario (whose solution, BTW, didn’t work for me), I need to use different keys for the same server under different repositories.
The workaround for me was to set up the session correctly with the environment variable GIT_SSH_COMMAND , like so:
Update:
Another thing to note here is that setting the environment variable correctly can be a hustle, so I’m using the command prompt modification facilities provided by things like Liquid Prompt or Fish Shell to hook into the shell and keep updating the environment variables according to the current directory and some rules. For example, all my personal projects that need to my personal SSH key with Gitlab are under
/Documents/Projects/personal so when the shell hook runs pwd and finds that the current directory is under that path, it automatically sets the GIT_SSH_COMMAND variables as needed.




