Host key verification failed ssh 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.

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.

If you’ve ever tried to connect to a remote server using ssh, and received an error message that says “Host key verification failed,” you know how frustrating it can be. This article will show you three ways to fix the problem.

What is a Host Key in SSH?

A Host key is a unique identifier that is used to verify the identity of a remote host. When you connect to a remote host, the Host key is verified against a list of known Host keys. If there is a match, the connection will be allowed to proceed. If there is not a match, the connection will be denied.

The Host key is also used to generate a cryptographic signature for each connection. This signature is used to verify the integrity of the data that is transferred between the client and server.

Understanding error message Host key verification failed

If you receive the error message “Host key verification failed”, it means that the key stored for the host you’re trying to connect to has changed. It is often caused by connecting to a different server than the one you originally connected to (for example, your server has been rebuilt by a new one).

Whenever we connect to a server via SSH, that server’s public key is stored in our home directory. The file is called known_hosts. 

This file is local to the user account and contains the known keys for remote hosts. These are collected from the hosts when connecting for the first time.

As with those keys stored in the file, ~/.ssh/known_hosts, these keys are used to verify the identity of the remote host, thus protecting against impersonation or man-in-the-middle attacks.

When we reconnect to the same server, the SSH connection will verify the current public key matches the one we have saved in our known_hosts file. If there is a match, the connection will proceed. If the match fails, ssh will fail with an error message Host key verification failed happens.

Example of Host key verification failed

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 a host key has just been changed. The fingerprint for the RSA key sent by the remote host is x. Please contact your system administrator.
Add correct host key in /home/ec2-user/.ssh/known_hosts to get rid of this message.

Offending RSA key in /home/ec2-user.ssh/known_hosts:222 RSA host key for www.howtouselinux.com has changed and you have requested strict checking.Host key verification failed.

Methods to fix problem of Host key verification failed

Host key verification failed error occurs when the server’s host key does not match the key that was expected. This can happen when the server’s key has been changed, or when the key has been compromised. 

Here are three ways to fix this Host key verification failed error.

  • Manually edit the “~/.ssh/known_hosts” file and remove the old key for the host you’re trying to connect to. This will allow you to connect to the new server without any problems.
  • Use the “ssh-keygen -R” command to remove the old key from your “~/.ssh/known_hosts” file. This will allow you to connect to the new server without any problems.
  • Use the “-o StrictHostKeyChecking=no” option when connecting to the server. This will prevent ssh from checking the “~/.ssh/known_hosts” file, and will allow you to connect to the new server without any problems.

Remove old host key info from known_hosts file

The easiest way to fix the problem of Host key verification failed is removing the old host key info and reconnect the server.

We can fix this issue with the following steps.

  • Locate our known_hosts file
  • open in a general text editor with vi /home/user/.ssh/known_hosts
  • search the old host name and press “ESC dd” to delete the line.
  • save the changes by pressing “esc” and typing “:wq!”.
  • reconnect the server

Remove old host key info with ssh-keygen command

We can also remove the old host key with ssh-keygen command.

Open up a terminal session, and type one of the following

  • ssh-keygen -R hostname
  • ssh-keygen -R ipaddress
  • ssh-keygen -f “/home/ec2-user.ssh/known_hosts” -R “192.168.0.106”

Disable SSH stricthostkeychecking option

The stricthostkeychecking option in SSH is a security feature that verifies the host key information for each connection. If there is a problem with the host key information, the connection will not be allowed to proceed. This option can be disabled, which will allow the connection to proceed even if there is a problem with the host key information.

  • Open up a terminal window.
  • Type in the following command: ssh -o StrictHostKeyChecking=no hostname

This command removes the old host key for the device in the known_hosts file and replaces old host key with the new host key.

Understanding SSH known_hosts File with Examples

Openbridge Support avatar

Written by Openbridge Support

Updated over a week ago

The RSA key on the Openbridge Server was changed and your SSH client is warning you that the discrepancy might be the fault of an attacker.

This guide will help resolve SSH connection issues that produce the following error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 a host key has just been changed. The fingerprint for the RSA key sent by the remote host is x. Please contact your system administrator.
Add correct host key in /home/ec2-user/.ssh/known_hosts to get rid of this message. Offending RSA key in /home/ec2-user.ssh/known_hosts:222 RSA host key for openbridge.com has changed and you have requested strict checking. Host key verification failed.

This error occurs when the target server you are trying to SSH into has been rebuilt or had it’s RSA key changed since the last time you connected to it. Whenever you connect to a server via SSH, that server’s public key is stored in your home directory (or possibly in your local account settings if using a Mac or Windows desktop) file called known_hosts

When you reconnect to the same server, the SSH connection will verify the current public key matches the one you have saved in your known_hosts  file. If the server’s key has changed since the last time you connected to it, you will receive the above error (or one similar to it).

While contacting your system administrators when any odd warning message occurs is a good idea, you are safely able to resolve this issue yourself:

First, locate your known_hosts  file, and open in a general text editor. The error will often give you the location of the known_hosts  file you need to change. In the example above the offending RSA key is located here:  /home/ec2-user.ssh/known_hosts:222 

Linux and Mac Users

Linux users will find this file in their home directory, in the ~/.ssh/ directory. You use sed  to remove the offending line. Run something like sed -i '222d' ~/.ssh/known_hosts which will remove the offending line as reported in our example

Mac users will find this in either their local account’s ~/.ssh  folder, or their network home directory as with Linux users. You can also run  sed -i '222d' ~/.ssh/known_hosts 

You can also use the IP address with sed  like this sed -i '/1.2.3.4/d' /home/ec2-user/.ssh/known_hosts 

Another option is to user ssh-keygen with the -R  option. This removes all keys belonging to hostname from a known_hosts  file. This option is useful to delete hashed hosts. If your remote hostname is server.openbridge.com  

$ ssh-keygen -R {server.openbridge.com}
$ ssh-keygen -R {ssh.server.ip.address}
ssh-keygen -R {ssh.server.ip.address} -f {/path/to/known_hosts}
$ ssh-keygen -R server.openbridge.com

Lastly, you can edit your  known_hosts with a text editor and remove the offending line. For example, using vi 

Type vi ~/.ssh/known_hosts . Go to line 222  and then dd  to delete and then wq  to save.

Windows Users

Windows users have several places this can be changed. Common places are ~Users~AppDataRoaming_ssh  or the SSH client’s configuration settings. This also might be in a location like C:Usersusername.ssh  or  C:cygwin64homebob.sshknown_hosts . The specific location will be a function of your Windows environment. 

Similar to the Mac and Linux examples, you want to remove the offending SSH key reference:

  • Remove the line containing the host name of the server you failed to connect to. In the example above, :222  indicates the server is on line 222  of the known_hosts  file

  • Save the known_hosts  file after removing the offending key line

  • Attempt to establish the SSH connection again. Once connected, you will see a new entry is created for the server in your known_hosts  file

The next time you attempt to log in, SSH should tell you that the host key is unknown and ask if you want to connect and save the new key.

For most of the cases, the error msg returned by the Linux would have told you what to do. For instance in the earlier answer:

my_mac:~ oivanche$ sudo ssh pi@192.168.0.45
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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 a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:sx1Z4xyGY9venBP6dIHAoBj0VhDOo7TUVCE2xWXpzQk.
Please contact your system administrator.
Add correct host key in /var/root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /var/root/.ssh/known_hosts:74
ECDSA host key for 192.168.0.45 has changed and you have requested strict checking.
Host key verification failed.

It says that the remote server host key has changed — therefore your previously stored local record DOES NOT MATCH any more. For security reasons the connection is not established.

The simplest solution would be just deleted the line mentioned (line 74) in your local pc in /var/root/.ssh/known_hosts by

sudo nano /var/root/.ssh/known_hosts

You would want to deleted the line mentioned ONLY. No easier way just use your keyboard cursor and backspace or delete keys.

Once deletion is done, save it by command Ctrl+o and quit the file by command Ctrl+x.

Now reconnect to your host via ssh, using something like this:

ssh -i /Users/ben/document/key.pem root@192.168.0.45

where /Users/ben/document/key.pem is your server’s key pair you had set to use (can’t find it anymore? go to the hosting site to regenerate one) and 192.168.0.45 is your remote server IP you are connecting to.

When prompted with something like are you sure you want to add the host key permanently to this machine? type yes. Then you have updated your local key for connecting to the remote server for good.

Hope this clarifies and helps.

При работе с SSH-соединениями нередко возникают разного рода ошибки. Это могут быть неполадки с соединением, авторизацией и т. д. Но есть также категория ошибок работы SSH, которые возникают на уровне протокола. Зачастую они имеют место быть при неумелом обращении, собственно, с самим протоколом SSH, например неправильное использование ключей шифрования. Но также могут быть и реальные неполадки, связанные с некорректной конфигурацией сервера или клиента SSH, что отражается на работе, в частности, протокола. Именно о таких неполадках, а также способах их выявления и устранения пойдёт речь в данной статье.

Содержание

  1. Какие бывают ошибки протокола SSH?
  2. Невозможность проверки ключа хоста
  3. Закрытие или сброс соединения
  4. Ошибка взаимодействия с хостом
  5. Заключение

Когда SSH-клиенты получают ошибки сброса соединений, неполадки с шифрованием, а также наблюдаются проблемы, связанные с «неизвестным» или «изменённым» хостом, то это, как правило, ошибки работы протокола SSH. Подобного рода неполадки часто возникают на этапе согласования зашифрованного соединения протоколом SSH посредством создания доверия между сервером и клиентом.

Невозможность проверки ключа хоста

При создании SSH-соединения протокол требует, чтобы стороны идентифицировали себя. Бывает так, что от сервера поступает следующая ошибка:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:doBAKL304WyMd8hnFc9a29r3nX9okS9BlrBJcHtuyNk.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /root/.ssh/known_hosts:14
ECDSA host key for 212.45.27.201 has changed and you have requested strict checking.
Host key verification failed.

Эта ошибка может возникать по нескольким причинам:

  • переустановка SSH-сервера и неполная его конфигурация;
  • восстановление сервера из резервной копии;
  • изменение IP-адреса сервера.

Очистка ключей хостов помогает решить эту проблему. Сами эти ключи хранятся на стороне клиента в файле ~/.ssh/known_hosts. Для очистки можно удалить все записи вручную. Либо можно использовать команду:

$ ssh-keygen -R host_ip

Эта команда попытается очистить соответствующую информацию о ключе хоста в файле known_hosts:

Host 123.123.123.123 found: line 14
/home/john/.ssh/known_hosts updated.
Original contents retained as /home/john/.ssh/known_hosts.old

После этих действий можно попробовать снова выполнить подключение к серверу SSH.

Закрытие или сброс соединения

Бывает так, что соединение с SSH-сервером устанавливается, однако на этапе проверки ключей сбрасывается. Эта ошибка выглядит следующим образом:

Connection closed by 123.123.123.123 port 22

Часто такая ошибка возникает по нескольким причинам:

  •  программный сбой работы SSH-сервера или он не запущен;
  • невозможность инициализировать соединение из-за отсутствия или недоступности ключей.

В данном случае необходимо проверить корректность заданной конфигурации сервера, проверить, запущен ли сам сервис. Если же с сервисом всё в порядке, то необходимо удостовериться, что SSH-ключи доступны для использования сервером. Если они отсутствуют, то необходимо их сгенерировать.

В данном случае необходимо проверить, есть ли в каталоге /etc/ssh набор файлов с именами sshd_host_*_key. Один из них должен иметь расширение *.pub.
В случае, если таких файлов нет, их нужно сгенерировать:

$ ssh-keygen -A
ssh-keygen: generating new host keys: RSA DSA ECDSA ED25519

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

Ошибка взаимодействия с хостом

Для работы протокола SSH на этапе его инициализации генерируется общий закрытый ключ. Он создаётся на основе шифрования, которое согласуется при создании подключения между сервером и клиентом. Иногда на этом этапе возникают несоответствия и на стороне клиента это приводит к следующей ошибке:

Unable to negotiate with 123.123.123.123: no matching key exchange method found.
Their offer: diffie-hellman-group1-sha1

Эта ошибка говорит о том, что сервер и клиент друг друга «не понимают». Это может быть вызвано следующими причинами:

  • список шифрования сервера был изменён или сервер его не поддерживает;
  • различные реализации (версии) протокола SSH на сервере и у клиента.

Как можно видеть, для устранения этой ошибки необходимо привести в соответствие версию клиента SSH, а также настроить шифрование для него. Если сервер использует устаревший метод шифрования, например SHA1, а у клиента по-умолчанию задействованы более совершенные методы, то это также будет вызывать ошибки протокола SSH. Для начала необходимо выяснить, действительно ли у сервера и клиента используются разные методы шифрования.
Для клиента использование методов шифрования можно настроить, используя опцию KexAlgorithms:

$ openssh -o KexAlgorithms=+diffie-hellman-group1-sha1 root@your_server_ip

Эта проблема не такая распространённая, поскольку возникает, когда версия реализации SSH-клиента более новая, чем используемая на сервере.

Заключение

В заключение нужно отметить, что рассмотренные неполадки и способы их устранения являются самыми распространёнными. Если для конкретного случая вышеописанное не помогает устранить проблему в работе SSH, то возможно, неполадка связана не с протоколом, а с другой областью, например с неполадками установления подключения по SSH.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Are you getting Host key verification failed sftp error?

Often, the users may get this error while attempting to connect using SFTP to the host server.

Unfortunately, the error occurs due to the mismatch of the private key from the list of known hosts files, which contains the host key.

At Bobcares, we often get requests from our customers to fix an error message Host key verification failed sftp as part of our Server Management Services.

Today, let’s get into the details on how our Support Engineers fix this error.

What is Host key verification failed sftp error?

SFTP is a secure version of the File Transfer Protocol, which facilitates data access and transfer over a Secure Shell (SSH) data stream.

By default, it uses the unique host key for verifying the exact server. This error occurs due to the mismatch of key verified from the ~/.ssh/known_hosts file.

While trying to connect the host server via sftp protocol, the user may get the following.

Initially, when the customer connects to a server via SSH, the public host key of the client has been saved to the ~/.ssh/known_hosts file.

The next time when users connect to the remote server, the client compares this key to the one that the server supplies.

After that, a connection will establish when the key matches, otherwise the Host key verification failed sftp error will pop up.

How to fix Host key verification failed sftp

Usually, our Support Engineers fix the error by removing the old key from the ~/.ssh/known_hosts file. Removal of the old key is either done manually or by using the ssh-keygen command.

1. Manual removal of key

One of our customers approached us with a problem with file transfer. He received an error when he tried to upload a file via SFTP to another system.

The error said Host key verification failed sftp.

Normally, all the keys are available in the file ~/. ssh/known_hosts. The file known_hosts will be found in the home directory of its user. This error happens due to a mismatch of the private key from the list of known hosts files.

The fix involves the manual removal of the offending key from the file.

To fix the error, we opened the ~/.ssh/known_hosts file and removed the entry from the known_hosts file.

Thus, it resolved the problem of the customer and he could upload files via sftp.

2. ssh-keygen command

Similarly, when a key mismatch occurs, we use the ssh-keygen command to remove the old key from the file ~/.ssh/known_hosts.

ssh-keygen -R [hostname|IP address]

After the removal of the key by using any of this method, the remote server asks for a confirmation to add the new key to the ~/.ssh/known_host file. It indicates the successful removal of the old key.

3. Problem with root user’s key

Often, many customers find problems while transferring files from one server to another. They may have the following error when they try to transfer the file.

"Could not open location 'sftp://dad@192.168.0.3/home/dad/Desktop/Desktop-Laptop%20swap%20file' Host key verification failed"

Sometimes, this occurs when the root user’s key mismatch with the key that already stored in the known_host file. Then we have to remove the old key entry from /root/.ssh/known_hosts file.

So our Support Engineers removed the old key by using the ssh-keygen command. After that, the user was easily able to transfer the files without any error.

[Need more help to solve sftp errors?- We’ll help you.]

Conclusion

In short, Host key verification failed sftp error mainly occurs when the server’s public host key mismatches with the key in the known_hosts file. Today, we saw how our Support Engineers fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I got this error.
can anyone help?

Add correct host key in /home/sam/.ssh/known_hosts to get rid of this message.
Offending key in /home/sam/.ssh/known_hosts:2
RSA host key for 192.168.1.3 has changed and you have requested strict checking.
Host key verification failed.

asked May 21, 2011 at 6:05

sam's user avatar

The message means that the SSH key for the server you are trying to connect to has changed since the last time you connected there.

If that server was re-installed (or got its keys regenerated for some reason), all you need to do is edit your .ssh/known_hosts file and remove the offending line (the one that mentions that server). Make sure you check the key signature when you reconnect before you save it when SSH asks you to.

If the server was not touched however, you have an issue: your .ssh/known_host was corrupted somehow, or the server was compromised, or someone’s trying to mount a man in the middle attack.

answered May 21, 2011 at 7:42

Mat's user avatar

MatMat

7,8931 gold badge32 silver badges32 bronze badges

Just to be clear, ssh implements server authentication by verifying this key. This is a security measure. Before taking action to reset the key, you should make sure you are actually connecting to the machine you think you are. If your network were hacked, you could be ignoring evidence of that event.

answered May 21, 2011 at 13:23

uSlackr's user avatar

uSlackruSlackr

8,90930 silver badges48 bronze badges

Open the file, and delete the second line, and save it

vi /home/sam/.ssh/known_hosts +2
dd
:x

answered May 21, 2011 at 6:10

freethinker's user avatar

freethinkerfreethinker

3,6403 gold badges21 silver badges21 bronze badges

192.168.1.3 looks like an IP address of a machine in a home network. The most likely reason is that you’ve previously SSH’d to an other machine with the same IP assigned.

In that case, you can safely remove line 2 of ~/.ssh/known_hosts.

answered May 21, 2011 at 9:08

Lekensteyn's user avatar

LekensteynLekensteyn

6,3965 gold badges26 silver badges48 bronze badges

При использовании ssh-сервера вы можете столкнуться с одной из распространенных ошибок: «Host Key Verification Failed». Чтобы понять, почему возникает эта ошибка, давайте сначала разберемся, как ssh устанавливает соединение.

Когда вы пытаетесь подключиться к удаленному серверу, сервер просит вас подтвердить, пытаетесь ли вы установить соединение с правильным сервером.

Если вы наберете «да», клиент добавит открытый ключ хоста в файл «.ssh/known_hosts». После добавления ключа удаленного сервера в следующий раз, когда вы попытаетесь подключиться к тому же серверу, клиент сравнит ключи с ключами, хранящимися в файле «known_hosts».

Вы не получите никаких предупреждений, если ключ присутствует в файле «known_hosts». Сервер будет подключен сразу.

Почему возникает ошибка «Host Key Verification Failed»

Основная причина, вызывающая ошибку Host Key Verification Failed», заключается в том, что ключ удаленного хоста был изменен и больше не тот, который хранится в файле «known_hosts». Ключ обычно меняется, когда серверы перестраиваются, и вы получаете сообщение об ошибке, как показано ниже:

Как исправить ошибку «Host Key Verification Failed»

Чтобы исправить эту ошибку, нам нужно удалить неверный ключ из файла «known_hosts», находящегося в нашей системе в каталоге «.ssh». Ошибка дает вам IP-адрес удаленного сервера и номер строки, в которой хранится ключ в файле «known_hosts».

В приведенной выше ошибки, «/home/user/.ssh/known_hosts:7», то «: 7» является задеть номер строки. Ниже перечислены несколько подходов к исправлению этой ошибки:

Способ 1:

Первый способ исправить эту ошибку – использовать команду sed. Команда «sed» используется для изменения текстовых файлов для поиска, добавления или удаления чего-либо из файлов. Мы используем его для удаления хоста-нарушителя:

$ sed -i '7d' ~.ssh/known_hosts

Если «7» – это номер строки, показанный в приведенной выше ошибке, ваш номер строки может быть другим; убедитесь, что вы используете правильный номер строки. Команда удалит неправильную строку из файла «known_hosts» и решит проблему.

Способ 2:

Второй подход – открыть файл «known_hosts» в любом редакторе:

$ nano.ssh/known_hosts

И вручную удалите оскорбительную строку и сохраните файл.

Способ 3:

Третий метод – удаление сервера с помощью команды «ssh-keygen». Следуйте синтаксису, указанному ниже:

$ ssh-keygen -R [IP_ADDRESS]

Например, чтобы удалить ключ хоста «192.168.10.116», используйте:

$ ssh-keygen -R 192.168.10.116

Заключение

Ошибка проверки ключа хоста возникает, когда ключ удаленного сервера изменяется, а клиент не проверяет его по сохраненным ключам. Ключи сервера хранятся в файле «known_hosts» на стороне клиента, и после установления соединения клиент проверяет ключ, сравнивая его с ключами, хранящимися в файле «known_host», и в случае сбоя вы получаете “Host key verification failed”.

Чтобы исправить это, удалите хост-нарушитель из файла «known_hosts». В этой статье упоминаются три различных метода удаления вредоносного хоста, и любой метод может использоваться для устранения этой ошибки.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Like this post? Please share to your friends:
  • Horizon не видит флешку windows 10
  • Horizon zero dawn фикс для запуска на windows 7
  • Horizon zero dawn тема windows 10
  • Horizon zero dawn скачать торрент xattab последняя версия для windows
  • Horizon zero dawn системные требования на пк windows 7