Host key verification failed git windows

I am trying to connect to a remote Git repository that resides on my web server and clone it to my machine. I am using the following format for my command: git clone ssh://username@domain.example/

You are connecting via the SSH protocol, as indicated by the ssh:// prefix on your clone URL. Using SSH, every host has a key. Clients remember the host key associated with a particular address and refuse to connect if a host key appears to change. This prevents man in the middle attacks.

The host key for domain.example has changed. If this does not seem fishy to you, remove the old key from your local cache by editing ${HOME}/.ssh/known_hosts to remove the line for domain.example or letting an SSH utility do it for you with

ssh-keygen -R domain.example

From here, record the updated key either by doing it yourself with

ssh-keyscan -t rsa domain.example >> ~/.ssh/known_hosts

or, equivalently, let ssh do it for you next time you connect with git fetch, git pull, or git push (or even a plain ol’ ssh domain.example) by answering yes when prompted

The authenticity of host 'domain.example (a.b.c.d)' can't be established.
RSA key fingerprint is XX:XX:...:XX.
Are you sure you want to continue connecting (yes/no)?

The reason for this prompt is domain.example is no longer in your known_hosts after deleting it and presumably not in the system’s /etc/ssh/ssh_known_hosts, so ssh has no way to know whether the host on the other end of the connection is really domain.example. (If the wrong key is in /etc, someone with administrative privileges will have to update the system-wide file.)

I strongly encourage you to consider having users authenticate with keys as well. That way, ssh-agent can store key material for convenience (rather than everyone having to enter her password for each connection to the server), and passwords do not go over the network.

Содержание

  1. exited with an unexpected code: 128. Host key verification failed. fatal: Could not read from remote repository. #4479
  2. Comments
  3. deed02392 commented Apr 20, 2018
  4. Description
  5. Version
  6. Steps to Reproduce
  7. Expected Behavior
  8. Actual Behavior
  9. Additional Information
  10. steveward commented Apr 20, 2018
  11. deed02392 commented Apr 20, 2018
  12. steveward commented Apr 20, 2018
  13. steveward commented Apr 20, 2018
  14. deed02392 commented Apr 20, 2018 •
  15. iAmWillShepherd commented Apr 24, 2018
  16. deed02392 commented Apr 26, 2018 •
  17. billygriffin commented Nov 29, 2018
  18. Host key verification failed for private repository #65
  19. Comments
  20. kpcallplus commented Dec 31, 2015
  21. orendecor commented Jan 2, 2016
  22. kpcallplus commented Jan 2, 2016
  23. gotlisch commented Jan 3, 2016
  24. orendecor commented Jan 3, 2016
  25. georgiandinca commented Jan 3, 2016
  26. orendecor commented Jan 3, 2016
  27. kalpitpandit commented Jan 3, 2016
  28. gotlisch commented Jan 4, 2016
  29. orendecor commented Jan 5, 2016
  30. gotlisch commented Jan 6, 2016
  31. mcki0127 commented Feb 6, 2016
  32. Git ошибка: «Ошибка проверки ключа хоста» при подключении к удаленному репозиторию
  33. ОТВЕТЫ
  34. Ответ 1
  35. Ответ 2
  36. Ответ 3
  37. Ответ 4
  38. Ответ 5
  39. Ответ 6
  40. Ответ 7
  41. Ответ 8
  42. Ответ 9
  43. Ответ 10
  44. Ответ 11
  45. Ответ 12
  46. Ответ 13
  47. Ответ 14
  48. Ответ 15
  49. Ответ 16
  50. Ответ 17
  51. Ответ 18

exited with an unexpected code: 128. Host key verification failed. fatal: Could not read from remote repository. #4479

Description

Just installed GitHub Desktop fresh. I opened a local cloned repo, commited a change and tried to push.

I suspect the issue is in the git binary that GH desktop is using.

Version

  • GitHub Desktop:
    1.1.1
  • Operating system:
    Microsoft Windows [Version 10.0.16299.371]

Steps to Reproduce

Install GitHub Desktop fresh. I opened a local cloned repo, commited a change and tried to push.

Expected Behavior

Actual Behavior

Authentication error modal

Additional Information

Have installed git for windows, git in cygwin and gitkraken. All these work in their own respective environments.

Relevant excerpt provided above

The text was updated successfully, but these errors were encountered:

Thanks for opening this @deed02392. The Host key verification failed error usually indicates an issue with SSH — did you clone this repository in GitHub Desktop, or did you clone it from another client using SSH?

I think I cloned it using GitKraken. I hope this helps.

@deed02392 thanks for the update. You can check the remote URL the repository is using from GitHub Desktop by going to the file menu and selecting Repository > Repository Settings > Remote . Let me know what that shows.

@deed02392 that’s all the information I needed, and it does indicate that this repository is using SSH.

There are two solutions for this:

  1. Switch the remote URL to use HTTPS instead of SSH (you should not have any authentication issues as long as you are logged in with your GitHub Enterprise account in GitHub Desktop).
  2. Get SSH working. The host key verification failed error means that the host key from GitHub Enterprise isn’t in your known_hosts file. You should be able to fix this by running the following command from Git Bash:

Replace with the URL of the GitHub Enterprise server you are connecting to.

Hope that helps. Let me know if that doesn’t get things working.

Thanks. Switching to HTTPS works, but I believe there are advantages to using SSH instead.

SSH cloning worked for this repository in the first place (from a cygwin environment). Adding the host key within the Git Bash environment succeeded, however this has not fixed the issue for GitHub Desktop. I think we need to review how GitHub Desktop uses SSH to determine why it isn’t working. E.g., does it use ‘ssh.exe’ from its processes PATH?

I believe there are advantages to using SSH instead.

Would you mind sharing these advantages and how using HTTPS does not fit into your workflow?

@iAmWillShepherd I did not say that HTTPS does not fit into my workflow.

I was just of the understanding that SSH was more secure than HTTPS because it used keys instead of authenticating with my username and password on every connect. I also perhaps mistakenly have the impression that SSH generally performs git operations faster than HTTPS.

Using HTTPS will be merely a workaround anyway.

I think this is a similar issue as #2085 so I’m going to close this. HTTPS should be a completely valid way to clone without any issues (I don’t think there’s a speed difference between the two but I could be mistaken), but we recognize that many people still prefer to use SSH so we’re tracking that as something to provide better support for in the future. Thanks!

Источник

Host key verification failed for private repository #65

I am getting below error when i am running /deploy.php from browser or if i push anything in repository.

$ git clone —depth=1 —branch master git@github.com:myrepository.git /tmp/spgd-8fbc87725193f8667aff13a1372edd28/
Cloning into ‘/tmp/spgd-8fbc87725193f8667aff13a1372edd28’.
Host key verification failed.
fatal: Could not read from remote repository.

When i run $ git clone —depth=1 —branch master git@github.com:myrepository.git /tmp/spgd-8fbc87725193f8667aff13a1372edd28/ directly in terminal its cloning repository without any error.

I have also referred #9 but didn’t help.

The text was updated successfully, but these errors were encountered:

Is there any solution?
I have the same problem

No luck. Please do post here if you find any solution.

I’m having the same issue. have setup the SSH key and everything but no luck. Works a charm on public projects but that’s no good to me..

I found out why it doesn’t work — basically is is because git sends message to deploy.php and then apache is trying to run «git clone. » on your server, well, apache is not root so it runs (in my server it’s daemon on others it’s www-data) the command and it won’t let it to add git to known_hosts.

Try to run this on your server:
sudo -u www-data ssh -T git@github.com

for me it’s asking me to save git to known host:
The authenticity of host ‘github.com (192.30.252.128)’ can’t be established.
RSA key fingerprint is 16:27. 48.
Are you sure you want to continue connecting (yes/no)? yes

I write «yes» and this is what I got
Failed to add the host to the list of known hosts (/usr/sbin/.ssh/known_hosts).
Permission denied (publickey).

And this is weird because I opened the permissions to the known_hosts file.
I think after solving this it should work.

georgiandinca commented Jan 3, 2016

You need to generate a key for www-data user and added to github repo.
If www-data has the /var/www/ home directory, then in there you will have a .ssh forder where the generated key files and the known_hosts file should be.

Thanks! this tip took me one step forward, the problem now is that I cannot add the new id_rsa to ssh-agent for some reason..

When I try to write this:
sudo ssh-add /usr/sbin/.ssh/id_rsa

It says:
Could not open a connection to your authentication agent.

kalpitpandit commented Jan 3, 2016

I got it working on private repository too. I have followed below steps :

Note : For debian system(which i am running), www-data is the Apache user. If you are on non-debian system you can check apache user by this command : ps aux | egrep ‘(apache|httpd)’ and replace that user name with www-data here.

  1. Create new directory in your webroot :
    mkdir -p /var/www/.ssh/
    chown -R www-data:www-data /var/www/.ssh
    chmod 0700 /var/www/.ssh
  2. Generate a new key for www-data user (Apache user) or move current user key to /var/www/.ssh directory.
    To generate fresh key : sudo -u www-data ssh-keygen -t rsa.
    To use existing one : cp

/.ssh/ /var/www/.ssh/ (We are moving id_rsa.pub, id_rsa & known_hosts files here)

  • Change ownership of /var/www/.ssh directory www-data.
    — sudo chown -R www-data:www-data /var/www/.ssh
  • Change ownership of /var/www/your-deployment-directory/ directory to www-data.
    — sudo chown -R www-data:www-data /var/www/YourProjectDirectory
  • Thanks for you replies! I had generated the SSH key and hooked it up in
    github, so thats not the problem. Also the script runs just fine when i
    connect to an open Repo using https so i dont think its permission related.
    Anyway will have a play around with it to see if i can work it out. Just to
    be clear, does it definetly work for github private repo over SSH, I saw
    several people having the same issue, dont want to spend time trying to fix
    it if it doesnt work in the first place 🙂
    On 3 Jan 2016 11:50 pm, «orendecor» notifications@github.com wrote:

    I found out way it doesn’t work — basically is is because git sends
    message to deploy.php and then apache is trying to run «git clone. » on
    your server, well, apache is not root so it runs (in my server it’s daemon
    on others it’s www-data) the command and it won’t let it to add git to
    known_hosts.

    Try to run this on your server:
    sudo -u www-data ssh -T git@github.com git@github.com

    for me it’s asking me to save git to known host:

    The authenticity of host ‘github.com http://github.com
    (192.30.252.128)’ can’t be established. RSA key fingerprint is
    16:27. 48. Are you sure you want to continue connecting (yes/no)? yes

    I write «yes» and this is what I got

    Failed to add the host to the list of known hosts
    (/usr/sbin/.ssh/known_hosts). Permission denied (publickey).

    And this is weird because I opened the permissions to the known_hosts
    file.
    I think after solving this it should work.


    Reply to this email directly or view it on GitHub
    #65 (comment)
    .

    tl;dr — working if you remove passphrases from id_rsa file.

    Long story:
    The problem is that id_rsa is encrypted with passphrases, and when I try to run ssh-agent on this id_rsa (so it will not ask for the passphrases each time) it won’t have a permission on this file.

    This because id_rsa has 600 rights (reading only for its owner — which is the apache user), and if you change this permissions then git won’t accept this key because its permissions are too open.

    I ended up removing the encryption for this key by running this line:
    sudo openssl rsa -in id_rsa -out new_id_rsa

    Since then everything is working fine 🙂

    (I’m not sure what are the implications of this passphrases removal)

    I see — thank you for confirming, much appreciated!

    On Wed, Jan 6, 2016 at 10:26 AM, orendecor notifications@github.com wrote:

    tl;dr — working if you remove passphrases from id_rsa file.

    Long story:
    The problem is that id_rsa is encrypted with passphrases, and when I try
    to run ssh-agent on this id_rsa (so it will not ask for the passphrases
    each time) it won’t have a permission on this file.

    This because id_rsa has 600 rights (reading only for its owner — which is
    the apache user), and if you change this permissions then git won’t accept
    this key because its permissions are too open.

    I ended up removing the encryption for this key by running this line:
    sudo openssl rsa -in id_rsa -out new_id_rsa

    Since then everything is working fine 🙂

    (I’m not sure what are the implications of this passphrases removal)


    Reply to this email directly or view it on GitHub
    #65 (comment)
    .

    I’m having the same trouble. This was working perfectly when my repository was public, but it broke when I went private. I initially encountered the error:
    _
    $ git clone —depth=1 —branch master git@github.com:mcki0127/[project].git /tmp/spgd-accb135f8fe13d74a36dc288e0b65c4d/
    Host key verification failed.
    fatal: Could not read from remote repository._

    I contacted GitHub and was instructed to add GitHub’s public key to the known hosts file, which I did with ssh -T git@github.com.

    However, I still got the error. Next, per GitHub support, I added GitHub’s key to the global known hosts file with ssh-keyscan -t rsa github.com >> /etc/ssh/ssh_known_hosts

    Then I got this:
    _
    Warning: Permanently added the RSA host key for IP address ‘192.30.252.131’ to the list of known hosts. Permission denied (Public key).
    fatal: Could not read from remote repository._

    I have checked and verified that there is a GitHub key in that global known_hosts file. But the error persists. I have tried kalpitpandit’s solution, and copied the keys into the var/www directory and chown the .ssh and project directories to www-data:www-data (I’m on Ubuntu).

    Currently I am getting this error:

    _
    $ git clone —depth=1 —branch master git@github.com:mcki0127/[project.git] /tmp/spgd-accb135f8fe13d74a36dc288e0b65c4d/
    Cloning into ‘/tmp/spgd-accb135f8fe13d74a36dc288e0b65c4d’.
    Failed to add the RSA host key for IP address ‘192.30.252.129’ to the list of known hosts (/var/www/vhosts/[project directory]).
    Permission denied (publickey).
    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights_

    I currently have the same ssh keys in root and in var/www. private keys have permission 600 and public keys have 644. I’m at a loss at this point

    Источник

    Git ошибка: «Ошибка проверки ключа хоста» при подключении к удаленному репозиторию

    Я пытаюсь подключиться к удаленному репозиторию Git, который находится на моем веб-сервере и клонировать его на мою машину.

    Я использую следующий формат для моей команды:

    Это отлично работает для большинства членов моей команды. Обычно после запуска этой команды Git запрашивается пароль пользователя, а затем запускается клонирование. Однако при запуске на одной из моих машин появляется следующая ошибка:

    фатальный: не удалось прочитать с удаленного хранилище.

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

    ОТВЕТЫ

    Ответ 1

    Вы подключаетесь по протоколу SSH, как указано префиксом ssh:// в URL вашего клона. Используя SSH, у каждого хоста есть ключ. Клиенты запоминают ключ хоста, связанный с конкретным адресом, и отказываются подключаться, если ключ хоста меняется. Это мешает человеку в середине атаки.

    Ключ хоста для domain.com изменился. Если вам это не кажется странным, удалите старый ключ из локального кэша, отредактировав $/.ssh/known_hosts чтобы удалить строку для domain.com, или разрешив утилите SSH сделать это за вас с

    Отсюда запишите обновленный ключ, либо сделав его самостоятельно с

    или, что то же самое, пусть ssh сделает это за вас в следующий раз, когда вы подключитесь с помощью git fetch , git pull или git push (или даже обычного ssh domain.com ), ответив «да» в ответ на запрос

    Причиной этого запроса является то, что domain.com больше не находится в ваших known_hosts после его удаления и, вероятно, отсутствует в системах /etc/ssh/ssh_known_hosts , поэтому ssh не может узнать, действительно ли хост на другом конце соединения domain.com. (Если неправильный ключ находится в /etc , кто-то с правами администратора должен будет обновить общесистемный файл.)

    Я настоятельно рекомендую вам также рассмотреть возможность аутентификации пользователей с помощью ключей. Таким образом, ssh-agent может хранить материал ключа для удобства (вместо того, чтобы вводить свой пароль для каждого соединения с сервером), и пароли не передаются по сети.

    Ответ 2

    ssh-keyscan -t rsa github.com >>

    Ответ 3

    У меня была похожая проблема, но с использованием ключей SSH. Из ответа Tupy выше я выяснил, что проблема в том, что файл known_hosts отсутствует или github.com отсутствует в списке известных хостов. Вот шаги, которые я следовал, чтобы решить это —

    /.ssh
    ssh-keyscan -t rsa github.com >>

    /.ssh/known_hosts

  • ssh-keygen -t rsa -C «user.email»
  • откройте открытый ключ с помощью этой команды $ cat

    /.ssh/id_rsa.pub и скопируйте его.

  • Добавьте ключ id_rsa.pub в список ключей SSH в вашем профиле GitHub.
  • Ответ 4

    Это происходит потому, что github в настоящее время не находится в ваших известных хостах.

    Вам должно быть предложено добавить github к вашим известным хостам. Если этого не произошло, вы можете запустить ssh -T [email protected] чтобы снова получить приглашение.

    Ответ 5

    Для меня мне просто нужно было ввести «да» в приглашении, которое спрашивает «Вы уверены, что хотите продолжить соединение (да/нет)?» а не просто нажать Enter.

    Ответ 6

    У меня такая же проблема для новой установленной системы, но это была проблема udev. Не было /dev/tty node, поэтому мне пришлось делать:

    Ответ 7

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

    Host *
    StrictHostKeyChecking no
    UserKnownHostsFile =/dev/null

    Ответ 8

    Что сработало для меня, так это сначала добавить мой SSH-ключ нового компьютера, я выполнил эти инструкции из GitLab — добавлю SSH-ключ. Обратите внимание, что, поскольку я нахожусь на Win10, мне пришлось выполнять все эти команды в Git Bash в Windows (он не работал в обычной командной консоли DOS).

    Затем снова в Git Bash мне пришлось сделать git clone репо, с которым у меня были проблемы, и в моем случае я должен был клонировать его под другим именем, поскольку я уже имел его локально и не хотел потерять свои коммиты, Например

    Затем я получил приглашение добавить его в список известных хостов, вопрос может быть следующим:

    Вы действительно хотите продолжить подключение (да/нет)?

    Я набрал «да», и он, наконец, работал, вам обычно нужно получить сообщение, подобное этому:

    Предупреждение. Постоянно добавлено «[ваша ссылка репо]» (ECDSA) в список известных хостов.

    Примечание. Если вы находитесь в Windows, убедитесь, что вы используете Git Bash для всех команд, это не работает в обычной командной оболочке CMD или в командной оболочке, мне действительно нужно было это сделать в Git Bash.

    Наконец, я удалил второе повторное myRepo2 ( myRepo2 в примере) и вернулся к моему первому репо, и я мог, наконец, сделать все вещи Git, как обычно, в моем любимом редакторе VSCode.

    Ответ 9

    Если вы используете git для Windows.

    • Откройте графический интерфейс git.
    • Откройте локальный репозиторий git в git GUI.
    • Добавьте пульт дистанционного управления или нажмите, если пульт дистанционного управления уже существует.
    • Ответьте «да» на вопрос о том, хотите ли вы продолжить.

    Клиент GUI добавляет ключ для вас в

    /.ssh/known_hosts . Это легче запомнить, если вы не делаете этого часто, а также избегаете необходимости использовать командную строку git (стандартные командные строки Windows не имеют исполняемого файла ssh-keyscan .

    Ответ 10

    Это означает, что ваш ключ удаленного хоста был изменен (может быть изменение пароля хоста),

    Ваш терминал предложил выполнить эту команду как пользователь root

    Вам нужно удалить это имя хоста из списка хостов на вашем ПК/сервере. Скопируйте эту предложенную команду и выполните ее как пользователь root.

    Попробуйте снова, надеюсь, это сработает.

    Ответ 11

    Когда удаленный сервер хочет подключиться к частному репо, он аутентифицируется через ssh. Создайте пару секретный-открытый ключ с помощью ssh-keygen или, если у вас уже есть открытый-закрытый ключ. Скопируйте и вставьте открытый ключ в настройках частного репо.

    YourPrivateRepo → Настройки → Развернуть ключи → Добавить ключ развертывания → Вставить открытый ключ.

    Теперь удаленный сервер сможет подключаться к частному репо.

    ПРИМЕЧАНИЕ. Ключи развертывания имеют доступ только для чтения репозитория. Необходимо явно разрешить доступ для записи.

    Ответ 12

    Вы можете использовать свой «git url» в формате URL «https» в файле Jenkins или где хотите.

    git url: ‘https://github.com/jglick/simple-maven-project-with-tests.git’

    Ответ 13

    Я столкнулся с такой же ошибкой внутри DockerFile во время сборки, пока изображение было общедоступным. Я немного изменил файл Dockerfile.

    Это связано с тем, что использование синтаксиса [email protected]. заканчивается> использованием SSH для клонирования, а внутри контейнера ваш закрытый ключ недоступен. Вместо этого вы захотите использовать RUN git clone> https://github.com/edenhill/librdkafka.git.

    Ответ 14

    Are you sure you want to continue connecting (yes/no)?

    Введите yes в качестве ответа

    Так я решил свою проблему. Но если вы попытаетесь просто нажать кнопку ввода, это не сработает!

    Ответ 15

    У меня была аналогичная проблема, к сожалению, я использовал GitExtensions HMI и забыл, что написал кодовую фразу. С HMI. забудьте об этом! Не вводите парольную фразу при создании ключа!

    Ответ 16

    Хорошо, я только раздробил репо, с которым я хотел работать, затем используйте это.

    Вот что я хотел сделать:

    Затем я получил эту ошибку, которая привела меня сюда:

    Затем я просто разветкил это репо и теперь могу использовать:

    Я думаю, что следующим логическим шагом будет синхронизация восходящего потока:

    так что изменения с восходящего потока вытаскиваются локально, когда я делаю:

    Ответ 17

    У меня появилось это сообщение, когда я попытался сделать git clone репо, которое не было моим. Исправление было в fork, а затем клонировано.

    Ответ 18

    Это означает, что у хоста есть новый ключ, а отпечаток пальца изменился или вы стали жертвой эксплойта «человек в середине». Чтобы защитить вас, клиент Mac OS X SSH не позволит вам завершить подключение к этому хосту, пока старый ключ не будет удален с вашего компьютера. Если вы определили, что ключ хоста был изменен (см. Инструкции подключения для текущих клавиш), выполните следующие действия, чтобы удалить старый ключ:

    • Откройте терминал в папке «Приложения» > «Утилита».
    • Введите open .ssh в окне терминала, затем нажмите клавишу Return .
    • Откроется папка .ssh , содержащая файл known_hosts . Перетащите known_hosts в корзину, затем закройте папку .ssh . Закрыть терминал.

    Источник

    You are connecting via the SSH protocol, as indicated by the ssh:// prefix on your clone URL. Using SSH, every host has a key. Clients remember the host key associated with a particular address and refuse to connect if a host key appears to change. This prevents man in the middle attacks.

    The host key for domain.com has changed. If this does not seem fishy to you, remove the old key from your local cache by editing ${HOME}/.ssh/known_hosts to remove the line for domain.com or letting an SSH utility do it for you with

    ssh-keygen -R domain.com
    

    From here, record the updated key either by doing it yourself with

    ssh-keyscan -t rsa domain.com >> ~/.ssh/known_hosts
    

    or, equivalently, let ssh do it for you next time you connect with git fetch, git pull, or git push (or even a plain ol’ ssh domain.com) by answering yes when prompted

    The authenticity of host 'domain.com (a.b.c.d)' can't be established.
    RSA key fingerprint is XX:XX:...:XX.
    Are you sure you want to continue connecting (yes/no)?

    The reason for this prompt is domain.com is no longer in your known_hosts after deleting it and presumably not in the system’s /etc/ssh/ssh_known_hosts, so ssh has no way to know whether the host on the other end of the connection is really domain.com. (If the wrong key is in /etc, someone with administrative privileges will have to update the system-wide file.)

    I strongly encourage you to consider having users authenticate with keys as well. That way, ssh-agent can store key material for convenience (rather than everyone having to enter her password for each connection to the server), and passwords do not go over the network.

    What happens in background when you connect a server first time using ssh

    When you connect to a server for the first time, the server prompts you to confirm that you are connected to the correct system. The following example uses the ssh command to connect to a remote host named host03:

    # ssh host03
    The authenticity of host 'host03 (192.0.2.103)' can’t be
    established. ECDSA key fingerprint is ...
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added 'host03,192.0.2.103' (ECDSA) to the list of known hosts.

    Host validation is one of OpenSSH’s major features. The command checks to make sure that you are connecting to the host that you think you are connecting to. When you enter yes, the client appends the server’s public host key to the user’s ~/.ssh/known_hosts file, creating the ~/.ssh directory if necessary. The next time you connect to the remote server, the client compares this key to the one the server supplies. If the keys match, you are not asked if you want to continue connecting.

    If someone tries to trick you into logging in to their machine so that they can sniff your SSH session, you will receive a warning similar to the following:

    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
    Someone could be eavesdropping on you right now (man-in-the-middle attack)!
    It is also possible that the RSA host key has just been changed.
    The fingerprint for the RSA key sent by the remote host is
    dd:cf:50:31:7a:78:93:13:dd:99:67:c2:a2:19:22:13.
    Please contact your system administrator.
    Add correct host key in /home/user01/.ssh/known_hosts to get rid of this message.
    Offending key in /home/lcz/.ssh/known_hosts:7
    RSA host key for 192.168.219.149 has changed and you have requested strict checking.
    Host key verification failed.

    If you ever get a warning like this, stop and determine whether there is a reason for the remote server’s host key to change (such as if SSH was upgraded or the server itself was upgraded). If there is no good reason for the host key to change, do not try to connect to that machine until you have resolved the situation.

    How to correct the “host key verification failed” error

    Method 1 – removing old key manually

    1. On the source server, the old keys are stored in the file ~/.ssh/known_hosts.

    2. Only if this event is legitimate, and only if it is precisely known why the SSH server presents a different key, then edit the file known_hosts and remove the no longer valid key entry. Each user in the client/source server has its own known_hosts in its home directory, just remove the entry in the file of a specific user for the destination server. For example:
    – If root wants to ssh to the server, just removing entry in the /root/.ssh/known_hosts file is all right.
    – If testuser wants to ssh to the server, then remove the entry in the file /home/testuser/.ssh/known_hosts.

    3. In my case, I will remove the the key (highlighted in red) for the destination server 192.168.219.149 from the file /home/user01/.ssh/known_hosts.

    # vim /home/user01/.ssh/known_hosts
    172.104.9.113 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLrY91bQOihgFZQ2Ay9KiBG0rg51/YxJAK7dvAIopRaWzFEEis3fQJiYZNLzLgQtlz6pIe2tj9m/Za33W6WirN8=
    192.168.219.148 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCrY/m16MdFt/Ym51Cc7kxZW3R2pcHV1jlOclv6sXix1UhMuPdtoboj+b7+NLlTcjfrUccL+1bkg8EblYucymeU=
    192.168.219.149 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCrY/m16MdFt/Ym51Cc7kxZW3R2pcHV1jlOclv6sXix1UhMuPdtoboj+b7+NLlTcjfrUccL+1bkg8EblYucymeU=

    Method 2 – removing old key using the ssh-keygen command

    You can also remove the old key using the ssh-keygen command as well. The syntax to use the command is below.

    $ ssh-keygen -R [hostname|IP address]

    For example, In our case we will use the IP address to delete the old key.

    $ ssh-keygen -R 192.168.219.149
    # Host 192.168.219.149 found: line 3
    /home/user01/.ssh/known_hosts updated.
    Original contents retained as /home/user01/.ssh/known_hosts.old

    Note : If you do not know precisely, why the SSH server presents a different key, either your known_hosts file is incorrect, or somebody must investigate this server and the network connections to understand the reason of the unexpected change.

    Verify

    If the remote servers asks for a confirmation to add the new key to the ~/.ssh/known_host file, it confirms that you have successfully removed the old key. If you confirm the request, the source machine adds the new key into the ~/.ssh/known_host file.

    $ ssh root@192.168.219.149
    The authenticity of host '192.168.219.149 (192.168.219.149)' can't be established.
    ECDSA key fingerprint is SHA256:V+iGp3gwSlnpbtYv4Niq6tcMMSZivSnYWQIaJnUvHb4.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added '192.168.219.149' (ECDSA) to the list of known hosts.

    Я пытаюсь подключиться к удаленному репозиторию Git, который находится на моем веб-сервере и клонировать его на мою машину.

    Я использую следующий формат для моей команды:

    git clone ssh://[email protected]/repository.git
    

    Это отлично работает для большинства членов моей команды. Обычно после запуска этой команды Git запрашивается пароль пользователя, а затем запускается клонирование. Однако при запуске на одной из моих машин появляется следующая ошибка:

    Ошибка проверки ключа хоста.

    фатальный: не удалось прочитать с удаленного хранилище.

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

    4b9b3361

    Ответ 1

    Вы подключаетесь по протоколу SSH, как указано префиксом ssh:// в URL вашего клона. Используя SSH, у каждого хоста есть ключ. Клиенты запоминают ключ хоста, связанный с конкретным адресом, и отказываются подключаться, если ключ хоста меняется. Это мешает человеку в середине атаки.

    Ключ хоста для domain.com изменился. Если вам это не кажется странным, удалите старый ключ из локального кэша, отредактировав ${HOME}/.ssh/known_hosts чтобы удалить строку для domain.com, или разрешив утилите SSH сделать это за вас с

    ssh-keygen -R domain.com
    

    Отсюда запишите обновленный ключ, либо сделав его самостоятельно с

    ssh-keyscan -t rsa domain.com >> ~/.ssh/known_hosts
    

    или, что то же самое, пусть ssh сделает это за вас в следующий раз, когда вы подключитесь с помощью git fetch, git pull или git push (или даже обычного ssh domain.com), ответив «да» в ответ на запрос

    The authenticity of host 'domain.com (a.b.c.d)' can't be established.
    RSA key fingerprint is XX:XX:...:XX.
    Are you sure you want to continue connecting (yes/no)?

    Причиной этого запроса является то, что domain.com больше не находится в ваших known_hosts после его удаления и, вероятно, отсутствует в системах /etc/ssh/ssh_known_hosts, поэтому ssh не может узнать, действительно ли хост на другом конце соединения domain.com. (Если неправильный ключ находится в /etc, кто-то с правами администратора должен будет обновить общесистемный файл.)

    Я настоятельно рекомендую вам также рассмотреть возможность аутентификации пользователей с помощью ключей. Таким образом, ssh-agent может хранить материал ключа для удобства (вместо того, чтобы вводить свой пароль для каждого соединения с сервером), и пароли не передаются по сети.

    Ответ 2

    Как я уже говорил ранее в Cloning git repo вызывает ошибку — проверка ключа хоста не удалась. фатальный: удаленный конец неожиданно повесился, добавьте GitHub в список авторизованных хостов:

    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

    Ответ 3

    У меня была похожая проблема, но с использованием ключей SSH. Из ответа Tupy выше я выяснил, что проблема в том, что файл known_hosts отсутствует или github.com отсутствует в списке известных хостов. Вот шаги, которые я следовал, чтобы решить это —

    1. mkdir -p ~/.ssh
    2. ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
    3. ssh-keygen -t rsa -C "user.email"
    4. откройте открытый ключ с помощью этой команды $ cat ~/.ssh/id_rsa.pub и скопируйте его.
    5. Добавьте ключ id_rsa.pub в список ключей SSH в вашем профиле GitHub.

    Ответ 4

    Это происходит потому, что github в настоящее время не находится в ваших известных хостах.

    Вам должно быть предложено добавить github к вашим известным хостам. Если этого не произошло, вы можете запустить ssh -T [email protected] чтобы снова получить приглашение.

    Ответ 5

    Для меня мне просто нужно было ввести «да» в приглашении, которое спрашивает «Вы уверены, что хотите продолжить соединение (да/нет)?» а не просто нажать Enter.

    Ответ 6

    У меня такая же проблема для новой установленной системы, но это была проблема udev. Не было /dev/tty node, поэтому мне пришлось делать:

    mknod -m 666 /dev/tty c 5 0
    

    Ответ 7

    Если вы находитесь в офисной интрасети (в противном случае опасной), которая всегда защищена брандмауэрами, просто используйте следующие строки в ~/.ssh/config

    Host *
    StrictHostKeyChecking no
    UserKnownHostsFile =/dev/null

    Ответ 8

    Что сработало для меня, так это сначала добавить мой SSH-ключ нового компьютера, я выполнил эти инструкции из GitLab — добавлю SSH-ключ. Обратите внимание, что, поскольку я нахожусь на Win10, мне пришлось выполнять все эти команды в Git Bash в Windows (он не работал в обычной командной консоли DOS).

    Затем снова в Git Bash мне пришлось сделать git clone репо, с которым у меня были проблемы, и в моем случае я должен был клонировать его под другим именем, поскольку я уже имел его локально и не хотел потерять свои коммиты, Например

    git clone ssh://[email protected]/myRepo.git myRepo2
    

    Затем я получил приглашение добавить его в список известных хостов, вопрос может быть следующим:

    Вы действительно хотите продолжить подключение (да/нет)?

    Я набрал «да», и он, наконец, работал, вам обычно нужно получить сообщение, подобное этому:

    Предупреждение. Постоянно добавлено «[ваша ссылка репо]» (ECDSA) в список известных хостов.

    Примечание. Если вы находитесь в Windows, убедитесь, что вы используете Git Bash для всех команд, это не работает в обычной командной оболочке CMD или в командной оболочке, мне действительно нужно было это сделать в Git Bash.

    Наконец, я удалил второе повторное myRepo2 (myRepo2 в примере) и вернулся к моему первому репо, и я мог, наконец, сделать все вещи Git, как обычно, в моем любимом редакторе VSCode.

    Ответ 9

    Если вы используете git для Windows.

    • Откройте графический интерфейс git.
    • Откройте локальный репозиторий git в git GUI.
    • Добавьте пульт дистанционного управления или нажмите, если пульт дистанционного управления уже существует.
    • Ответьте «да» на вопрос о том, хотите ли вы продолжить.

    Клиент GUI добавляет ключ для вас в ~/.ssh/known_hosts. Это легче запомнить, если вы не делаете этого часто, а также избегаете необходимости использовать командную строку git (стандартные командные строки Windows не имеют исполняемого файла ssh-keyscan.

    Ответ 10

    Это означает, что ваш ключ удаленного хоста был изменен (может быть изменение пароля хоста),

    Ваш терминал предложил выполнить эту команду как пользователь root

    $ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]
    

    Вам нужно удалить это имя хоста из списка хостов на вашем ПК/сервере. Скопируйте эту предложенную команду и выполните ее как пользователь root.

    $ sudo su                                                        // Login as a root user
    
    $ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]    // Terminal suggested command execute here
    Host [www.website.net]:4231 found: line 16 type ECDSA
    /root/.ssh/known_hosts updated.
    Original contents retained as /root/.ssh/known_hosts.old
    
    $ exit                                                           // Exist from root user
    

    Попробуйте снова, надеюсь, это сработает.

    Ответ 11

    Когда удаленный сервер хочет подключиться к частному репо, он аутентифицируется через ssh. Создайте пару секретный-открытый ключ с помощью ssh-keygen или, если у вас уже есть открытый-закрытый ключ. Скопируйте и вставьте открытый ключ в настройках частного репо.

    YourPrivateRepo → Настройки → Развернуть ключи → Добавить ключ развертывания → Вставить открытый ключ.

    Теперь удаленный сервер сможет подключаться к частному репо.

    ПРИМЕЧАНИЕ. Ключи развертывания имеют доступ только для чтения репозитория. Необходимо явно разрешить доступ для записи.

    Ответ 12

    Вы можете использовать свой «git url» в формате URL «https» в файле Jenkins или где хотите.

    git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'

    Ответ 13

    Я столкнулся с такой же ошибкой внутри DockerFile во время сборки, пока изображение было общедоступным. Я немного изменил файл Dockerfile.

     RUN git clone  https://github.com/kacole2/express-node-mongo-skeleton.git /www/nodejs
    

    Это связано с тем, что использование синтаксиса [email protected]:… заканчивается> использованием SSH для клонирования, а внутри контейнера ваш закрытый ключ недоступен. Вместо этого вы захотите использовать RUN git clone> https://github.com/edenhill/librdkafka.git.

    Ответ 14

    Когда спросили:

    Are you sure you want to continue connecting (yes/no)?

    Введите yes в качестве ответа

    Так я решил свою проблему. Но если вы попытаетесь просто нажать кнопку ввода, это не сработает!

    Ответ 15

    У меня была аналогичная проблема, к сожалению, я использовал GitExtensions HMI и забыл, что написал кодовую фразу.
    С HMI… забудьте об этом! Не вводите парольную фразу при создании ключа!

    Ответ 16

    Хорошо, я только раздробил репо, с которым я хотел работать, затем используйте это…

    Вот что я хотел сделать:

    npm install 'mtorromeo/vue-strap#vue2'
    

    Затем я получил эту ошибку, которая привела меня сюда:

    Host key verification failed.
    
    fatal: Could not read from remote repository.
    

    Затем я просто разветкил это репо и теперь могу использовать:

    npm install 'emahuni/vue-strap#vue2' --save-dev
    

    Я думаю, что следующим логическим шагом будет синхронизация восходящего потока:

    git remote add upstream https://github.com/mtorromeo/vue-strap.git
    

    так что изменения с восходящего потока вытаскиваются локально, когда я делаю:

    git fetch upstream
    

    ; -)

    Ответ 17

    У меня появилось это сообщение, когда я попытался сделать git clone репо, которое не было моим. Исправление было в fork, а затем клонировано.

    Ответ 18

    Согласно веб-сайт Университета штата Сан-Франциско:

    Это означает, что у хоста есть новый ключ, а отпечаток пальца изменился или вы стали жертвой эксплойта «человек в середине». Чтобы защитить вас, клиент Mac OS X SSH не позволит вам завершить подключение к этому хосту, пока старый ключ не будет удален с вашего компьютера. Если вы определили, что ключ хоста был изменен (см. Инструкции подключения для текущих клавиш), выполните следующие действия, чтобы удалить старый ключ:

    • Откройте терминал в папке «Приложения» > «Утилита».
    • Введите open .ssh в окне терминала, затем нажмите клавишу Return.
    • Откроется папка .ssh, содержащая файл known_hosts. Перетащите known_hosts в корзину, затем закройте папку .ssh. Закрыть терминал.

    When I try to ssh to my server from a linux computer with debian, I just get

    Host key verification failed.

    The only help I found online was deleting the key from ~/.ssh/known_hosts… well I did not only that, I deleted the whole ~/.ssh just to be sure, and it didn’t help either, I still have Host key verification failed. error.

    asked Sep 23, 2012 at 5:26

    Karel Bílek's user avatar

    OK, answered.

    When I run ssh with -v option, it showed me the actual error.

    It was caused by mistakenly setting wrong access rights to /dev/tty, whatever that is, and ssh somehow didn’t like it. sudo chmod 666 /dev/tty seemed to fix it.

    answered Sep 23, 2012 at 5:36

    Karel Bílek's user avatar

    Karel BílekKarel Bílek

    1,7995 gold badges18 silver badges26 bronze badges

    4

    So the poster’s problem has been resolved. But in case others come to this question by searching and their symptoms are not coming from the same cause:

    Deleting ~/.ssh/known_hosts (or just the offending line in it) will purge the cached host key. However, there is also a system-wide cache, which will be stored someplace like /etc/ssh/ssh_known_hosts. Host keys won’t be cached there unless that’s specifically requested. But if you’re having host key verification issues, have a look in both of these files.

    answered Sep 23, 2012 at 11:42

    dubiousjim's user avatar

    dubiousjimdubiousjim

    2,62818 silver badges27 bronze badges

    It is also possible to run into this issue in various other ways, especially when dealing with Windows which may have several implementations of SSH tacked on to it.

    I ran into this when ssh’ing into a Windows 10 machine that was running SSH server under Cygwin. When you run ssh from that prompt, it runs the cygwin version of ssh, which uses ~/.ssh to store the ssh files — under cygwin that is /home/username.

    However, if you run git from that same prompt, and Git has been installed via Windows (which in my case it had been), it uses the ssh files from C:Usersusername.ssh.

    Normally you run ssh hostname to cache the host key for git, but in this case it does not work, since there are different known_hosts files.

    Once I copied the key from one known_hosts file to the other, the git commands worked fine.

    answered Jan 11, 2019 at 20:15

    yourcomputergenius's user avatar

    Понравилась статья? Поделить с друзьями:
  • Horizon не видит флешку windows 10
  • Horizon zero dawn фикс для запуска на windows 7
  • Horizon zero dawn тема windows 10
  • Horizon zero dawn скачать торрент xattab последняя версия для windows
  • Horizon zero dawn системные требования на пк windows 7