[SOLVED] fatal: could not read from remote repository.
This tutorial shows you the two main origins and solutions to the error, «fatal: could not read from remote repository.» These are:
- Git pushing to non-existing remote URL
- Failing to config SSH keys properly
First, the tutorial briefly takes you through Git remote and creating an SSH connection between Git and GitHub. Next, the tutorial creates the error then shows you how to solve it step by step.
We use GitHub for the demos, but you can still follow along with a different website.
Git remote
Git tracks its connection to GitHub using the git remote command. For example, you can check the destination URLs using the git remote -v command.
origin is an alias for the https://github.com/Stevealila/Python.git URL. You can modify or update it.
The https part shows that the connection is via HTTPs, not SSH. github.com is the website, while Python is the name of the remote repository. (fetch) or (push) means we can get (clone or pull) or send (push) data through the remote URL, respectively.
Since getting or sending data to a remote may occur through multiple branches, you need to specify the (default is main) branch after the origin part.
You may ignore the origin main part if the remote only has one branch and the branch is checked out during the git push process.
The key takeaway is that Git must know the path to fetching from or pushing changes to a remote repository. Otherwise, it may throw the error fatal: could not read from remote repository.
Before diving into practical examples, let me show you another common origin of the error.
SSH Connection
Secure Shell (SSH) ensures two remote computers can connect and share data securely. In this case, your (local) computer and (remote) GitHub server want to share code.
But instead of asking you to input your username and password every time you want to push to the remote repository, SSH automatically completes the connection because the computers already remember each other after the initial connection.
So, you probably get the message, «fatal: could not read from remote repository.» because the remote machine cannot remember (authenticate) your local computer.
But how do you know if an SSH connection exists?
First, check the existence of the keys in the
/.ssh folder of your local computer.
Better yet, you can generate a new one.
ssh-keygen is the command to generate a key.
The -t option specifies the type of encryption used to generate the key. I have used ed25519 algorithm. You can also try out rsa algorithm.
The -C option stands for comment.
Running the command outputs an SSH key pair: public and private. The public key ends in a .pub extension, while the private key lacks an extension.
You should inform your computer’s SSH agent about the new keys. The agent is the wallet that safely stores your various SSH keys. You can start up the SSH agent using the following commands.
Next, store your private key in the agent’s wallet using the following commands.
id_ed25519 is the private key we generated earlier. Its full path is
/.ssh/id_ed25519 . We add it to the activated SSH agent using the ssh-add command.
Note: You need to add a config file before using the command on MacOS.
Next, log in to GitHub and store the public the key under SSH (New) key text box. Use this path: Settings->SSH and GPG keys
![[SOLVED] fatal: could not read from remote repository.](https://www.golinuxcloud.com/wp-content/uploads/settings-1.jpg)
![[SOLVED] fatal: could not read from remote repository.](https://www.golinuxcloud.com/wp-content/uploads/ssh-keys.jpg)
Now that you have securely connected two remote machines, let’s invoke and solve the error fatal: could not read from remote repository.
Source
1: Pushing to non-existing remote
Despite authenticating the local machine, Git and GitHub may fail to understand each other if you attempt to push to a remote repository that does not exist.
Let’s build a local repository and attempt to push the changes to a non-existing remote.
We create test_repo directory and convert it to a Git repository using the git init command. We then create example.py file in the working directory before staging and committing the changes.
Two errors pop up on attempting to push changes to an unknown remote. One of the errors is fatal: Could not read from remote repository.

The solution is to create the repo
![[SOLVED] fatal: could not read from remote repository.](https://www.golinuxcloud.com/wp-content/uploads/new-repo-12-1.jpg)
and set its URL as the local repository’s remote URL.
Now the connection goes through after adding or setting the remote connection.
Source
2: Incorrectly linking through SSH keys
You may also get the error when you fail to connect the machines with the SSH keys correctly.
For example, you could be pushing to or cloning from the remote after connecting the machines with SSH for the first time.
The (local) machine asks, «Are you sure you want to continue connecting (yes/no/[fingerprint])?» You should input ‘yes’ followed by clicking the enter key. If you input ‘no’ or leave it blank, the connection fails and throws the error fatal: could not read from remote repository.
The pull process goes through after we type ‘yes’.

Conclusion
You just learned the main causes of the error fatal: could not read from remote repository and how to solve them. Now it is your turn to apply the knowledge.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
How to Fix SSH “Permission Denied” with Git Clone
Are you frustrated that cloning your Git repository over SSH always results in a “permission denied” error message in the terminal? Here’s how to fix it once and for all.
![]()
I operate several droplets on DigitalOcean and this issue has been bugging me for ages. When I couldn’t take it anymore, I spent a whole hour searching for and trying out various suggested fixes with absolutely no avail. Then I reflected on what I was doing in the first place and figured out the logic behind the operations.
Before we start, I wanted to let you know that you can start your own droplet on DigitalOcean with a $100 credit. Simply follow this link:
DigitalOcean — The developer cloud
Helping millions of developers easily build, test, manage, and scale applications of any size — faster than ever…
If you’re not logged in as the root user on your machine, you’ll likely have tried this command to clone your Git repository (GitLab in this case):
And this error keeps re-appearing:
Generate SSH Keys and Test SSH Authentication
First of all, ensure that your SSH key has been generated and the file containing the corresponding public key id_rsa.pub has been added to the account where your Git repository is hosted (scroll below to find a list of Git hosting services and where to add your public key).
If you haven’t generated an SSH key yet, this should be your first step. Run the following command on the machine you plan to Git clone in:
Press return for all questions by keeping the defaults and empty passphrase. This will generate two files in the
/.ssh directory within your home directory:
Copy and paste the content of the newly-generated id_rsa.pub file into the account where your repository is hosted. In my case, this is GitLab.
- GitLab: Navigate to your User Settings > SSH Keys
- GitHub: Navigate to your Settings > SSH and GPG Keys
- BitBucket: Navigate to your Bitbucket settings > SSH keys
Now you can do an SSH authentication test using this command:
Authentication should succeed with this return message:
Everything should work, but I still cannot clone my Git repository. Argh!
Solution 1: Use HTTPS
This is the most effortless solution at hand. Simply switch to cloning from the HTTPS path for your Git repository. But the convenience of never having to enter your credentials again and letting the SSH keys authenticate you will forever haunt you.
Each git pull will ask for authentication over and over again. That’s not the solution you were looking for. Me neither.
Solution 2: Use ‘sudo git clone’
Move SSH Key Files to root’s .ssh Directory
When performing operations while not logged in with the root user, we are accustomed to precede all commands with sudo . But sudo implies that SSH keys need to be available in the root’s home directory.
This solution is the most elegant because it allows you to continue with the same directory permissions that you had been working with thus far. No radical permission changes will be performed (we’ll get to that in the 3rd solution below).
All you do is move the SSH keys we’ve generated above to the root’s SSH directory located at /root/.ssh . If you try sudo git clone now, you’ll likely encounter this error:
While this warning won’t let you proceed any further, there is a simple fix to it. Set the file permissions to 600 (owner read-write) and retry sudo git clone .
It should work now.
Solution 3: Use ‘git clone’ (without sudo)
Amend Permissions of the Target Directory
This solution requires a change of file permissions for entire directories. As it’s quite intrusive, this isn’t my favorite option.
You can actually git clone without the sudo, but will probably run into writing permission errors like these:
A workaround is to amend the target’s directory permissions so that your non-root user can clone the necessary files into it. I followed a simple tutorial to correct permissions on /var/www:
- Change the directory owner and group:
sudo chown www-data:www-data /var/www - Allow the group to write to the directory with appropriate permissions:
sudo chmod -R 775 /var/www - Add yourself to the www-data group:
sudo usermod -a -G www-data USER
Replace USER with your account’s user name. That’s it. You should now be able to clone into the desired directory under /var/www.
Conclusion
I hope either one of three solutions suggested above will help you in fixing the persistent permission errors. It’s just a matter of using common sense: SSH-ing with the superuser command means that SSH will look for keys in the root’s home directory.
Not using the superuser command is generally unconventional. At least it will look up SSH keys in your home directory, but requires appropriate directory writing permissions.
Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists
change your ssh url by an http url for your remote ‘origin’, use:
It will ask for your GitHub password on the git push.
![]()
does ssh -T git@github.com ouput the same username ( in Hi [My Username]! ) as in the one used for the ssh url of your repo ( git@github.com:username/repo.git )?
Sorry It not showing same name
That means somehow the credentials have changed.
One solution would be to at least copy %HOME%\.ssh\id_rsa.pub in the SSH keys section of the right GitHub account
I am working on private repo. So In git@github.com:username/repo.git,
If you were able to clone/push to that repo whose username is not your own GitHub account, that must be because you had your previous public ssh key added as a contributor to that repo by the repo’s owner.
What next is to ask that same repo owner to add your current public ssh key %HOME%\.ssh\id_rsa.pub to the repo contributor list.
So check with the owner that you (meaning your public ssh key) are declared as a contributor.
![]()
For me, I was getting this error because my ssh agent was not running somehow. Doing this worked:
![]()
Sometimes that (copying the pub ssh key to github/bitbucket) is not enough, particularly with Bitbucket. You also may need to check if your ssh is using the identity you expect rather than messing up with git remote
Check if the agent is using the same identity you pasted on github/bitbucket with ssh-add -l . If missing add it with
This error happened to me too as the original repository creator had left the company, which meant their account was deleted from the github team.
git remote set-url origin https://github.com/<user_name>/<repo_name>.git
And then git pull origin develop or whatever git command you wanted to execute should prompt you for a login and continue as normal.
Sometimes this happens to me because of network problems. I don’t understand the problem fully, but switching to a different sub-network or using VPN solves it
This error can be because of no SSH key on the your local machine. Check the SSH key locally:
If above command do not give any output use below command to create ssh key(Linux/Mac):
Now again run cat
/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git. In gitlab/bitbucket go to
and add the key
![]()
Edit 1
Since I get so many votes, I discovered some issue with this approach and that is that it will remove all your identities so you might have the same issue when you try to read from other repositories and you will need to to this step again for each project. but it might also not be the case for your project
![]()
I got the very same errors too. In My case upgrading from Windows 7 to 8 messed up my settings. What helped was to regenerate the private and public SSH keys using PuTTYGen, and change the SSH tool in tortoisegit from SSH to Plink.
Maybe, as in my silly situation, you may somehow created the ssh key by directly typing
And so it is created with the local system user credentials so they don’t match, use full command like this and recreate
This command prevents git to ask username and password, not forever but with a default limit to 15 minutes.
This moves the default limit to 1 hour.
![]()
For me none of the solutions here solved it. Frustrated, I restarted my Macbook’s iTerm terminal, and voila! My github authorization started working again.
Weird, but maybe iTerm has its own way of handling SSH authorizations or that my terminal session wasn’t authorized somehow.
![]()
Easy solution for me:
1.) The public SSH Key has to be saved on https://github.com/settings/keys
2.) The email address inside "
/.ssh/id_rsa.pub" (At the end of the file) has to be entered on Github (https://github.com/settings/emails). (This was my problem)
After I saved the email address on GitHub, the problem solved itself.
I had this issue and tried many things but still din’t work. Eventually I decided to generate another SSH KEY and boom — it worked. Follow this article by github to guide you on how to generate your SSH KEY.
Lastly don’t forget to add it to your github settings. Click here for a guide on how to add your SSH KEY to your github account.
![]()
In my case updating GIT helps — I had version 2.23 and with installing version 2.26.2.windows.1 problem disapears.
So if you are sure your SSH key is valid then (see @VonC answer):
- update GIT
- update composer
- run composer clearcache
And it should be ok.
This issue could be related with missing SSH key at Github or any other git server.
In my case I had copied code to another computer and tried to git pull . It failed.
So I had to generate a new SSH key on that machine and update profile on git server with additional SSH key.
![]()
Strangely I had this occur with a single repository out of > 20 repositories on my MacBook Pro.
The solution was to upgrade git via homebrew, and everything strangely worked after it finished:
Hope this helps someone!
Its not necessary to apply above solutions, I simply changed my internet, it was working fine with my home internet but after 3 to 4 hours my friend suggest me to connect with different internet then I did data package and connect my laptop with it, now it is working fine.
I had the same problem. I tried a couple of solutions mentioned above, it did not work for me. I even restarted my machine and also reconnected my WLAN. But all in vain. Then on the remote repo, I manually made a small change in the readme file of the repo. To pull that change on the local copy of my repo in my machine, I did the usual git pull and then the git push origin . This actually worked.
![]()
For me somehow sudo reboot ing the fluffing EC2 instance after a fresh ssh-keygen and rm
/.ssh/known_hosts fixed it! Still not sure how it works but it worked on 4 different EC2 servers with uptime over 700 days. I think it is related to some breaking updates on some processes during the 700 days!! Still not sure what fixed it but for damn its fixed!
I had this same issue and resolved it by adding my SSH key in the
/.ssh/config file and then updating my git repo url.
Note that the Host text exists between the @ and : symbols in the git url.
![]()
The error message you encountered, "Permission denied (publickey)," indicates that you don’t have the proper authentication set up to access the remote repository on GitHub. When using the SSH protocol (the default for GitHub), you need to have an SSH key associated with your GitHub account for secure communication and repository access.
To fix this issue and clone the repository successfully, follow these steps:
Check for Existing SSH Keys: First, check if you already have an SSH key set up on your computer. Open your terminal or command prompt and run:
This command will list all files in the
/.ssh directory. Look for files named id_rsa and id_rsa.pub , which are your private and public SSH keys, respectively.
Generate a New SSH Key (If Needed): If you don’t have an SSH key or need to generate a new one, use the following command:
Replace "your@email.com" with the email associated with your GitHub account. Press Enter to accept the default file location and set a passphrase (or leave it blank for no passphrase).
Add the Public Key to Your GitHub Account: After generating the SSH key, you need to add the public key ( id_rsa.pub ) to your GitHub account. Copy the contents of the public key file using the following command:
Copy the output to your clipboard.
Then, go to your GitHub account’s settings and navigate to "SSH and GPG keys." Click "New SSH key," paste the copied public key into the "Key" field, and give it a recognizable title. Finally, click "Add SSH key" to save it.
Try Cloning Again: With the SSH key added to your GitHub account, try cloning the repository again using the same git clone <repository_url> command.
The cloning process should now work without asking for your username and password.
Настройка доступа по SSH ключу в GitHub в Windows и MacOS
При первой загрузке/выгрузке изменений в/из Github часто возникает ошибка git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Данная статья раз и навсегда положит этим ошибкам конец! 
Всё то, о чём пойдет речь ниже, можно посмотреть в этом видео
ШАГ 1. Поиск существующего SSH ключа
Открываем терминал в том месте где у вас лежит код, который вы хотите интегрировать в Github или Gitlab. Проверяем есть ли уже существующий SSH ключ, для этого вводим команду ниже: ls -al
/.ssh
Пример НЕсуществующего ключа SSH:
Пример существующего ключа SSH:
Если ключ существует переходите сразу к шагу 4 или создайте отдельный новый ключ специально для Github.
ШАГ 2. Генерация нового SSH ключа
- Введите в терминале команду ниже:
ssh-keygen -t ed25519 -C «your_email@example.com»
Пояснения команды:
ssh-keygen команда для генерации SSH ключа -t ed25519 алгоритм шифрования, по умолчанию алгоритм rsa, Github рекомендует использовать алгоритм ed25519 -C значит «комментарий», все что после этой команды в кавычках будет комментарием «your_email@example.com» комментарий, замените на свой email в Github — это нужно чтобы различать SSH ключи между собой, их может быть несколько - Теперь нужно указать путь и название файла, можно оставить по умолчанию и нажать Enter, но давайте поменяем имя файла, чтобы понимать что он сгенерирован именно для Github!
Скопируйте и вставьте путь по умолчанию, поменяйте имя файла и нажмите Enter.
- Далее нужно будет задать пароль (кодовую фразу) для нашего ключа, пропускаем этот шаг, просто два раза нажимаем Enter, иначе придется постоянно вводить этот пароль.

- Если вы все сделали правильно будет примерно также, как на скриншоте ниже:

ШАГ 3. Добавление SSH ключа в SSH-agent
Не пропускайте этот шаг! Без него ничего работать не будет.
Что же такое SSH-agent на сайте habr.com вот такое описание: «ssh-agent — это менеджер ключей для SSH. Он хранит ваши ключи и сертификаты в памяти, незашифрованные и готовые к использованию ssh . Это избавляет вас от необходимости вводить пароль каждый раз, когда вы подключаетесь к серверу.»
- Сначала запустим SSH-agent командой ниже:
eval «$(ssh-agent -s)»
надпись Agent pid 61 (у вас будет любое другое число) говорит о том, что агент успешно запущен!
- Добавьте SSH ключ в SSH агент командой ниже, предварительно поменяв название SSH ключа на ваше:
ssh-add
-
Для пользователей MacOS вводим команду ниже, откроется обычный редактор текста, вставляем в него текст и сохраняем изменения
open
ШАГ 4. Добавление SSH в Github
- Откройте файл где хранится публичный SSH ключ (.pub) и скопируте его содержимое:
cat
Готово! Проверьте что ключ работает
Возвращаемся в наш терминал и вводим команду git pull, файлы должны загрузиться или как в моем случае должна появиться надпись, что все уже обновлено.
