Error: permission denied (publickey)

Verify the public key is attached to your account

You must provide your public key to GitHub to establish a secure connection.

  1. Open Terminal.

  2. Start SSH agent in the background.

  3. Find and take a note of your public key fingerprint.

  4. In the upper-right corner of any page, click your profile photo, then click Settings.

  5. In the user settings sidebar, click SSH and GPG keys.

  6. Compare the list of SSH keys with the output from the command.

  1. Open the command line.

  2. Start SSH agent in the background.

  3. Find and take a note of your public key fingerprint.

  4. In the upper-right corner of any page, click your profile photo, then click Settings.

  5. In the user settings sidebar, click SSH and GPG keys.

  6. Compare the list of SSH keys with the output from the command.

  1. Open Terminal.

  2. Start SSH agent in the background.

  3. Find and take a note of your public key fingerprint. If you’re using OpenSSH 6.7 or older:

    If you’re using OpenSSH 6.8 or newer:

  4. In the upper-right corner of any page, click your profile photo, then click Settings.

  5. In the user settings sidebar, click SSH and GPG keys.

  6. Compare the list of SSH keys with the output from the command.

If you don’t see your public key in GitHub, you’ll need to add your SSH key to GitHub to associate it with your computer.

Make sure you have a key that is being used

  1. Open .
  2. Verify that you have a private key generated and loaded into SSH.

If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.

  1. If you are using Git Bash, turn on ssh-agent:

    If you are using another terminal prompt, such as Git for Windows, turn on ssh-agent:

  2. Verify that you have a private key generated and loaded into SSH.

  1. Open .
  2. Verify that you have a private key generated and loaded into SSH.

The command should print out a long string of numbers and letters. If it does not print anything, you will need to generate a new SSH key and associate it with GitHub.

Tip: On most systems the default private keys ( and ) are automatically added to the SSH authentication agent. You shouldn’t need to run unless you override the file name when you generate a key.

You can also check that the key is being used by trying to connect to :

In that example, we did not have any keys for SSH to use. The «-1» at the end of the «identity file» lines means SSH couldn’t find a file to use. Later on, the «Trying private key» lines also indicate that no file was found. If a file existed, those lines would be «1» and «Offering public key», respectively:

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

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

Connection closed by 123.123.123.123 port 22

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

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

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

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

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

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

Убедитесь, что у вас есть ключ, который используется

Команда ssh-add должна вывести длинную строку из цифр и букв. Если ничего не будет выведено на экран, вы должны сгенерировать новый SSH-ключ и связать его с GitLab.

Замечание. В большинстве систем приватные ключи по умолчанию (, и ) автоматически добавляются к агенту аутентификации SSH. Вы не должны запускать , иначе вы перезапишите имя файла при генерации ключа.

Получение детализации

ssh -vT ‘-p 25000’


debug1: identity file /Users/вы/.ssh/id_rsa type -1
debug1: identity file /Users/вы/.ssh/id_rsa-cert type -1
debug1: identity file /Users/вы/.ssh/id_dsa type -1
debug1: identity file /Users/вы/.ssh/id_dsa-cert type -1

debug1: Authentications that can continue: publickey, password
debug1: Next authentication method: publickey
debug1: Trying private key: /Users/you/.ssh/id_rsa
debug1: Trying private key: /Users/you/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).

В этом примере у нас нет ключей для использования SSH. Значение «-1» в конце строки «identity file» означает, что SSH не может найти файла для использования. Ниже, строка «Trying private key» также показывает, что файл не найден. Если бы файл был найден, значение в этих строках было бы «1», и «Offering public key» соответственно.

ssh -vT ‘-p 25000’


debug1: identity file /Users/вы/.ssh/id_rsa type 1

debug1: Authentications that can continue: publickey, password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: C:\\Users\\вы\\.ssh\\id_rsa

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

При создании 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-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.

How to fix SSH Permission denied

Both solutions contain steps you need to perform on the server-side. Start by opening the terminal on your server and proceed with one of the solutions below.

Solution 1: Enable Password Authentication

If you want to use a password to access the SSH server, a solution for fixing the Permission denied error is to enable password login in the file.

To do this, open the file in a text editor.  This example uses the nano editor:

In the file, find the line and make sure it ends with .

Find the option and disable it by adding .

If lines are commented out, remove the hash sign to uncomment them.

Save the file and exit.

Restart the SSH service by typing the following command:

Solution 2: Change File System Permissions

Using the password-based login as the SSH authentication method is not recommended due to security concerns. Therefore, the following solution may be preferable since it troubleshoots the public key authentication method.

First, open the file using a text editor:

In the file, make sure the following options are set as follows:

Note: The steps above are considered best security practices. If you need to use root login, set the relevant line to .

Comment out the GSSAPI-related options by adding the hash sign at the beginning of the line:

Also, make sure the line is set to :

Save the file and restart the sshd service:

Now navigate to your home folder and check the permissions:

If your owner permissions are not set to read, write, and execute (), use the chmod command to change them:

Now go to the folder and recheck the permissions:

This directory should also have read, write, and execute permissions for the file owner. To enforce them, use again:

The folder contains the file. Check its permissions with:

The file owner should have read and write permissions. To set them, use:

Now try logging in with the key pair again. The output below shows a successful login attempt.

Note: For more information about Linux file permission, read the Linux File Permissions Tutorial.

Conclusion

This tutorial covered the steps necessary to troubleshoot the SSH Permission denied (publickey,gssapi-keyex,gssapi-with-mic) error. By completing the steps in the guide, you should fix the error and successfully SSH into your server.

What is Causing SSH Permission Denied (publickey,gssapi-keyex,gssapi-with-mic)?

The SSH Permission denied error appears when trying to SSH into a server:

Following the Permission denied statement, the bracket contains the attempted authentication methods that failed at the initiation of the connection. The error suggests that the public key is the issue, which is misleading.

One reason for the error may be , the file that contains SSH server configuration. The other possibility is that the file has insufficient permissions. This file contains the list of public keys for the clients allowed to SSH into the server. Consequently, the system’s inability to read from the file results in the Permission denied error.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Техноарена
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: