Add known host linux

SSH — How to add host to ssh/known_host file

This keys are added via Eclipse IDE, Want to know what are other ways to add hosts (IPs) and their keys to ssh/known_hosts file. Specific:- How to add ssh-dss key for any host(IP) in known_hosts file. EDIT:- I am using JBoss BRMS which uses git for BRMS Projects, So at time of cloning the BRMS Project in Eclipse IDE via Git it gives following error

The authenticity of host ‘localhost’ can’t be established.
DSA key fingerprint is e2:2c:62 //trimmed.
Are you sure you want to continue connecting?

And it then automatically add ssh-dss key to known_hosts file. So where to find that key and add it manually on knownhosts file

Similar question with complete answer here: stackoverflow.com/questions/34906302/… Safest is to get key out-of-band, generate the line and rehash.

2 Answers 2

The format of ~/.ssh/known_hosts is defined by OpenSSH. Other software might either call OpenSSH (the ssh command), or might have its own implementations that aren’t necessarily 100% compatible.

The OpenSSH known_hosts format is described in the sshd(8) manual page, under «ssh_known_hosts file format». It says that it’s a text file with one line per host–key pair:

Each line in these files contains the following fields: markers (optional), hostnames, keytype, base64-encoded key, comment. The fields are separated by spaces. […] Hostnames is a comma-separated list of patterns (‘ * ’ and ‘ ? ’ act as wildcards); each pattern in turn is matched against the host name. […] A hostname or address may optionally be enclosed within ‘ [ ’ and ‘ ] ’ brackets then followed by ‘ : ’ and a non-standard port number.

To automatically add a key for a new host, just SSH to it.

To manually add a key for a new host, 1) open the known_hosts file in your text editor and 2) add the key for a new host, following the same format. (The key must match the host you’re connecting to. You can query a host for its key using ssh-keyscan -t .)

Читайте также:  Astra linux wiki принтеры

To add a key for all hosts, use a * pattern as the hostname, which will match all hostnames and addresses. To add a key for all hosts on a specific port, use [*]:8001 as the hostname.

Источник

Понимание файла SSH known_hosts

ssh

Статьи

Файл ssh known_hosts — это файл, в котором хранится открытый ключ всех серверов, к которым вы подключились с помощью ssh. Этот файл используется для проверки идентичности серверов в будущем. Ssh может автоматически добавлять ключи в этот файл, но их можно добавить и вручную.

Понимание SSH known_hosts

В SSH для аутентификации компьютеров и пользователей используется криптография с открытым ключом. Ключи хоста аутентифицируют хосты. Уполномоченные ключи и ключи идентификации аутентифицируют пользователей. В OpenSSH коллекция известных ключей хостов хранится в /etc/ssh/known_hosts и в .ssh/known_hosts в домашнем каталоге каждого пользователя. При первом подключении к хосту ssh обычно добавляет открытый ключ удаленного хоста в файл known_hosts пользователя.

Формат файла known_hosts

Формат представляет собой один открытый ключ или сертификат на одну непрерывную строку. Каждая строка содержит имя хоста, количество битов, экспоненту и модуль. В начале строки находится либо имя хоста, либо хэш, представляющий имя хоста. Можно использовать список хостов, разделенных запятыми, в поле имени хоста, если хост имеет несколько имен или если один и тот же ключ используется на нескольких машинах в пуле серверов.

Вот один из примеров ключа хоста с IP:

192.168.0.1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIPV.

Назначение файла known_hosts

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

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

Добавление открытого ключа в known_hosts вручную

Мы можем использовать ssh-keygen с опцией -F для поиска файла known_hosts.

ssh-keygen -F server.example.com .

По умолчанию будет искаться файл ~/.ssh/known_hosts, и ключ будет напечатан, если он будет найден. С помощью опции -f можно искать в другом файле. Если ключ должен быть удален из файла, опция -R работает аналогично поиску по хосту и затем удаляет его, если он найден, даже если имя хоста хэшировано.

ssh-keygen -R serverё.example.com -f ~/.ssh/known_hosts

Когда ключ будет удален, он будет добавлен в файл ~/.ssh/known_hosts.old на случай, если он понадобится позже. Если с помощью -F или -R используется файл не по умолчанию, то имя, включая путь, должно быть указано с помощью -f. Но -f необязателен, если используется файл по умолчанию.

Читайте также:  Связка ключей linux ubuntu

Как просмотреть файл ssh know_hosts?

Чтобы просмотреть файл ssh know_hosts в вашей системе Linux, вы можете использовать следующую команду:

Чтобы добавить новый хост в файл ssh know_hosts, вы можете использовать следующую команду:

ssh-keyscan -t rsa [remote.server.com] >> ~/.ssh/known_hosts ssh-keyscan -H remote.server.com >> ~/.ssh/known_hosts

Чтобы удалить хост из файла know hosts, вы можете использовать следующую команду:

ssh-keygen -R [remote.server.com] ssh-keygen -r [remote.server.com]

Где я должен хранить файл ssh know_hosts?

Файл ssh know_hosts должен храниться в каталоге ~/.ssh. Например, полный путь к файлу ssh know_hosts следующий: ~/.ssh/known_hosts.

Каковы некоторые распространенные проблемы с файлом ssh know_hosts?

Файл ssh know_hosts — это файл, в котором хранится информация о хостах, к которым вы подключились с помощью ssh. Этот файл может помочь предотвратить атаки типа «человек посередине», проверяя ключ хоста перед подключением.

Частая проблема с файлом ssh know_hosts — это когда вы пытаетесь подключиться к хосту и получаете сообщение об ошибке: «WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!». Обычно это происходит, если вы поменяли оборудование на сервере, к которому подключаетесь, или если на удаленном сервере изменились настройки.

Если вы получили это сообщение об ошибке, вы можете исправить ее, удалив хост из файла ssh know_hosts и добавив его обратно:

ssh-keygen -R [remote.server.com]
ssh-keyscan -t rsa [remote.server.com] >> ~/.ssh/known_hosts
ssh-keyscan -H remote.server.com >> ~/.ssh/known_hosts

Другая распространенная проблема с файлом ssh know_hosts — это когда вы пытаетесь подключиться к хосту и получаете сообщение об ошибке: «WARNING: POSSIBLE DNS SPOOFING DETECTED!». Обычно это происходит, когда вы пытаетесь подключиться к несуществующему узлу.

Если вы получили это сообщение об ошибке, проверьте файл /etc/hosts и убедитесь, что имя удаленного сервера там есть и ему присвоен действительный IP-адрес.

Похожие записи:

Источник

Add public key to known_hosts file

I am trying to copy a public key from Server A over to the known_hosts file in Server B. They are both linux servers. Initially I thought about opening the public key file and copying its contents over to the known_hosts file but I suspect that is not the correct method. Does anyone know what the right way to do so is? My public key is in the format ssh-rsa AADGD. Can someone help? Thanks!

Читайте также:  Android sdk on arm linux

4 Answers 4

I answered almost similar answer on SuperUser few days ago. The important parts:

  • The format differs
  • There are different host keys (types) on each server (make sure you paste the one that is actually used)
  • There is ssh-keyscan which can create the format for you

Otherwise just prefix your key with server IP address (you can add also hostname, after comma), remove the comment from end of the line and you are fine. Format then look like this:

And one more note, if you use HashKnownHosts yes (Debian and Ubuntu does), you need to re-hash your known_hosts such as:

ssh-keygen -Hf ~/.ssh/known_hosts 

Thanks! So to confirm, I should edit the known_hosts file and add server_ip_address ssh-rsa AADGD. at the end of the file?

gotcha, and is there a specific ip i should use? it typed /sbin/ifconfig –a and got about 5 different types of IP addresses.

the ip you want to use when connecting from server B to server A as your question describes. If it is somehow different, check the files and terms in the end of man sshd

Having just bumped into this problem, here’s how I approached it:

Over time, copying the files mechanically via

ssh-keyscan server-name >> ~/.ssh/known_hosts 

gave me duplicate entries in .ssh/known_hosts .

Other manual methods required me to create the .ssh directory didn’t already exist, etc.

I decided to just let ssh handle it:

ssh -o StrictHostKeyChecking=no server-name ls 

The -o StrictHostKeyChecking=no option automatically answers ‘yes’ to the

The authenticity of host 'server-name (12.345.678.900)' can't be established. RSA key fingerprint is XXXXXXX. Are you sure you want to continue connecting (yes/no)? 

message (insert here all the security caveats about connecting randomly to machines you don’t know).

The ls command is just a fluff command that will execute and force SSH to disconnect when done. You can change it to whatever fluff command you like.

ssh will take care of creating the .ssh dir (if necessary), adding only one copy of the key, etc.

Источник

Оцените статью
Adblock
detector