How to use ssh key github
How to use ssh key github
Working with SSH key passphrases
In this article
You can secure your SSH keys and configure an authentication agent so that you won’t have to reenter your passphrase every time you use your SSH keys.
About passphrases for SSH keys
With SSH keys, if someone gains access to your computer, the attacker can gain access to every system that uses that key. To add an extra layer of security, you can add a passphrase to your SSH key. To avoid entering the passphrase every time you connect, you can securely save your passphrase in the SSH agent.
Adding or changing a passphrase
You can change the passphrase for an existing private key without regenerating the keypair by typing the following command:
If your key already has a passphrase, you will be prompted to enter it before you can change to a new passphrase.
Auto-launching ssh-agent on Git for Windows
You can run ssh-agent automatically when you open bash or Git shell. Copy the following lines and paste them into your
/.bashrc file in Git shell:
If your private key is not stored in one of the default locations (like
/.ssh/id_rsa ), you’ll need to tell your SSH authentication agent where to find it. To add your key to ssh-agent, type ssh-add
Now, when you first run Git Bash, you are prompted for your passphrase:
The ssh-agent process will continue to run until you log out, shut down your computer, or kill the process.
Saving your passphrase in the keychain
On Mac OS X Leopard through OS X El Capitan, these default private key files are handled automatically:
The first time you use your key, you will be prompted to enter your passphrase. If you choose to save the passphrase with your keychain, you won’t have to enter it again.
Otherwise, you can store your passphrase in the keychain when you add your key to the ssh-agent. For more information, see «Adding your SSH key to the ssh-agent.»
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
xirixiz / Set up GitHub push with SSH keys.md
SSH keypair setup for GitHub (or GitHub/GitLab/BitBucket, etc, etc)
Make sure there is at least one file in it (even just the README.md)
Generate a SSH key pair (private/public):
Copy the contents of the public SSH key
GNU/Linux (requires the xclip package):
Windows Command Line:
Git Bash on Windows / Windows PowerShell:
or ofcourse copy it via your favorite editor, cat, or whatever suits your needs 🙂
Copy the public SSH key to GitHub
Copy the contents of the to your SSH keys to your GitHub account settings (https://github.com/settings/keys).
Test the SSH key:
Change directory into the local clone of your repository (if you’re not already there) and run:
Now try editing a file (try the README) and then do:
You should not be asked for a username or password. If it works, your SSH key is correctly configured.
martinlicht commented Aug 19, 2021
git remote set-url origin git@github.com:username/your-repository.git thanks! That important line is missing in the official GitHub documentation.
pl-jay commented Sep 1, 2021
Caleb-Stripes commented Sep 2, 2021 •
When I run the command git remote set-url origin git@github.com: / I get a fatal error: No such remote ‘origin’
martinlicht commented Sep 2, 2021
bjwealthy commented Sep 12, 2021
great security feature
HaPuLo commented Oct 18, 2021
great security feature
almiavicas commented Oct 30, 2021
Thanks! It realy helps the git remote set-url line
satylogin commented Nov 13, 2021
Thanks for the writeup 🙂 They should really add the git remote set-url line in official setup.
tik9 commented Dec 24, 2021
@satylogin git remote set-url origin is clearly and a must be in the doks, look no further
tik9 commented Jan 25, 2022
tusharGitHub13 commented Feb 4, 2022
Thanks a lot really helpful to start journey on Github
rakzhodekams commented Feb 5, 2022
tik9 commented Feb 5, 2022
@rakzhodekams What code did you use? Usually you need a token, but let me see your code.
psychoslave commented Feb 8, 2022 •
Viha123 commented Feb 17, 2022
thank you very much, took longer than it should have but I got there.
trobutlef commented Apr 5, 2022 •
thank you! I’ve been struggling with this for hours.
cnske commented Apr 8, 2022
thank you! How to use this approach with several repos?
m-git-0 commented Apr 30, 2022
Thank you. This has improved my workflow
ShukuraliProgrammer commented Jun 2, 2022
I couldn’t solve with this solution
xirixiz commented Jun 3, 2022
Good description @ShukuraliProgrammer. Please be more clear what it is that’s not working out for you. Only then the community is able to help out.
RoboWanabe commented Jun 6, 2022
I’m currently having an issue, followed advice.. created keys, assigned to GitHub, tested connection with ssh. but still when i try to push i’m getting fatal: repository ‘https://github.com/user/repo.git/’ not found
Any ideas how to debug?
RoboWanabe commented Jun 6, 2022
just solved my own problem.
I was using https repo endpoints.. if your using SSH you need the SSH end points. use them when setting origin
Allways expanding my memory slots 😉
thangnv-works commented Jun 29, 2022
ctimmer commented Jul 28, 2022
I ran the ssh test and it ran as expected but when I run:
git push
I get the following response:
remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for ‘https://github.com/ctimmer/poll-looper/’
Why is the new authentication (ssh) being recognized? What am I missing?
CR-Wizard commented Jul 28, 2022
Do a git remote and make sure is includes SSH URLS.
There can be different endpoints for your repo, one is for the old password now deprecated way (https), the other is for SSH.. you can see the URL as different for both.
Go to your repo and click clone, select SSH, copy these URLS and change your remote on your repo.
Hope this makes sense.
ctimmer commented Jul 29, 2022
Doesn’t appear to be an SSH url. Where do I click «clone»?
ctimmer commented Jul 29, 2022
Got it wasn’t using the SSH url. Thanks for the help
gstano commented Aug 1, 2022
Thank you very much for this thread. I am a beginner using github. I have successfully used in the past following instructions (and even set up the key in the past). However, I had to re-install everything from scratch recently. I have the keys established, but for some reason, I cannot link them up with my local instance of git and the online instance.
I am following all of the instructions here, but I keep getting asked for a user name and password.
When I select yes, it does recognize me. As far as I can tell, it appears my old key is trying to be used versus the new key.
It is mildly annoying as I managed this once before, but cannot accomplish the task again, even with the various support threads.
Thank you for your time and help!
Geoffrey
How to Set Up an SSH Key to GitHub
So if you are tired of typing your username and password in just to make a simple push to GitHub, then today is your lucky day. The madness ends today. We are going to make the task effortless, by generating an SSH key and setting it up in GitHub.
Setting up SSH Authentication
This process of not needing to use a username and password is called SSH authentication. Basically you are going to generate a long random string of characters and symbols and instead of submitting a username and password, your computer will submit this long string. GitHub will compare the string with the one I told it belongs to my computer and if there is a match, then GitHub lets us through. Of course it is more complex than this behind the scenes, but this is good enough to understand it for now.
The basic process of getting this set up is as follows:
Part 1: Generate an SSH Key
Before we do anything, we need an SSH key to work with. We generate the key through the terminal or git bash. The following commands work on Windows, Linux, and Mac exactly the same. The only difference between the three operating systems is that Linux and Mac will use the terminal and Windows will use their Git Bash program.
You will be asked for a location to store the key and you will want to just click enter to save it in the default location.
Part 2: Add Your SSH Key to your SSH Agent
Next we need to let our computer’s SSH agent (the program that distributes and uses the SSH keys) to know which SSH key to use. You probably only have one SSH key on your computer, so this won’t be very hard, but you could theoretically have an infinite number of them. This is why we tell the SSH agent which one to use.
Of course first we need to enable the SSH agent:
Now you should have it enabled and you can now set it to use the key we just generated:
Now our SSH Agent, knows which key to use, so it is time to tell GitHub all about our adventures.
Part 3: Add the SSH Key to GitHub
All that is really needed at this point is to copy the ssh key and paste it into GitHub. The problem is that copying the code isn’t the easiest thing in the world. We need to use the terminal again. The problem is that this will vary depending on which OS you use.
MacOS:
Windows:
Linux:
You unfortunately don’t have a copy feature built into all distributions of Linux, so if you don’t have one already we will install xClip.
Now that you have it, you can copy it to your clipboard:
Now you will have your SSH key in your clipboard of your computer. You can simply paste it into GitHub. Log into GitHub and go to the settings page. You can access the settings page by clicking on your avatar in the top right and going to the bottom of the menu and choosing “Settings”
Now select SSH and GPG on the left hand side.
Select “Add New SSH” and paste your code into the large text field.
That is literally all there is! You just need to save the key and then start using git like you normally would inside the terminal.
Few Last Things
You will notice the first time you go to use the command that it will ask if you want to add github to a list of known hosts. You will want to type yes to these requests because it will remember that GitHub is safe and then not harass you about pushing to it anymore. After the first time you select that option, you shouldn’t have to do it again.
Переходим с HTTPS на SSH доступ в GitHub
Table of Contents
C 13 августа 2021 года Github блокирует доступ по HTTPS протоколу к репозиториям, то есть теперь вы не сможете, получить или отправить изменений в удаленный репозиторий без SSH ключа.
В этом гайде покажу как создать ключ, загрузить на сервер и перенастроить локальный репозиторий на SSH доступ. В качестве примера используется Windows 10 и GitBash.
Что необходимо #
Создание пары ключей SSH #
Открывайте GitBash или терминал, вводите:
После заходите в папку.
В итоге для запуска генерации ключа, выполните:
Вам будут заданы несколько вопросов:
Подтвердить кодовую фразу или ее отсутсвие, тоже нажав Enter.
В результате вам покажут рисунок вашего ключа:
Вывод должен быть таким:
Активация ключа #
Для того чтобы ключ использовался системой, необходимо добавить ключ в ssh-agent.
результат, номер процесса может отличаться:
Добавьте ранее созданный ключ:
При успехе получите ответ:
Ключи SSH готовы к использованию!
Добавление публичного ключа в профиль на GitHub #
ℹ Кратко про ключи. С помощью публичного ключа, каждый может зашифровать информацию, расшифровать может только владелец приватного ключа, поэтому приватный ключ нельзя передавать, отправлять или хранить в открытом виде. Желательно пару ключей дополнительно скопировать на отдельный носитель, на случай потери ключа на компьютере.
В GitHub для работы с репозиториями скопируйте публичный ключ, одним из способов:
это скопирует публичный ключ в буфер обмена.
Нажимайте не кнопку New SSH Key
В поле Key вставьте скопированный ключ:
В поле Title можете вставить название ключа, пригодится если у вас будет в профиле более одного ключа. Поможет их различать.
Теперь можно использовать SSH доступ к вашим репозиторияем!
Получение репозитория по SSH #
Откройте репозиторий и скопируйте ссылку для SSH доступа:
И как обычно используйте команду git clone:
Как сменить работу с HTTPS на SSH #
Если у вас есть локальный (на вашем рабочем компьютере) репозиторий полученный по https, очень просто сменить доступ на SSH.
Для этого убедитесь что доступ по HTTPS, для этого выведите список remote:
ссылки начинаются c https, а значит вы не можете ни загрузить ни получить обновления удаленного репозитория.
Зайдите в репозиторий и скопируйте SSH ссылку доступа, перейдите в локальный репозиторий и удалите текущий remote origin:
и добавьте новый, последняя строка в команде это ссылка доступа SSH:
проверьте список удаленных репозиториев:
и если у вас формат без https в начале ссылки, то все выполнено верно, можно работать с репозиторием и проверить командой git fetch
На этом вопросы с доступом к вашим репозиториям на гитхабе закрыт!
developius / README.md
Create a new repository, or reuse an existing one.
Generate a new SSH key:
Copy the contents of the file
/.ssh/id_rsa.pub to your SSH keys in your GitHub account settings (https://github.com/settings/keys).
Change directory into the local clone of your repository (if you’re not already there) and run:
Now try editing a file (try the README) and then do:
You should not be asked for a username or password. If it works, your SSH key is correctly configured.
OtiZ2 commented Sep 27, 2017
Clone can by direct via ssh
git clone git@github.com:username/your-repository.git
ragerdl commented Oct 19, 2017 •
AndrewPlewe commented Jan 24, 2018
AndrewPlewe commented Jan 24, 2018
«Q: Is the RSA algorithm insecure in general after the disclosure of this vulnerability?
A: No. If the RSA primes are generated as a truly random numbers, our method cannot be applied. For example, keys generated by the OpenSSL library are NOT affected.»
MartinX3 commented Feb 16, 2018
Thank you for this gist!
It is recommend to use the 4096 bit keys.
You don’t know, if there will be bugs found, which will weak your key.
You don’t know, if there will be a breakthrough in computer performance.
But later, you should switch to elliptic curve keys.
They are smaller, but stronger compared to RSA.
jbarros35 commented Jan 13, 2019
fatal: No such remote ‘origin’
saikumar22k commented Mar 6, 2019
Can I push my changes using shh, if I clone my project using http. Please help
ghost commented Mar 24, 2019
Can I push my changes using shh, if I clone my project using http. Please help
lukependleton commented Mar 24, 2019
@HassanElanabi Thank you so much! This has been causing me problems for a long time!
One other thing is that if
git remote get-url origin
doesn’t work, you can use
git remote show origin
to see the current url. At least that’s how I had to do it. Thanks again!
troccoli commented May 1, 2019 •
BTW, I have tried to use the token rather than my password but it didn’t work.
Update May 2nd, 2019
I have switched my remotes to ssh instead of https and since I had already installed my public keys on GitHub I had no problem pushing.
jaeaess commented Jun 29, 2019
Hi GitHub community! I am very beginner, so please answer with very detailed help. I will try to be as precise as possible.
Context: Mac OS X El Capitan Version 10.11.6 (15G22010)
GitHub Page with 2 Google Domains: jaeaess.com and jessdejesus.com
At the beginning, I connected my account «jaeaess» with HTTPS. Adding, pushing committing were working fine. Then, I connected my account «jessdejesus» with HTTPS. But then I ran into errors when trying to push my code.
Now, I am having the following:
#jessdejesus account
Host github-jessdejesus
HostName github.com
User git
IdentityFile
#Second GitHub
Host github.com-jessdejesus
HostName github.com
User git
IdentityFile
Could you please help me?
Many thanks in advance.