- Git SSH Windows — пошаговое руководство
- Генерация ключа SSH
- Добавление SSH-ключа в ssh-agent
- Добавление ключа SSH в учетную запись GitHub
- 4.3 Git на сервере — Генерация открытого SSH ключа
- Генерация открытого SSH ключа
- Adding a new SSH key to your GitHub account
- Generating a new SSH key and adding it to the ssh-agent
- In this article
- Generating a new SSH key
- Adding your SSH key to the ssh-agent
- bsara / git-ssh-auth-win-setup.md
- This comment has been minimized.
- pensebien commented Nov 28, 2017 •
- This comment has been minimized.
- rianquinn commented Feb 27, 2018
- This comment has been minimized.
- leoreeves commented Mar 6, 2018 •
- This comment has been minimized.
- pauljohn32 commented Mar 18, 2018
- This comment has been minimized.
- smutel commented Mar 22, 2018
- This comment has been minimized.
- gregbown commented May 14, 2018
- This comment has been minimized.
- demiters commented Aug 27, 2018
- This comment has been minimized.
- fushenghua commented Sep 4, 2018
- This comment has been minimized.
- bonovski commented Sep 13, 2018
- This comment has been minimized.
- surjikal commented Sep 15, 2018
- This comment has been minimized.
- Tri125 commented Jan 2, 2019
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-агент введите следующую команду.
На экране отобразится похожая строка.
Agent pid 31724
Добавим свой закрытый ключ 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.
4.3 Git на сервере — Генерация открытого SSH ключа
Генерация открытого SSH ключа
Как отмечалось ранее, многие Git-серверы используют аутентификацию по открытым SSH-ключам. Для того чтобы предоставить открытый ключ, каждый пользователь в системе должен его сгенерировать, если только этого уже не было сделано ранее. Этот процесс аналогичен во всех операционных системах. Сначала вам стоит убедиться, что у вас ещё нет ключа. По умолчанию пользовательские SSH ключи сохраняются в каталоге
/.ssh домашнем каталоге пользователя. Вы можете легко проверить наличие ключа перейдя в этот каталог и посмотрев его содержимое:
Ищите файл с именем id_dsa или id_rsa и соответствующий ему файл с расширением .pub . Файл с расширением .pub — это ваш открытый ключ, а второй файл — ваш приватный ключ. Если указанные файлы у вас отсутствуют (или даже нет каталога .ssh ), вы можете создать их используя программу ssh-keygen , которая входит в состав пакета SSH в системах Linux/Mac, а для Windows поставляется вместе с Git:
Сначала программа попросит указать расположение файла для сохранения ключа ( .ssh/id_rsa ), затем дважды ввести пароль для шифрования. Если вы не хотите вводить пароль каждый раз при использовании ключа, то можете оставить его пустым или использовать программу ssh-agent . Если вы решили использовать пароль для приватного ключа, то настоятельно рекомендуется использовать опцию -o , которая позволяет сохранить ключ в формате, более устойчивом ко взлому методом подбора, чем стандартный формат.
Теперь каждый пользователь должен отправить свой открытый ключ вам или тому, кто администрирует Git-сервер (подразумевается, что ваш SSH-сервер уже настроен на работу с открытыми ключами). Для этого достаточно скопировать содержимое файла с расширением .pub и отправить его по электронной почте. Открытый ключ выглядит примерно так:
Adding a new SSH key to your GitHub account
To configure your GitHub account to use your new (or existing) SSH key, you’ll also need to add it to your GitHub account.
Before adding a new SSH key to your GitHub account, you should have:
After adding a new SSH key to your GitHub account, you can reconfigure any local repositories to use SSH. For more information, see «Switching remote URLs from HTTPS to SSH.»
Note: DSA keys (SSH-DSS) are no longer supported. Existing keys will continue to function, but you cannot add new DSA keys to your GitHub account.
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.
Tip: If pbcopy isn’t working, you can locate the hidden .ssh folder, open the file in your favorite text editor, and copy it to your clipboard.
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.
Tip: If clip isn’t working, you can locate the hidden .ssh folder, open the file in your favorite text editor, and copy it to your clipboard.
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.
Tip: If xclip isn’t working, you can locate the hidden .ssh folder, open the file in your favorite text editor, and copy it to your clipboard.
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».
Generating a new SSH key and adding it to the ssh-agent
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.
In this article
If you don’t already have an SSH key, you must generate a new SSH key. If you’re unsure whether you already have an SSH key, check for existing keys.
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
Open Terminal Terminal Git Bash .
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:
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, replacing
/.ssh/id_ed25519 if you are not using the default location and name for your id_ed25519 key.
Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
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.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an ssh key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
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.
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.
bsara / git-ssh-auth-win-setup.md
Setup SSH Authentication for Git Bash on Windows
- Create a folder at the root of your user home folder (Example: C:/Users/uname/ ) called .ssh .
- Create the following files if they do not already exist (paths begin from the root of your user home folder):
- .ssh/config
- .bash_profile
- .bashrc
Create a New SSH Key
Follow the steps in the section named «Generating a new SSH Key» found in the following documentation from GitHub: Generating a new SSH key and adding it to the ssh-agent
Configure SSH for Git Hosting Server
Add the following text to .ssh/config ( .ssh should be found in the root of your user home folder):
Enable SSH Agent Startup Whenever Git Bash is Started
First, ensure that following lines are added to .bash_profile , which should be found in your root user home folder:
Now, add the following text to .bashrc , which should be found in your root user home folder:
This comment has been minimized.
Copy link Quote reply
pensebien commented Nov 28, 2017 •
Thank you for the gist. But I found it easy to just add to my
./profile file
localUser@mycomputer MINGw64 / notepad /.profile
then I Paste this
I also took time to read about ssh-agent
This comment has been minimized.
Copy link Quote reply
rianquinn commented Feb 27, 2018
This worked perfectly, Thanks
This comment has been minimized.
Copy link Quote reply
leoreeves commented Mar 6, 2018 •
@emmaakin, thanks that works great. FYI, there’s a backtick at the start and end your code snippet that will cause an error.
This comment has been minimized.
Copy link Quote reply
pauljohn32 commented Mar 18, 2018
The part that launches the ssh agent is valuable. However, I’m not persuaded there is a benefit in the git config file. The Default key name is «id_rsa» and that is what ssh will look for. I think the config file is not having an effect. At least for me.
In my case, the name of the key is different for every server and, for reasons I cannot understand, the ssh system only wants to look for «id_rsa». On Linux, this is a symptom of a permissions problem, permissions should be 700. But in Windows, it appears not possible to set permissions at all. In the Git bash shell, permissions always have g+r and o+r.
The config file is ignores, at least for me. You can see same result if you name your key in another file, put in
And it wont work. If it does work, I’d love to hear from you.
This comment has been minimized.
Copy link Quote reply
smutel commented Mar 22, 2018
If you use an old dsa key, put this in config PubkeyAcceptedKeyTypes=+ssh-dss
This comment has been minimized.
Copy link Quote reply
gregbown commented May 14, 2018
Wow! First of all, thank you! I am astonished as to why none of this presented anywhere on GitHub? I spent a couple of hours looking for the missing steps, All they say is paste your public key here with no mention of how GitHub is supposed to find the private key on Windows, where it should be stored, what else is required, etc.
The only thing I would add to this is that if you are generating you keys with PuTTY Key Generator, you must select from the menu -> Conversions -> Export SSH key(force new file format) and save the private key as just «id_rsa» NOT id_rsa.ppk the default PuTTY format
Thank you again Brandon
This comment has been minimized.
Copy link Quote reply
demiters commented Aug 27, 2018
This comment has been minimized.
Copy link Quote reply
fushenghua commented Sep 4, 2018
This comment has been minimized.
Copy link Quote reply
bonovski commented Sep 13, 2018
Thank you, works perfectly!
bitbucket and github are really missing these crucial steps, lost almost 8 hours setting it up on windows.
This comment has been minimized.
Copy link Quote reply
surjikal commented Sep 15, 2018
I added this to /etc/ssh/ssh_config so that I could use a shared deployment key for all users on my server. Thanks for the info!
This comment has been minimized.
Copy link Quote reply
Tri125 commented Jan 2, 2019
If you want to add multiple keys to the agent simply replace the line ssh-add
/.ssh/id_rsa; with the following block:
This will add every ssh key that start with id_
The inconvenience is that when the ssh-agent start, it’s going to prompt you to enter the password for every keys even if you don’t necessarily use them. I haven’t found a solution for this.
You might want to use that with git for windows if, say, you have a different github account: 1 for your personal work and another for your professional work. Github won’t let you re-use the same ssh key for both accounts so you need 2 keys.
To make this work, you will need to do 2 more steps. in $
In this example, we have the secondary ssh key named id_rsa_corpo .
If you already cloned the repo for the secondary key, change the remote to point to github-corpo .
If not, then just clone by replacing the host :