Can I automatically add a new host to known_hosts?Non interactive git clone (ssh fingerprint prompt)Add remote host to known_hosts file without promptHow to auto accept new ssh fingerprints but decline changed?“Add correct host key in known_hosts” / multiple ssh host keys per hostname?Securely add host (e.g. github) to SSH known_hosts file?ssh-keyscan - still promoted with The authenticity of host '[hostname] ([IP address])' can't be establishedSSH failing from script, working on command line (Git)gitosis public keyError connecting to server through sshHow to remove strict RSA key checking in SSH and what's the problem here?How to make ssh match known_hosts to host/ip:port instead of just host/ip?Wiped out the known_hosts file on my server machine. Is it safe?gitosis public keySSH known_hosts holds duplicate keys for same serverssh-keyscan - still promoted with The authenticity of host '[hostname] ([IP address])' can't be establishedWarning: Remote host identification has changed (SSH)Securely add host (e.g. github) to SSH known_hosts file?validating virtual machine host automatically with fingerprint and something else

What is the best linguistic term for describing the kw > p / gw > b change, and its usual companion s > h

Infinitely many hats

Uses of T extends U?

Could IPv6 make NAT / port numbers redundant?

How could Catholicism have incorporated witchcraft into its dogma?

Grammar of "Nec huic publico, ut opinantur, malo turba tantum et imprudens uulgus ingemuit"

If a massive object like Jupiter flew past the Earth how close would it need to come to pull people off of the surface?

Compact Mechanical Energy Source

Is this story about US tax office reasonable?

What does the term “mohel” mean in Hilchot Melicha (salting)?

Split polygon using another polygon in QGIS

Can a wire having a 610-670 THz (frequency of blue light) AC frequency supply, generate blue light?

Plot exactly N bounce of a ball

I think I may have violated academic integrity last year - what should I do?

A Mathematical Discussion: Fill in the Blank

How to prevent bad sectors?

Is it ok to put a subplot to a story that is never meant to contribute to the development of the main plot?

How do I subvert the tropes of a train heist?

Is a post-climate apocolypse city in which many or most insects have disappeared realistic?

Yandex Programming Contest: Alarms

What does "Marchentalender" on the front of a postcard mean?

Where can I find the list of all tendons in the human body?

The qvolume of an integer

Restoring order in a deck of playing cards



Can I automatically add a new host to known_hosts?


Non interactive git clone (ssh fingerprint prompt)Add remote host to known_hosts file without promptHow to auto accept new ssh fingerprints but decline changed?“Add correct host key in known_hosts” / multiple ssh host keys per hostname?Securely add host (e.g. github) to SSH known_hosts file?ssh-keyscan - still promoted with The authenticity of host '[hostname] ([IP address])' can't be establishedSSH failing from script, working on command line (Git)gitosis public keyError connecting to server through sshHow to remove strict RSA key checking in SSH and what's the problem here?How to make ssh match known_hosts to host/ip:port instead of just host/ip?Wiped out the known_hosts file on my server machine. Is it safe?gitosis public keySSH known_hosts holds duplicate keys for same serverssh-keyscan - still promoted with The authenticity of host '[hostname] ([IP address])' can't be establishedWarning: Remote host identification has changed (SSH)Securely add host (e.g. github) to SSH known_hosts file?validating virtual machine host automatically with fingerprint and something else






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








235















Here's my situation: I'm setting up a test harness that will, from a central client, launch a number of virtual machine instances and then execute commands on them via ssh. The virtual machines will have previously unused hostnames and IP addresses, so they won't be in the ~/.ssh/known_hosts file on the central client.



The problem I'm having is that the first ssh command run against a new virtual instance always comes up with an interactive prompt:



The authenticity of host '[hostname] ([IP address])' can't be established.
RSA key fingerprint is [key fingerprint].
Are you sure you want to continue connecting (yes/no)?


Is there a way that I can bypass this and get the new host to be already known to the client machine, maybe by using a public key that's already baked into the virtual machine image ? I'd really like to avoid having to use Expect or whatever to answer the interactive prompt if I can.










share|improve this question



















  • 4





    For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

    – Eil
    Feb 15 '18 at 20:04

















235















Here's my situation: I'm setting up a test harness that will, from a central client, launch a number of virtual machine instances and then execute commands on them via ssh. The virtual machines will have previously unused hostnames and IP addresses, so they won't be in the ~/.ssh/known_hosts file on the central client.



The problem I'm having is that the first ssh command run against a new virtual instance always comes up with an interactive prompt:



The authenticity of host '[hostname] ([IP address])' can't be established.
RSA key fingerprint is [key fingerprint].
Are you sure you want to continue connecting (yes/no)?


Is there a way that I can bypass this and get the new host to be already known to the client machine, maybe by using a public key that's already baked into the virtual machine image ? I'd really like to avoid having to use Expect or whatever to answer the interactive prompt if I can.










share|improve this question



















  • 4





    For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

    – Eil
    Feb 15 '18 at 20:04













235












235








235


95






Here's my situation: I'm setting up a test harness that will, from a central client, launch a number of virtual machine instances and then execute commands on them via ssh. The virtual machines will have previously unused hostnames and IP addresses, so they won't be in the ~/.ssh/known_hosts file on the central client.



The problem I'm having is that the first ssh command run against a new virtual instance always comes up with an interactive prompt:



The authenticity of host '[hostname] ([IP address])' can't be established.
RSA key fingerprint is [key fingerprint].
Are you sure you want to continue connecting (yes/no)?


Is there a way that I can bypass this and get the new host to be already known to the client machine, maybe by using a public key that's already baked into the virtual machine image ? I'd really like to avoid having to use Expect or whatever to answer the interactive prompt if I can.










share|improve this question
















Here's my situation: I'm setting up a test harness that will, from a central client, launch a number of virtual machine instances and then execute commands on them via ssh. The virtual machines will have previously unused hostnames and IP addresses, so they won't be in the ~/.ssh/known_hosts file on the central client.



The problem I'm having is that the first ssh command run against a new virtual instance always comes up with an interactive prompt:



The authenticity of host '[hostname] ([IP address])' can't be established.
RSA key fingerprint is [key fingerprint].
Are you sure you want to continue connecting (yes/no)?


Is there a way that I can bypass this and get the new host to be already known to the client machine, maybe by using a public key that's already baked into the virtual machine image ? I'd really like to avoid having to use Expect or whatever to answer the interactive prompt if I can.







linux ssh known-hosts






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 1 '15 at 21:40









chicks

3,08072033




3,08072033










asked Apr 16 '10 at 4:15









gareth_bowlesgareth_bowles

5,97262838




5,97262838







  • 4





    For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

    – Eil
    Feb 15 '18 at 20:04












  • 4





    For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

    – Eil
    Feb 15 '18 at 20:04







4




4





For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

– Eil
Feb 15 '18 at 20:04





For a test environment which is self-contained and physically secure, automated key acceptance may work just fine. But automatically accepting public keys in a production environment or across an untrusted network (such as the Internet) completely bypasses any protection against man-in-the-middle attacks that SSH would otherwise afford. The only valid way to make sure you're secure against MITM attacks is to verify the host's public key through some out-of-band trusted channel. There is no secure way to automate it without setting up a moderately complicated key signing infrastructure.

– Eil
Feb 15 '18 at 20:04










15 Answers
15






active

oldest

votes


















140














Set the StrictHostKeyChecking option to no, either in the config file or via -o :



ssh -o StrictHostKeyChecking=no username@hostname.com






share|improve this answer




















  • 60





    This leaves you open to man in the middle attacks, probably not a good idea.

    – JasperWallace
    Sep 23 '13 at 7:23






  • 9





    @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

    – Massimo
    Oct 21 '14 at 17:33






  • 8





    This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

    – Peter V. Mørch
    May 21 '15 at 9:19







  • 9





    Downvoting as this does not answer the question and opens to serious security vulnerabilities.

    – marcv81
    Jan 20 '16 at 4:48






  • 11





    @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

    – Ignacio Vazquez-Abrams
    Jun 15 '16 at 17:31


















218














IMO, the best way to do this is the following:



ssh-keygen -R [hostname]
ssh-keygen -R [ip_address]
ssh-keygen -R [hostname],[ip_address]
ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts


That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.






share|improve this answer




















  • 4





    Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

    – Robert
    May 24 '13 at 22:00






  • 6





    Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

    – JasperWallace
    Sep 23 '13 at 7:24







  • 2





    @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

    – user68729
    Apr 28 '14 at 21:57






  • 1





    Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

    – phasetwenty
    Aug 6 '14 at 18:11






  • 4





    This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

    – retrohacker
    Sep 29 '15 at 3:04



















89














For the lazy ones:



ssh-keyscan -H <host> >> ~/.ssh/known_hosts


-H hashes the hostname / IP address






share|improve this answer




















  • 2





    "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

    – Sarah Messer
    Sep 4 '15 at 20:19






  • 3





    Vulnerable to MITM attacks. You're not checking the key fingerprint.

    – Mnebuerquo
    Jun 15 '16 at 17:20






  • 7





    @Mnebuerquo You say what to do but not how, which would be helpful.

    – Jim
    Mar 24 '17 at 21:20






  • 3





    @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

    – fivef
    Nov 30 '17 at 9:07







  • 1





    @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

    – Waqas Shah
    Jan 4 '18 at 4:22


















41














As mentioned, using key-scan would be the right & unobtrusive way to do it.



ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts


The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...






share|improve this answer

























  • Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

    – utapyngo
    May 23 '14 at 7:49






  • 1





    The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

    – paulmelnikow
    Jul 27 '15 at 17:46







  • 1





    This is subject to the same MITM attacks as the others.

    – Mnebuerquo
    Jun 15 '16 at 17:18











  • @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

    – Rich L
    Aug 17 '17 at 13:58






  • 1





    If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

    – Zart
    Nov 28 '17 at 17:09


















18














You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.






share|improve this answer




















  • 3





    Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

    – Mnebuerquo
    Jun 15 '16 at 17:20






  • 3





    @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

    – Brian Cline
    Aug 25 '17 at 19:27












  • This is not the way to do it. MITM.

    – jameshfisher
    Nov 28 '17 at 16:39


















7














This is how you can incorporate ssh-keyscan into your play:



---
# ansible playbook that adds ssh fingerprints to known_hosts
- hosts: all
connection: local
gather_facts: no
tasks:
- command: /usr/bin/ssh-keyscan -T 10 ansible_host
register: keyscan
- lineinfile: name=~/.ssh/known_hosts create=yes line= item
with_items: ' keyscan.stdout_lines '





share|improve this answer


















  • 1





    Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

    – Mnebuerquo
    Jun 15 '16 at 17:22






  • 1





    This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

    – Zart
    Jun 16 '16 at 21:42











  • This is not the way to do it. MITM.

    – jameshfisher
    Nov 28 '17 at 16:39






  • 2





    @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

    – Waqas Shah
    Jan 4 '18 at 4:25











  • It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

    – Cameron Lowell Palmer
    Nov 23 '18 at 14:15


















6














this would be a complete solution, accepting host key for the first time only



#!/usr/bin/env ansible-playbook
---
- name: accept ssh fingerprint automatically for the first time
hosts: all
connection: local
gather_facts: False

tasks:
- name: "check if known_hosts contains server's fingerprint"
command: ssh-keygen -F inventory_hostname
register: keygen
failed_when: keygen.stderr != ''
changed_when: False

- name: fetch remote ssh key
command: ssh-keyscan -T5 inventory_hostname
register: keyscan
failed_when: keyscan.rc != 0 or keyscan.stdout == ''
changed_when: False
when: keygen.rc == 1

- name: add ssh-key to local known_hosts
lineinfile:
name: ~/.ssh/known_hosts
create: yes
line: " item "
when: keygen.rc == 1
with_items: 'default([]) '





share|improve this answer

























  • This is not the way to do it. MITM.

    – jameshfisher
    Nov 28 '17 at 16:40


















5














I had a similar issue and found that some of the provided answers only got me part way to an automated solution. The following is what I ended up using, hope it helps:



ssh -o "StrictHostKeyChecking no" -o PasswordAuthentication=no 10.x.x.x


It adds the key to known_hosts and doesn't prompt for the password.






share|improve this answer


















  • 1





    Vulnerable to MITM attacks. You're not checking the fingerprint.

    – Mnebuerquo
    Jun 15 '16 at 17:23






  • 3





    Nobody checks the fingerprint.

    – Brendan Byrd
    Jun 2 '17 at 3:11











  • This is not the way to do it. MITM.

    – jameshfisher
    Nov 28 '17 at 16:40


















4














So, I was searching for a mundane way to bypass the unkown host manual interaction of cloning a git repo as shown below:



brad@computer:~$ git clone git@bitbucket.org:viperks/viperks-api.git
Cloning into 'viperks-api'...
The authenticity of host 'bitbucket.org (104.192.143.3)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?


Note the RSA key fingerprint...



So, this is a SSH thing, this will work for git over SSH and just SSH related things in general...



brad@computer:~$ nmap bitbucket.org --script ssh-hostkey

Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-05 10:21 EDT
Nmap scan report for bitbucket.org (104.192.143.3)
Host is up (0.032s latency).
Other addresses for bitbucket.org (not scanned): 104.192.143.2 104.192.143.1 2401:1d80:1010::150
Not shown: 997 filtered ports
PORT STATE SERVICE
22/tcp open ssh
| ssh-hostkey:
| 1024 35:ee:d7:b8:ef:d7:79:e2:c6:43:9e:ab:40:6f:50:74 (DSA)
|_ 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40 (RSA)
80/tcp open http
443/tcp open https

Nmap done: 1 IP address (1 host up) scanned in 42.42 seconds


First, install nmap on your daily driver. nmap is highly helpful for certain things, like detecting open ports and this-- manually verifying SSH fingerprints. But, back to what we are doing.



Good. I'm either compromised at the multiple places and machines I've checked it-- or the more plausible explanation of everything being hunky dory is what is happening.



That 'fingerprint' is just a string shortened with a one way algorithm for our human convenience at the risk of more than one string resolving into the same fingerprint. It happens, they are called collisions.



Regardless, back to the original string which we can see in context below.



brad@computer:~$ ssh-keyscan bitbucket.org
# bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
no hostkey alg
# bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-129
bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
# bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-123
no hostkey alg


So, ahead of time, we have a way of asking for a form of identification from the original host.



At this point we manually are as vulnerable as automatically-- the strings match, we have the base data that creates the fingerprint, and we could ask for that base data (preventing collisions) in the future.



Now to use that string in a way that prevents asking about a hosts authenticity...



The known_hosts file in this case does not use plaintext entries. You'll know hashed entries when you see them, they look like hashes with random characters instead of xyz.com or 123.45.67.89.



brad@computer:~$ ssh-keyscan -t rsa -H bitbucket.org
# bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==


The first comment line infuriatingly shows up-- but you can get rid of it with a simple redirect via the ">" or ">>" convention.



As I've done my best to obtain untainted data to be used to identify a "host" and trust, I will add this identification to my known_hosts file in my ~/.ssh directory. Since it will now be identified as a known host, I will not get the prompt mentioned above when you were a youngster.



Thanks for sticking with me, here you go. I'm adding the bitbucket RSA key so that I can interact with my git repositories there in a non-interactive way as part of a CI workflow, but whatever you do what you want.



#!/bin/bash
cp ~/.ssh/known_hosts ~/.ssh/known_hosts.old && echo "|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==" >> ~/.ssh/known_hosts


So, that's how you stay a virgin for today. You can do the same with github by following similar directions on your own time.



I saw so many stack overflow posts telling you to programmatically add the key blindly without any kind of checking. The more you check the key from different machines on different networks, the more trust you can have that the host is the one it says it is-- and that is the best you can hope from this layer of security.



WRONG
ssh -oStrictHostKeyChecking=no hostname [command]



WRONG
ssh-keyscan -t rsa -H hostname >> ~/.ssh/known_hosts



Don't do either of the above things, please. You're given the opportunity to increase your chances of avoiding someone eavesdropping on your data transfers via a man in the middle attack-- take that opportunity. The difference is literally verifying that the RSA key you have is the one of the bona fide server and now you know how to get that information to compare them so you can trust the connection. Just remember more comparisons from different computers & networks will usually increase your ability to trust the connection.






share|improve this answer























  • I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

    – Waqas Shah
    Jan 5 '18 at 4:37











  • ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

    – BradChesney79
    Jan 15 '18 at 19:51











  • Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

    – Micah R Ledbetter
    Feb 7 '18 at 17:40











  • ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

    – BradChesney79
    Feb 7 '18 at 19:06











  • This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

    – vastlysuperiorman
    Jun 26 '18 at 17:28


















4














I do a one-liner script, a bit long but useful to make this task for hosts with multiples IPs, using dig and bash



(host=github.com; ssh-keyscan -H $host; for ip in $(dig @8.8.8.8 github.com +short); do ssh-keyscan -H $host,$ip; ssh-keyscan -H $ip; done) 2> /dev/null >> .ssh/known_hosts





share|improve this answer






























    4














    The following avoid duplicate entries in ~/.ssh/known_hosts:



    if ! grep "$(ssh-keyscan github.com 2>/dev/null)" ~/.ssh/known_hosts > /dev/null; then
    ssh-keyscan github.com >> ~/.ssh/known_hosts
    fi





    share|improve this answer


















    • 1





      This is not the way to do it. MITM.

      – jameshfisher
      Nov 28 '17 at 16:42











    • I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

      – Martin Bramwell
      Mar 5 at 23:00


















    3














    To do this properly, what you really want to do is collect the host public keys of the VMs as you create them and drop them into a file in known_hosts format. You can then use the -o GlobalKnownHostsFile=..., pointing to that file, to ensure that you're connecting to the host you believe you should be connecting to. How you do this depends on how you're setting up the virtual machines, however, but reading it off the virtual filesystem, if possible, or even getting the host to print the contents of /etc/ssh/ssh_host_rsa_key.pub during configuration may do the trick.



    That said, this may not be worthwhile, depending on what sort of environment you're working in and who your anticipated adversaries are. Doing a simple "store on first connect" (via a scan or simply during the first "real" connection) as described in several other answers above may be considerably easier and still provide some modicum of security. However, if you do this I strongly suggest you change the user known hosts file (-o UserKnownHostsFile=...) to a file specific
    for this particular test installation; this will avoid polluting your personal known hosts file with test information and make it easy to clean up the now useless public keys when you delete your VMs.






    share|improve this answer






























      3














      This whole



      • ssh-key-scan

      • ssh-copy-id

      • ECSDA key warning

      business kept annoying me so I opted for



      One script to rule them all



      This is a variant of the script at https://askubuntu.com/a/949731/129227 with Amadu Bah's answer https://serverfault.com/a/858957/162693 in a loop.



      example call



      ./sshcheck somedomain site1 site2 site3



      The script will loop over the names sites and modify the .ssh/config and .ssh/known_hosts file and do ssh-copy-id on request - for the last feature just the let the ssh test calls fail e.g. by hitting enter 3 times on the password request.



      sshcheck script



      #!/bin/bash
      # WF 2017-08-25
      # check ssh access to bitplan servers

      #ansi colors
      #http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
      blue='33[0;34m'
      red='33[0;31m'
      green='33[0;32m' # 'e[1;32m' is too bright for white bg.
      endColor='33[0m'

      #
      # a colored message
      # params:
      # 1: l_color - the color of the message
      # 2: l_msg - the message to display
      #
      color_msg()
      local l_color="$1"
      local l_msg="$2"
      echo -e "$l_color$l_msg$endColor"


      #
      # error
      #
      # show an error message and exit
      #
      # params:
      # 1: l_msg - the message to display
      error()
      local l_msg="$1"
      # use ansi red for error
      color_msg $red "Error: $l_msg" 1>&2
      exit 1


      #
      # show the usage
      #
      usage()
      echo "usage: $0 domain sites"
      exit 1


      #
      # check known_hosts entry for server
      #
      checkknown()
      local l_server="$1"
      #echo $l_server
      local l_sid="$(ssh-keyscan $l_server 2>/dev/null)"
      #echo $l_sid
      if (! grep "$l_sid" $sknown) > /dev/null
      then
      color_msg $blue "adding $l_server to $sknown"
      ssh-keyscan $l_server >> $sknown 2>&1
      fi


      #
      # check the given server
      #
      checkserver() yes) ssh-copy-id $l_server
      esac
      fi


      #
      # check all servers
      #
      checkservers()
      me=$(hostname -f)
      for server in $(echo $*

      #
      # check configuration
      #
      checkconfig()
      #https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh
      if [ -f $sconfig ]
      then
      color_msg $green "$sconfig exists"
      ls -l $sconfig
      fi


      sconfig=~/.ssh/config
      sknown=~/.ssh/known_hosts

      case $# in
      0) usage ;;
      1) usage ;;
      *)
      domain=$1
      shift
      color_msg $blue "checking ssh configuration for domain $domain sites $*"
      checkconfig
      checkservers $*
      #for server in $(echo $* | sort)
      ##do
      # checkknown $server
      #done
      ;;
      esac





      share|improve this answer
































        3














        How are you building these machines? can you run a dns update script? can you join an IPA Domain?



        FreeIPA does this automatically, but essentially all you need is SSHFP dns records and DNSSEC on your zone (freeipa provides as configurable options (dnssec disabled by default)).



        You can get the existing SSHFP records from your host by running.



        ssh-keygen -r jersey.jacobdevans.com




        jersey.jacobdevans.com IN SSHFP 1 1 4d8589de6b1a48e148d8fc9fbb967f1b29f53ebc jersey.jacobdevans.com IN SSHFP 1 2 6503272a11ba6d7fec2518c02dfed88f3d455ac7786ee5dbd72df63307209d55
        jersey.jacobdevans.com IN SSHFP 3 1 5a7a1e8ab8f25b86b63c377b303659289b895736 > jersey.jacobdevans.com IN SSHFP 3 2 1f50f790117dfedd329dbcf622a7d47551e12ff5913902c66a7da28e47de4f4b




        then once published, you'd add VerifyHostKeyDNS yes to your ssh_config or ~/.ssh/config



        If/When google decides to flip on DNSSEC, you could ssh in without a hostkey prompt.



        ssh jersey.jacobdevans.com



        BUT my domain is not signed yet, so for now you'd see....




        debug1: Server host key: ecdsa-sha2-nistp256 SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s



        debug1: found 4 insecure fingerprints in DNS



        debug1: matching host key fingerprint



        found in DNS The authenticity of host 'jersey.jacobdevans.com (2605:6400:10:434::10)' can't be established. ECDSA key fingerprint is
        SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s. Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? no







        share|improve this answer
































          1














          Here is how to do a collection of hosts



          define a collection of hosts



          ssh_hosts:
          - server1.domain.com
          - server2.domain.com
          - server3.domain.com
          - server4.domain.com
          - server5.domain.com
          - server6.domain.com
          - server7.domain.com
          - server8.domain.com
          - server9.domain.com


          Then define two tasks to add the keys to known hosts:



          - command: "ssh-keyscan item"
          register: known_host_keys
          with_items: "ssh_hosts"
          tags:
          - "ssh"

          - name: Add ssh keys to know hosts
          known_hosts:
          name: "item.item"
          key: "item.stdout"
          path: ~/.ssh/known_hosts
          with_items: "known_host_keys.results"





          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "2"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f132970%2fcan-i-automatically-add-a-new-host-to-known-hosts%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            15 Answers
            15






            active

            oldest

            votes








            15 Answers
            15






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            140














            Set the StrictHostKeyChecking option to no, either in the config file or via -o :



            ssh -o StrictHostKeyChecking=no username@hostname.com






            share|improve this answer




















            • 60





              This leaves you open to man in the middle attacks, probably not a good idea.

              – JasperWallace
              Sep 23 '13 at 7:23






            • 9





              @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

              – Massimo
              Oct 21 '14 at 17:33






            • 8





              This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

              – Peter V. Mørch
              May 21 '15 at 9:19







            • 9





              Downvoting as this does not answer the question and opens to serious security vulnerabilities.

              – marcv81
              Jan 20 '16 at 4:48






            • 11





              @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

              – Ignacio Vazquez-Abrams
              Jun 15 '16 at 17:31















            140














            Set the StrictHostKeyChecking option to no, either in the config file or via -o :



            ssh -o StrictHostKeyChecking=no username@hostname.com






            share|improve this answer




















            • 60





              This leaves you open to man in the middle attacks, probably not a good idea.

              – JasperWallace
              Sep 23 '13 at 7:23






            • 9





              @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

              – Massimo
              Oct 21 '14 at 17:33






            • 8





              This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

              – Peter V. Mørch
              May 21 '15 at 9:19







            • 9





              Downvoting as this does not answer the question and opens to serious security vulnerabilities.

              – marcv81
              Jan 20 '16 at 4:48






            • 11





              @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

              – Ignacio Vazquez-Abrams
              Jun 15 '16 at 17:31













            140












            140








            140







            Set the StrictHostKeyChecking option to no, either in the config file or via -o :



            ssh -o StrictHostKeyChecking=no username@hostname.com






            share|improve this answer















            Set the StrictHostKeyChecking option to no, either in the config file or via -o :



            ssh -o StrictHostKeyChecking=no username@hostname.com







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 3 '14 at 9:53









            Jason

            1356




            1356










            answered Apr 16 '10 at 4:34









            Ignacio Vazquez-AbramsIgnacio Vazquez-Abrams

            39.8k46377




            39.8k46377







            • 60





              This leaves you open to man in the middle attacks, probably not a good idea.

              – JasperWallace
              Sep 23 '13 at 7:23






            • 9





              @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

              – Massimo
              Oct 21 '14 at 17:33






            • 8





              This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

              – Peter V. Mørch
              May 21 '15 at 9:19







            • 9





              Downvoting as this does not answer the question and opens to serious security vulnerabilities.

              – marcv81
              Jan 20 '16 at 4:48






            • 11





              @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

              – Ignacio Vazquez-Abrams
              Jun 15 '16 at 17:31












            • 60





              This leaves you open to man in the middle attacks, probably not a good idea.

              – JasperWallace
              Sep 23 '13 at 7:23






            • 9





              @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

              – Massimo
              Oct 21 '14 at 17:33






            • 8





              This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

              – Peter V. Mørch
              May 21 '15 at 9:19







            • 9





              Downvoting as this does not answer the question and opens to serious security vulnerabilities.

              – marcv81
              Jan 20 '16 at 4:48






            • 11





              @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

              – Ignacio Vazquez-Abrams
              Jun 15 '16 at 17:31







            60




            60





            This leaves you open to man in the middle attacks, probably not a good idea.

            – JasperWallace
            Sep 23 '13 at 7:23





            This leaves you open to man in the middle attacks, probably not a good idea.

            – JasperWallace
            Sep 23 '13 at 7:23




            9




            9





            @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

            – Massimo
            Oct 21 '14 at 17:33





            @JasperWallace, while this is usually good advice, the specific use case (deploying test VMs and sending commands to them) should be safe enough.

            – Massimo
            Oct 21 '14 at 17:33




            8




            8





            This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

            – Peter V. Mørch
            May 21 '15 at 9:19






            This gives a Warning: Permanently added 'hostname,1.2.3.4' (RSA) to the list of known hosts. To avoid the warning, and to avoid the entry being added to any known_hosts file, I do: ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null username@hostname.com

            – Peter V. Mørch
            May 21 '15 at 9:19





            9




            9





            Downvoting as this does not answer the question and opens to serious security vulnerabilities.

            – marcv81
            Jan 20 '16 at 4:48





            Downvoting as this does not answer the question and opens to serious security vulnerabilities.

            – marcv81
            Jan 20 '16 at 4:48




            11




            11





            @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

            – Ignacio Vazquez-Abrams
            Jun 15 '16 at 17:31





            @Mnebuerquo: If you were worried about security then you wouldn't have anything at all to do with this question. You'd have the correct host key in front of you, gathered from the console of the system you wanted to connect to, and you would manually verify it upon first connecting. You certainly wouldn't do anything "automatically".

            – Ignacio Vazquez-Abrams
            Jun 15 '16 at 17:31













            218














            IMO, the best way to do this is the following:



            ssh-keygen -R [hostname]
            ssh-keygen -R [ip_address]
            ssh-keygen -R [hostname],[ip_address]
            ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts


            That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.






            share|improve this answer




















            • 4





              Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

              – Robert
              May 24 '13 at 22:00






            • 6





              Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

              – JasperWallace
              Sep 23 '13 at 7:24







            • 2





              @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

              – user68729
              Apr 28 '14 at 21:57






            • 1





              Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

              – phasetwenty
              Aug 6 '14 at 18:11






            • 4





              This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

              – retrohacker
              Sep 29 '15 at 3:04
















            218














            IMO, the best way to do this is the following:



            ssh-keygen -R [hostname]
            ssh-keygen -R [ip_address]
            ssh-keygen -R [hostname],[ip_address]
            ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts


            That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.






            share|improve this answer




















            • 4





              Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

              – Robert
              May 24 '13 at 22:00






            • 6





              Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

              – JasperWallace
              Sep 23 '13 at 7:24







            • 2





              @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

              – user68729
              Apr 28 '14 at 21:57






            • 1





              Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

              – phasetwenty
              Aug 6 '14 at 18:11






            • 4





              This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

              – retrohacker
              Sep 29 '15 at 3:04














            218












            218








            218







            IMO, the best way to do this is the following:



            ssh-keygen -R [hostname]
            ssh-keygen -R [ip_address]
            ssh-keygen -R [hostname],[ip_address]
            ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts


            That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.






            share|improve this answer















            IMO, the best way to do this is the following:



            ssh-keygen -R [hostname]
            ssh-keygen -R [ip_address]
            ssh-keygen -R [hostname],[ip_address]
            ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
            ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts


            That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 27 '11 at 22:14

























            answered Sep 27 '11 at 20:51









            yardenayardena

            2,3441105




            2,3441105







            • 4





              Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

              – Robert
              May 24 '13 at 22:00






            • 6





              Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

              – JasperWallace
              Sep 23 '13 at 7:24







            • 2





              @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

              – user68729
              Apr 28 '14 at 21:57






            • 1





              Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

              – phasetwenty
              Aug 6 '14 at 18:11






            • 4





              This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

              – retrohacker
              Sep 29 '15 at 3:04













            • 4





              Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

              – Robert
              May 24 '13 at 22:00






            • 6





              Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

              – JasperWallace
              Sep 23 '13 at 7:24







            • 2





              @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

              – user68729
              Apr 28 '14 at 21:57






            • 1





              Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

              – phasetwenty
              Aug 6 '14 at 18:11






            • 4





              This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

              – retrohacker
              Sep 29 '15 at 3:04








            4




            4





            Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

            – Robert
            May 24 '13 at 22:00





            Why do you need all 3 ssh-keyscan's? Can't you get by with just the first one since it works for both hostname and ip?

            – Robert
            May 24 '13 at 22:00




            6




            6





            Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

            – JasperWallace
            Sep 23 '13 at 7:24






            Can you be sure that the machine replying to the ssh-keyscan request is really the one you want to talk to? If not you've opened yourself to a man in the middle attack.

            – JasperWallace
            Sep 23 '13 at 7:24





            2




            2





            @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

            – user68729
            Apr 28 '14 at 21:57





            @JasperWallace Yes, for that you need at least the fingerprint or even better the public key, in which case you can add it directly to known_hosts, turning this question moot. If you only have the fingerprint, you will have to write an extra step which verifies the downloaded public key with your fingerprint...

            – user68729
            Apr 28 '14 at 21:57




            1




            1





            Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

            – phasetwenty
            Aug 6 '14 at 18:11





            Calls to ssh-keyscan were failing for me because my target host doesn't support the default version 1 key type. Adding -t rsa,dsa to the command fixed this.

            – phasetwenty
            Aug 6 '14 at 18:11




            4




            4





            This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

            – retrohacker
            Sep 29 '15 at 3:04






            This is probably a bad idea. You are opening yourself to a man-in-the-middle attack by updating these keys. To avoid duplicate entries, check the return status of ssh-keygen -F [address] instead. medium.com/@wblankenship/…

            – retrohacker
            Sep 29 '15 at 3:04












            89














            For the lazy ones:



            ssh-keyscan -H <host> >> ~/.ssh/known_hosts


            -H hashes the hostname / IP address






            share|improve this answer




















            • 2





              "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

              – Sarah Messer
              Sep 4 '15 at 20:19






            • 3





              Vulnerable to MITM attacks. You're not checking the key fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 7





              @Mnebuerquo You say what to do but not how, which would be helpful.

              – Jim
              Mar 24 '17 at 21:20






            • 3





              @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

              – fivef
              Nov 30 '17 at 9:07







            • 1





              @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

              – Waqas Shah
              Jan 4 '18 at 4:22















            89














            For the lazy ones:



            ssh-keyscan -H <host> >> ~/.ssh/known_hosts


            -H hashes the hostname / IP address






            share|improve this answer




















            • 2





              "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

              – Sarah Messer
              Sep 4 '15 at 20:19






            • 3





              Vulnerable to MITM attacks. You're not checking the key fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 7





              @Mnebuerquo You say what to do but not how, which would be helpful.

              – Jim
              Mar 24 '17 at 21:20






            • 3





              @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

              – fivef
              Nov 30 '17 at 9:07







            • 1





              @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

              – Waqas Shah
              Jan 4 '18 at 4:22













            89












            89








            89







            For the lazy ones:



            ssh-keyscan -H <host> >> ~/.ssh/known_hosts


            -H hashes the hostname / IP address






            share|improve this answer















            For the lazy ones:



            ssh-keyscan -H <host> >> ~/.ssh/known_hosts


            -H hashes the hostname / IP address







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 15 at 12:10

























            answered Sep 25 '14 at 10:03









            fiveffivef

            99963




            99963







            • 2





              "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

              – Sarah Messer
              Sep 4 '15 at 20:19






            • 3





              Vulnerable to MITM attacks. You're not checking the key fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 7





              @Mnebuerquo You say what to do but not how, which would be helpful.

              – Jim
              Mar 24 '17 at 21:20






            • 3





              @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

              – fivef
              Nov 30 '17 at 9:07







            • 1





              @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

              – Waqas Shah
              Jan 4 '18 at 4:22












            • 2





              "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

              – Sarah Messer
              Sep 4 '15 at 20:19






            • 3





              Vulnerable to MITM attacks. You're not checking the key fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 7





              @Mnebuerquo You say what to do but not how, which would be helpful.

              – Jim
              Mar 24 '17 at 21:20






            • 3





              @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

              – fivef
              Nov 30 '17 at 9:07







            • 1





              @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

              – Waqas Shah
              Jan 4 '18 at 4:22







            2




            2





            "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

            – Sarah Messer
            Sep 4 '15 at 20:19





            "ssh-keyscan -H <host> >> ~/.ssh/known_hosts" produces an entry more like what ssh does with user interaction. (The -H hashes the name of the remote host.)

            – Sarah Messer
            Sep 4 '15 at 20:19




            3




            3





            Vulnerable to MITM attacks. You're not checking the key fingerprint.

            – Mnebuerquo
            Jun 15 '16 at 17:20





            Vulnerable to MITM attacks. You're not checking the key fingerprint.

            – Mnebuerquo
            Jun 15 '16 at 17:20




            7




            7





            @Mnebuerquo You say what to do but not how, which would be helpful.

            – Jim
            Mar 24 '17 at 21:20





            @Mnebuerquo You say what to do but not how, which would be helpful.

            – Jim
            Mar 24 '17 at 21:20




            3




            3





            @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

            – fivef
            Nov 30 '17 at 9:07






            @jameshfisher Yes its vulnerable to MITM attacks, but have you ever compared the RSA fingerprint, which was shown to you with the actual one of the server, when you were doing this manually? No? So this answer is the way to do it for you. If yes, you shouldn't use this answer and do it manually or implement other security measures...

            – fivef
            Nov 30 '17 at 9:07





            1




            1





            @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

            – Waqas Shah
            Jan 4 '18 at 4:22





            @Mnebuerquo I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one!

            – Waqas Shah
            Jan 4 '18 at 4:22











            41














            As mentioned, using key-scan would be the right & unobtrusive way to do it.



            ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
            mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts


            The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...






            share|improve this answer

























            • Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

              – utapyngo
              May 23 '14 at 7:49






            • 1





              The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

              – paulmelnikow
              Jul 27 '15 at 17:46







            • 1





              This is subject to the same MITM attacks as the others.

              – Mnebuerquo
              Jun 15 '16 at 17:18











            • @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

              – Rich L
              Aug 17 '17 at 13:58






            • 1





              If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

              – Zart
              Nov 28 '17 at 17:09















            41














            As mentioned, using key-scan would be the right & unobtrusive way to do it.



            ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
            mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts


            The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...






            share|improve this answer

























            • Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

              – utapyngo
              May 23 '14 at 7:49






            • 1





              The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

              – paulmelnikow
              Jul 27 '15 at 17:46







            • 1





              This is subject to the same MITM attacks as the others.

              – Mnebuerquo
              Jun 15 '16 at 17:18











            • @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

              – Rich L
              Aug 17 '17 at 13:58






            • 1





              If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

              – Zart
              Nov 28 '17 at 17:09













            41












            41








            41







            As mentioned, using key-scan would be the right & unobtrusive way to do it.



            ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
            mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts


            The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...






            share|improve this answer















            As mentioned, using key-scan would be the right & unobtrusive way to do it.



            ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
            mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts


            The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 27 '15 at 19:55









            kasperd

            26.8k1252104




            26.8k1252104










            answered Mar 6 '12 at 9:00









            ysawejysawej

            51944




            51944












            • Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

              – utapyngo
              May 23 '14 at 7:49






            • 1





              The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

              – paulmelnikow
              Jul 27 '15 at 17:46







            • 1





              This is subject to the same MITM attacks as the others.

              – Mnebuerquo
              Jun 15 '16 at 17:18











            • @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

              – Rich L
              Aug 17 '17 at 13:58






            • 1





              If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

              – Zart
              Nov 28 '17 at 17:09

















            • Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

              – utapyngo
              May 23 '14 at 7:49






            • 1





              The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

              – paulmelnikow
              Jul 27 '15 at 17:46







            • 1





              This is subject to the same MITM attacks as the others.

              – Mnebuerquo
              Jun 15 '16 at 17:18











            • @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

              – Rich L
              Aug 17 '17 at 13:58






            • 1





              If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

              – Zart
              Nov 28 '17 at 17:09
















            Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

            – utapyngo
            May 23 '14 at 7:49





            Is there a way to check whether the key is in known_hosts before ssh-keyscan? The reason is that it requires some time and additional network connection.

            – utapyngo
            May 23 '14 at 7:49




            1




            1





            The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

            – paulmelnikow
            Jul 27 '15 at 17:46






            The original poster's version of this file had cat ~/.ssh/tmp_hosts > ~/.ssh/known_hosts, but a subsequent edit changed it to >>. Using >> is an error. It defeats the purpose of the uniqueness in the first line, and causes it to dump new entries into known_hosts every time it runs. (Just posted an edit to change it back.)

            – paulmelnikow
            Jul 27 '15 at 17:46





            1




            1





            This is subject to the same MITM attacks as the others.

            – Mnebuerquo
            Jun 15 '16 at 17:18





            This is subject to the same MITM attacks as the others.

            – Mnebuerquo
            Jun 15 '16 at 17:18













            @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

            – Rich L
            Aug 17 '17 at 13:58





            @utapyngo ssh-keygen -F will give you the current fingerprint. If it comes back blank with return code of 1, then you don't have it. If it prints something and return code is 0, then it's already present.

            – Rich L
            Aug 17 '17 at 13:58




            1




            1





            If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

            – Zart
            Nov 28 '17 at 17:09





            If you care that much about MITM, deploy DNSSEC and SSHFP records or use some other secure means of distributing the keys and this kludge solution will be irrelevant.

            – Zart
            Nov 28 '17 at 17:09











            18














            You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.






            share|improve this answer




















            • 3





              Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 3





              @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

              – Brian Cline
              Aug 25 '17 at 19:27












            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39















            18














            You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.






            share|improve this answer




















            • 3





              Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 3





              @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

              – Brian Cline
              Aug 25 '17 at 19:27












            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39













            18












            18








            18







            You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.






            share|improve this answer















            You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 21 '15 at 21:08









            kenorb

            3,2933042




            3,2933042










            answered Apr 16 '10 at 5:09









            AlexAlex

            5,94311731




            5,94311731







            • 3





              Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 3





              @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

              – Brian Cline
              Aug 25 '17 at 19:27












            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39












            • 3





              Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

              – Mnebuerquo
              Jun 15 '16 at 17:20






            • 3





              @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

              – Brian Cline
              Aug 25 '17 at 19:27












            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39







            3




            3





            Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

            – Mnebuerquo
            Jun 15 '16 at 17:20





            Make sure you check the fingerprint to ensure it is the correct key. Otherwise you open yourself up to MITM attacks.

            – Mnebuerquo
            Jun 15 '16 at 17:20




            3




            3





            @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

            – Brian Cline
            Aug 25 '17 at 19:27






            @Mnebuerquo Fair point in the general context, but why would someone be trying to programmatically gather keys if they already knew what the correct key was?

            – Brian Cline
            Aug 25 '17 at 19:27














            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:39





            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:39











            7














            This is how you can incorporate ssh-keyscan into your play:



            ---
            # ansible playbook that adds ssh fingerprints to known_hosts
            - hosts: all
            connection: local
            gather_facts: no
            tasks:
            - command: /usr/bin/ssh-keyscan -T 10 ansible_host
            register: keyscan
            - lineinfile: name=~/.ssh/known_hosts create=yes line= item
            with_items: ' keyscan.stdout_lines '





            share|improve this answer


















            • 1





              Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

              – Mnebuerquo
              Jun 15 '16 at 17:22






            • 1





              This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

              – Zart
              Jun 16 '16 at 21:42











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39






            • 2





              @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

              – Waqas Shah
              Jan 4 '18 at 4:25











            • It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

              – Cameron Lowell Palmer
              Nov 23 '18 at 14:15















            7














            This is how you can incorporate ssh-keyscan into your play:



            ---
            # ansible playbook that adds ssh fingerprints to known_hosts
            - hosts: all
            connection: local
            gather_facts: no
            tasks:
            - command: /usr/bin/ssh-keyscan -T 10 ansible_host
            register: keyscan
            - lineinfile: name=~/.ssh/known_hosts create=yes line= item
            with_items: ' keyscan.stdout_lines '





            share|improve this answer


















            • 1





              Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

              – Mnebuerquo
              Jun 15 '16 at 17:22






            • 1





              This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

              – Zart
              Jun 16 '16 at 21:42











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39






            • 2





              @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

              – Waqas Shah
              Jan 4 '18 at 4:25











            • It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

              – Cameron Lowell Palmer
              Nov 23 '18 at 14:15













            7












            7








            7







            This is how you can incorporate ssh-keyscan into your play:



            ---
            # ansible playbook that adds ssh fingerprints to known_hosts
            - hosts: all
            connection: local
            gather_facts: no
            tasks:
            - command: /usr/bin/ssh-keyscan -T 10 ansible_host
            register: keyscan
            - lineinfile: name=~/.ssh/known_hosts create=yes line= item
            with_items: ' keyscan.stdout_lines '





            share|improve this answer













            This is how you can incorporate ssh-keyscan into your play:



            ---
            # ansible playbook that adds ssh fingerprints to known_hosts
            - hosts: all
            connection: local
            gather_facts: no
            tasks:
            - command: /usr/bin/ssh-keyscan -T 10 ansible_host
            register: keyscan
            - lineinfile: name=~/.ssh/known_hosts create=yes line= item
            with_items: ' keyscan.stdout_lines '






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 3 '16 at 3:12









            ZartZart

            29436




            29436







            • 1





              Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

              – Mnebuerquo
              Jun 15 '16 at 17:22






            • 1





              This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

              – Zart
              Jun 16 '16 at 21:42











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39






            • 2





              @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

              – Waqas Shah
              Jan 4 '18 at 4:25











            • It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

              – Cameron Lowell Palmer
              Nov 23 '18 at 14:15












            • 1





              Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

              – Mnebuerquo
              Jun 15 '16 at 17:22






            • 1





              This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

              – Zart
              Jun 16 '16 at 21:42











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:39






            • 2





              @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

              – Waqas Shah
              Jan 4 '18 at 4:25











            • It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

              – Cameron Lowell Palmer
              Nov 23 '18 at 14:15







            1




            1





            Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

            – Mnebuerquo
            Jun 15 '16 at 17:22





            Are you uploading a known valid known_hosts file, or are you doing ssh-keyscan and dumping the output into known_hosts without verifying fingerprints?

            – Mnebuerquo
            Jun 15 '16 at 17:22




            1




            1





            This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

            – Zart
            Jun 16 '16 at 21:42





            This is simply dumps output of a keyscan, yes. So in effect it's the same as StrictHostKeyChecking=no, just with silent known_hosts updating without fiddling with ssh options. This solution also doesn't work well due to ssh-keyscan returning multiple lines which causes this task always be flagged as 'changed'

            – Zart
            Jun 16 '16 at 21:42













            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:39





            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:39




            2




            2





            @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

            – Waqas Shah
            Jan 4 '18 at 4:25





            @jameshfisher I would be really glad if you also let us know a better way to handle this, when we need to clone a repo using batch scripts un-attended and we want to by-pass this prompt. Please shed some light on a real solution if you think this is not the right one! Please let us know "how" to do it, if you think this is not the right way to do it!

            – Waqas Shah
            Jan 4 '18 at 4:25













            It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

            – Cameron Lowell Palmer
            Nov 23 '18 at 14:15





            It is a perfectly valid method of adding values to known_hosts, but yes it is susceptible to MITM. However, for internal use it is fine.

            – Cameron Lowell Palmer
            Nov 23 '18 at 14:15











            6














            this would be a complete solution, accepting host key for the first time only



            #!/usr/bin/env ansible-playbook
            ---
            - name: accept ssh fingerprint automatically for the first time
            hosts: all
            connection: local
            gather_facts: False

            tasks:
            - name: "check if known_hosts contains server's fingerprint"
            command: ssh-keygen -F inventory_hostname
            register: keygen
            failed_when: keygen.stderr != ''
            changed_when: False

            - name: fetch remote ssh key
            command: ssh-keyscan -T5 inventory_hostname
            register: keyscan
            failed_when: keyscan.rc != 0 or keyscan.stdout == ''
            changed_when: False
            when: keygen.rc == 1

            - name: add ssh-key to local known_hosts
            lineinfile:
            name: ~/.ssh/known_hosts
            create: yes
            line: " item "
            when: keygen.rc == 1
            with_items: 'default([]) '





            share|improve this answer

























            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40















            6














            this would be a complete solution, accepting host key for the first time only



            #!/usr/bin/env ansible-playbook
            ---
            - name: accept ssh fingerprint automatically for the first time
            hosts: all
            connection: local
            gather_facts: False

            tasks:
            - name: "check if known_hosts contains server's fingerprint"
            command: ssh-keygen -F inventory_hostname
            register: keygen
            failed_when: keygen.stderr != ''
            changed_when: False

            - name: fetch remote ssh key
            command: ssh-keyscan -T5 inventory_hostname
            register: keyscan
            failed_when: keyscan.rc != 0 or keyscan.stdout == ''
            changed_when: False
            when: keygen.rc == 1

            - name: add ssh-key to local known_hosts
            lineinfile:
            name: ~/.ssh/known_hosts
            create: yes
            line: " item "
            when: keygen.rc == 1
            with_items: 'default([]) '





            share|improve this answer

























            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40













            6












            6








            6







            this would be a complete solution, accepting host key for the first time only



            #!/usr/bin/env ansible-playbook
            ---
            - name: accept ssh fingerprint automatically for the first time
            hosts: all
            connection: local
            gather_facts: False

            tasks:
            - name: "check if known_hosts contains server's fingerprint"
            command: ssh-keygen -F inventory_hostname
            register: keygen
            failed_when: keygen.stderr != ''
            changed_when: False

            - name: fetch remote ssh key
            command: ssh-keyscan -T5 inventory_hostname
            register: keyscan
            failed_when: keyscan.rc != 0 or keyscan.stdout == ''
            changed_when: False
            when: keygen.rc == 1

            - name: add ssh-key to local known_hosts
            lineinfile:
            name: ~/.ssh/known_hosts
            create: yes
            line: " item "
            when: keygen.rc == 1
            with_items: 'default([]) '





            share|improve this answer















            this would be a complete solution, accepting host key for the first time only



            #!/usr/bin/env ansible-playbook
            ---
            - name: accept ssh fingerprint automatically for the first time
            hosts: all
            connection: local
            gather_facts: False

            tasks:
            - name: "check if known_hosts contains server's fingerprint"
            command: ssh-keygen -F inventory_hostname
            register: keygen
            failed_when: keygen.stderr != ''
            changed_when: False

            - name: fetch remote ssh key
            command: ssh-keyscan -T5 inventory_hostname
            register: keyscan
            failed_when: keyscan.rc != 0 or keyscan.stdout == ''
            changed_when: False
            when: keygen.rc == 1

            - name: add ssh-key to local known_hosts
            lineinfile:
            name: ~/.ssh/known_hosts
            create: yes
            line: " item "
            when: keygen.rc == 1
            with_items: 'default([]) '






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '16 at 15:06

























            answered Nov 23 '16 at 13:51









            mazacmazac

            6113




            6113












            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40

















            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40
















            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:40





            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:40











            5














            I had a similar issue and found that some of the provided answers only got me part way to an automated solution. The following is what I ended up using, hope it helps:



            ssh -o "StrictHostKeyChecking no" -o PasswordAuthentication=no 10.x.x.x


            It adds the key to known_hosts and doesn't prompt for the password.






            share|improve this answer


















            • 1





              Vulnerable to MITM attacks. You're not checking the fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:23






            • 3





              Nobody checks the fingerprint.

              – Brendan Byrd
              Jun 2 '17 at 3:11











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40















            5














            I had a similar issue and found that some of the provided answers only got me part way to an automated solution. The following is what I ended up using, hope it helps:



            ssh -o "StrictHostKeyChecking no" -o PasswordAuthentication=no 10.x.x.x


            It adds the key to known_hosts and doesn't prompt for the password.






            share|improve this answer


















            • 1





              Vulnerable to MITM attacks. You're not checking the fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:23






            • 3





              Nobody checks the fingerprint.

              – Brendan Byrd
              Jun 2 '17 at 3:11











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40













            5












            5








            5







            I had a similar issue and found that some of the provided answers only got me part way to an automated solution. The following is what I ended up using, hope it helps:



            ssh -o "StrictHostKeyChecking no" -o PasswordAuthentication=no 10.x.x.x


            It adds the key to known_hosts and doesn't prompt for the password.






            share|improve this answer













            I had a similar issue and found that some of the provided answers only got me part way to an automated solution. The following is what I ended up using, hope it helps:



            ssh -o "StrictHostKeyChecking no" -o PasswordAuthentication=no 10.x.x.x


            It adds the key to known_hosts and doesn't prompt for the password.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 21 '14 at 17:27









            VenomFangsVenomFangs

            234249




            234249







            • 1





              Vulnerable to MITM attacks. You're not checking the fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:23






            • 3





              Nobody checks the fingerprint.

              – Brendan Byrd
              Jun 2 '17 at 3:11











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40












            • 1





              Vulnerable to MITM attacks. You're not checking the fingerprint.

              – Mnebuerquo
              Jun 15 '16 at 17:23






            • 3





              Nobody checks the fingerprint.

              – Brendan Byrd
              Jun 2 '17 at 3:11











            • This is not the way to do it. MITM.

              – jameshfisher
              Nov 28 '17 at 16:40







            1




            1





            Vulnerable to MITM attacks. You're not checking the fingerprint.

            – Mnebuerquo
            Jun 15 '16 at 17:23





            Vulnerable to MITM attacks. You're not checking the fingerprint.

            – Mnebuerquo
            Jun 15 '16 at 17:23




            3




            3





            Nobody checks the fingerprint.

            – Brendan Byrd
            Jun 2 '17 at 3:11





            Nobody checks the fingerprint.

            – Brendan Byrd
            Jun 2 '17 at 3:11













            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:40





            This is not the way to do it. MITM.

            – jameshfisher
            Nov 28 '17 at 16:40











            4














            So, I was searching for a mundane way to bypass the unkown host manual interaction of cloning a git repo as shown below:



            brad@computer:~$ git clone git@bitbucket.org:viperks/viperks-api.git
            Cloning into 'viperks-api'...
            The authenticity of host 'bitbucket.org (104.192.143.3)' can't be established.
            RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
            Are you sure you want to continue connecting (yes/no)?


            Note the RSA key fingerprint...



            So, this is a SSH thing, this will work for git over SSH and just SSH related things in general...



            brad@computer:~$ nmap bitbucket.org --script ssh-hostkey

            Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-05 10:21 EDT
            Nmap scan report for bitbucket.org (104.192.143.3)
            Host is up (0.032s latency).
            Other addresses for bitbucket.org (not scanned): 104.192.143.2 104.192.143.1 2401:1d80:1010::150
            Not shown: 997 filtered ports
            PORT STATE SERVICE
            22/tcp open ssh
            | ssh-hostkey:
            | 1024 35:ee:d7:b8:ef:d7:79:e2:c6:43:9e:ab:40:6f:50:74 (DSA)
            |_ 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40 (RSA)
            80/tcp open http
            443/tcp open https

            Nmap done: 1 IP address (1 host up) scanned in 42.42 seconds


            First, install nmap on your daily driver. nmap is highly helpful for certain things, like detecting open ports and this-- manually verifying SSH fingerprints. But, back to what we are doing.



            Good. I'm either compromised at the multiple places and machines I've checked it-- or the more plausible explanation of everything being hunky dory is what is happening.



            That 'fingerprint' is just a string shortened with a one way algorithm for our human convenience at the risk of more than one string resolving into the same fingerprint. It happens, they are called collisions.



            Regardless, back to the original string which we can see in context below.



            brad@computer:~$ ssh-keyscan bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            no hostkey alg
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-129
            bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-123
            no hostkey alg


            So, ahead of time, we have a way of asking for a form of identification from the original host.



            At this point we manually are as vulnerable as automatically-- the strings match, we have the base data that creates the fingerprint, and we could ask for that base data (preventing collisions) in the future.



            Now to use that string in a way that prevents asking about a hosts authenticity...



            The known_hosts file in this case does not use plaintext entries. You'll know hashed entries when you see them, they look like hashes with random characters instead of xyz.com or 123.45.67.89.



            brad@computer:~$ ssh-keyscan -t rsa -H bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            |1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==


            The first comment line infuriatingly shows up-- but you can get rid of it with a simple redirect via the ">" or ">>" convention.



            As I've done my best to obtain untainted data to be used to identify a "host" and trust, I will add this identification to my known_hosts file in my ~/.ssh directory. Since it will now be identified as a known host, I will not get the prompt mentioned above when you were a youngster.



            Thanks for sticking with me, here you go. I'm adding the bitbucket RSA key so that I can interact with my git repositories there in a non-interactive way as part of a CI workflow, but whatever you do what you want.



            #!/bin/bash
            cp ~/.ssh/known_hosts ~/.ssh/known_hosts.old && echo "|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==" >> ~/.ssh/known_hosts


            So, that's how you stay a virgin for today. You can do the same with github by following similar directions on your own time.



            I saw so many stack overflow posts telling you to programmatically add the key blindly without any kind of checking. The more you check the key from different machines on different networks, the more trust you can have that the host is the one it says it is-- and that is the best you can hope from this layer of security.



            WRONG
            ssh -oStrictHostKeyChecking=no hostname [command]



            WRONG
            ssh-keyscan -t rsa -H hostname >> ~/.ssh/known_hosts



            Don't do either of the above things, please. You're given the opportunity to increase your chances of avoiding someone eavesdropping on your data transfers via a man in the middle attack-- take that opportunity. The difference is literally verifying that the RSA key you have is the one of the bona fide server and now you know how to get that information to compare them so you can trust the connection. Just remember more comparisons from different computers & networks will usually increase your ability to trust the connection.






            share|improve this answer























            • I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

              – Waqas Shah
              Jan 5 '18 at 4:37











            • ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

              – BradChesney79
              Jan 15 '18 at 19:51











            • Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

              – Micah R Ledbetter
              Feb 7 '18 at 17:40











            • ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

              – BradChesney79
              Feb 7 '18 at 19:06











            • This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

              – vastlysuperiorman
              Jun 26 '18 at 17:28















            4














            So, I was searching for a mundane way to bypass the unkown host manual interaction of cloning a git repo as shown below:



            brad@computer:~$ git clone git@bitbucket.org:viperks/viperks-api.git
            Cloning into 'viperks-api'...
            The authenticity of host 'bitbucket.org (104.192.143.3)' can't be established.
            RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
            Are you sure you want to continue connecting (yes/no)?


            Note the RSA key fingerprint...



            So, this is a SSH thing, this will work for git over SSH and just SSH related things in general...



            brad@computer:~$ nmap bitbucket.org --script ssh-hostkey

            Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-05 10:21 EDT
            Nmap scan report for bitbucket.org (104.192.143.3)
            Host is up (0.032s latency).
            Other addresses for bitbucket.org (not scanned): 104.192.143.2 104.192.143.1 2401:1d80:1010::150
            Not shown: 997 filtered ports
            PORT STATE SERVICE
            22/tcp open ssh
            | ssh-hostkey:
            | 1024 35:ee:d7:b8:ef:d7:79:e2:c6:43:9e:ab:40:6f:50:74 (DSA)
            |_ 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40 (RSA)
            80/tcp open http
            443/tcp open https

            Nmap done: 1 IP address (1 host up) scanned in 42.42 seconds


            First, install nmap on your daily driver. nmap is highly helpful for certain things, like detecting open ports and this-- manually verifying SSH fingerprints. But, back to what we are doing.



            Good. I'm either compromised at the multiple places and machines I've checked it-- or the more plausible explanation of everything being hunky dory is what is happening.



            That 'fingerprint' is just a string shortened with a one way algorithm for our human convenience at the risk of more than one string resolving into the same fingerprint. It happens, they are called collisions.



            Regardless, back to the original string which we can see in context below.



            brad@computer:~$ ssh-keyscan bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            no hostkey alg
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-129
            bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-123
            no hostkey alg


            So, ahead of time, we have a way of asking for a form of identification from the original host.



            At this point we manually are as vulnerable as automatically-- the strings match, we have the base data that creates the fingerprint, and we could ask for that base data (preventing collisions) in the future.



            Now to use that string in a way that prevents asking about a hosts authenticity...



            The known_hosts file in this case does not use plaintext entries. You'll know hashed entries when you see them, they look like hashes with random characters instead of xyz.com or 123.45.67.89.



            brad@computer:~$ ssh-keyscan -t rsa -H bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            |1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==


            The first comment line infuriatingly shows up-- but you can get rid of it with a simple redirect via the ">" or ">>" convention.



            As I've done my best to obtain untainted data to be used to identify a "host" and trust, I will add this identification to my known_hosts file in my ~/.ssh directory. Since it will now be identified as a known host, I will not get the prompt mentioned above when you were a youngster.



            Thanks for sticking with me, here you go. I'm adding the bitbucket RSA key so that I can interact with my git repositories there in a non-interactive way as part of a CI workflow, but whatever you do what you want.



            #!/bin/bash
            cp ~/.ssh/known_hosts ~/.ssh/known_hosts.old && echo "|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==" >> ~/.ssh/known_hosts


            So, that's how you stay a virgin for today. You can do the same with github by following similar directions on your own time.



            I saw so many stack overflow posts telling you to programmatically add the key blindly without any kind of checking. The more you check the key from different machines on different networks, the more trust you can have that the host is the one it says it is-- and that is the best you can hope from this layer of security.



            WRONG
            ssh -oStrictHostKeyChecking=no hostname [command]



            WRONG
            ssh-keyscan -t rsa -H hostname >> ~/.ssh/known_hosts



            Don't do either of the above things, please. You're given the opportunity to increase your chances of avoiding someone eavesdropping on your data transfers via a man in the middle attack-- take that opportunity. The difference is literally verifying that the RSA key you have is the one of the bona fide server and now you know how to get that information to compare them so you can trust the connection. Just remember more comparisons from different computers & networks will usually increase your ability to trust the connection.






            share|improve this answer























            • I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

              – Waqas Shah
              Jan 5 '18 at 4:37











            • ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

              – BradChesney79
              Jan 15 '18 at 19:51











            • Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

              – Micah R Ledbetter
              Feb 7 '18 at 17:40











            • ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

              – BradChesney79
              Feb 7 '18 at 19:06











            • This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

              – vastlysuperiorman
              Jun 26 '18 at 17:28













            4












            4








            4







            So, I was searching for a mundane way to bypass the unkown host manual interaction of cloning a git repo as shown below:



            brad@computer:~$ git clone git@bitbucket.org:viperks/viperks-api.git
            Cloning into 'viperks-api'...
            The authenticity of host 'bitbucket.org (104.192.143.3)' can't be established.
            RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
            Are you sure you want to continue connecting (yes/no)?


            Note the RSA key fingerprint...



            So, this is a SSH thing, this will work for git over SSH and just SSH related things in general...



            brad@computer:~$ nmap bitbucket.org --script ssh-hostkey

            Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-05 10:21 EDT
            Nmap scan report for bitbucket.org (104.192.143.3)
            Host is up (0.032s latency).
            Other addresses for bitbucket.org (not scanned): 104.192.143.2 104.192.143.1 2401:1d80:1010::150
            Not shown: 997 filtered ports
            PORT STATE SERVICE
            22/tcp open ssh
            | ssh-hostkey:
            | 1024 35:ee:d7:b8:ef:d7:79:e2:c6:43:9e:ab:40:6f:50:74 (DSA)
            |_ 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40 (RSA)
            80/tcp open http
            443/tcp open https

            Nmap done: 1 IP address (1 host up) scanned in 42.42 seconds


            First, install nmap on your daily driver. nmap is highly helpful for certain things, like detecting open ports and this-- manually verifying SSH fingerprints. But, back to what we are doing.



            Good. I'm either compromised at the multiple places and machines I've checked it-- or the more plausible explanation of everything being hunky dory is what is happening.



            That 'fingerprint' is just a string shortened with a one way algorithm for our human convenience at the risk of more than one string resolving into the same fingerprint. It happens, they are called collisions.



            Regardless, back to the original string which we can see in context below.



            brad@computer:~$ ssh-keyscan bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            no hostkey alg
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-129
            bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-123
            no hostkey alg


            So, ahead of time, we have a way of asking for a form of identification from the original host.



            At this point we manually are as vulnerable as automatically-- the strings match, we have the base data that creates the fingerprint, and we could ask for that base data (preventing collisions) in the future.



            Now to use that string in a way that prevents asking about a hosts authenticity...



            The known_hosts file in this case does not use plaintext entries. You'll know hashed entries when you see them, they look like hashes with random characters instead of xyz.com or 123.45.67.89.



            brad@computer:~$ ssh-keyscan -t rsa -H bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            |1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==


            The first comment line infuriatingly shows up-- but you can get rid of it with a simple redirect via the ">" or ">>" convention.



            As I've done my best to obtain untainted data to be used to identify a "host" and trust, I will add this identification to my known_hosts file in my ~/.ssh directory. Since it will now be identified as a known host, I will not get the prompt mentioned above when you were a youngster.



            Thanks for sticking with me, here you go. I'm adding the bitbucket RSA key so that I can interact with my git repositories there in a non-interactive way as part of a CI workflow, but whatever you do what you want.



            #!/bin/bash
            cp ~/.ssh/known_hosts ~/.ssh/known_hosts.old && echo "|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==" >> ~/.ssh/known_hosts


            So, that's how you stay a virgin for today. You can do the same with github by following similar directions on your own time.



            I saw so many stack overflow posts telling you to programmatically add the key blindly without any kind of checking. The more you check the key from different machines on different networks, the more trust you can have that the host is the one it says it is-- and that is the best you can hope from this layer of security.



            WRONG
            ssh -oStrictHostKeyChecking=no hostname [command]



            WRONG
            ssh-keyscan -t rsa -H hostname >> ~/.ssh/known_hosts



            Don't do either of the above things, please. You're given the opportunity to increase your chances of avoiding someone eavesdropping on your data transfers via a man in the middle attack-- take that opportunity. The difference is literally verifying that the RSA key you have is the one of the bona fide server and now you know how to get that information to compare them so you can trust the connection. Just remember more comparisons from different computers & networks will usually increase your ability to trust the connection.






            share|improve this answer













            So, I was searching for a mundane way to bypass the unkown host manual interaction of cloning a git repo as shown below:



            brad@computer:~$ git clone git@bitbucket.org:viperks/viperks-api.git
            Cloning into 'viperks-api'...
            The authenticity of host 'bitbucket.org (104.192.143.3)' can't be established.
            RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
            Are you sure you want to continue connecting (yes/no)?


            Note the RSA key fingerprint...



            So, this is a SSH thing, this will work for git over SSH and just SSH related things in general...



            brad@computer:~$ nmap bitbucket.org --script ssh-hostkey

            Starting Nmap 7.01 ( https://nmap.org ) at 2016-10-05 10:21 EDT
            Nmap scan report for bitbucket.org (104.192.143.3)
            Host is up (0.032s latency).
            Other addresses for bitbucket.org (not scanned): 104.192.143.2 104.192.143.1 2401:1d80:1010::150
            Not shown: 997 filtered ports
            PORT STATE SERVICE
            22/tcp open ssh
            | ssh-hostkey:
            | 1024 35:ee:d7:b8:ef:d7:79:e2:c6:43:9e:ab:40:6f:50:74 (DSA)
            |_ 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40 (RSA)
            80/tcp open http
            443/tcp open https

            Nmap done: 1 IP address (1 host up) scanned in 42.42 seconds


            First, install nmap on your daily driver. nmap is highly helpful for certain things, like detecting open ports and this-- manually verifying SSH fingerprints. But, back to what we are doing.



            Good. I'm either compromised at the multiple places and machines I've checked it-- or the more plausible explanation of everything being hunky dory is what is happening.



            That 'fingerprint' is just a string shortened with a one way algorithm for our human convenience at the risk of more than one string resolving into the same fingerprint. It happens, they are called collisions.



            Regardless, back to the original string which we can see in context below.



            brad@computer:~$ ssh-keyscan bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            no hostkey alg
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-129
            bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-123
            no hostkey alg


            So, ahead of time, we have a way of asking for a form of identification from the original host.



            At this point we manually are as vulnerable as automatically-- the strings match, we have the base data that creates the fingerprint, and we could ask for that base data (preventing collisions) in the future.



            Now to use that string in a way that prevents asking about a hosts authenticity...



            The known_hosts file in this case does not use plaintext entries. You'll know hashed entries when you see them, they look like hashes with random characters instead of xyz.com or 123.45.67.89.



            brad@computer:~$ ssh-keyscan -t rsa -H bitbucket.org
            # bitbucket.org SSH-2.0-conker_1.0.257-ce87fba app-128
            |1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==


            The first comment line infuriatingly shows up-- but you can get rid of it with a simple redirect via the ">" or ">>" convention.



            As I've done my best to obtain untainted data to be used to identify a "host" and trust, I will add this identification to my known_hosts file in my ~/.ssh directory. Since it will now be identified as a known host, I will not get the prompt mentioned above when you were a youngster.



            Thanks for sticking with me, here you go. I'm adding the bitbucket RSA key so that I can interact with my git repositories there in a non-interactive way as part of a CI workflow, but whatever you do what you want.



            #!/bin/bash
            cp ~/.ssh/known_hosts ~/.ssh/known_hosts.old && echo "|1|yr6p7i8doyLhDtrrnWDk7m9QVXk=|LuKNg9gypeDhfRo/AvLTAlxnyQw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==" >> ~/.ssh/known_hosts


            So, that's how you stay a virgin for today. You can do the same with github by following similar directions on your own time.



            I saw so many stack overflow posts telling you to programmatically add the key blindly without any kind of checking. The more you check the key from different machines on different networks, the more trust you can have that the host is the one it says it is-- and that is the best you can hope from this layer of security.



            WRONG
            ssh -oStrictHostKeyChecking=no hostname [command]



            WRONG
            ssh-keyscan -t rsa -H hostname >> ~/.ssh/known_hosts



            Don't do either of the above things, please. You're given the opportunity to increase your chances of avoiding someone eavesdropping on your data transfers via a man in the middle attack-- take that opportunity. The difference is literally verifying that the RSA key you have is the one of the bona fide server and now you know how to get that information to compare them so you can trust the connection. Just remember more comparisons from different computers & networks will usually increase your ability to trust the connection.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 5 '16 at 21:18









            BradChesney79BradChesney79

            21738




            21738












            • I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

              – Waqas Shah
              Jan 5 '18 at 4:37











            • ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

              – BradChesney79
              Jan 15 '18 at 19:51











            • Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

              – Micah R Ledbetter
              Feb 7 '18 at 17:40











            • ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

              – BradChesney79
              Feb 7 '18 at 19:06











            • This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

              – vastlysuperiorman
              Jun 26 '18 at 17:28

















            • I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

              – Waqas Shah
              Jan 5 '18 at 4:37











            • ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

              – BradChesney79
              Jan 15 '18 at 19:51











            • Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

              – Micah R Ledbetter
              Feb 7 '18 at 17:40











            • ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

              – BradChesney79
              Feb 7 '18 at 19:06











            • This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

              – vastlysuperiorman
              Jun 26 '18 at 17:28
















            I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

            – Waqas Shah
            Jan 5 '18 at 4:37





            I think this is the best solution to this problem. However, be very careful while using Nmap on something like Amazon EC2, I got a warning about the port scanning that Nmap does! Fill in their form before doing portscanning!

            – Waqas Shah
            Jan 5 '18 at 4:37













            ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

            – BradChesney79
            Jan 15 '18 at 19:51





            ...well, yeah. I don't know why you would do the port scanning from EC2. If you are logged in to your account, you can just get the keys from the actual machines. This is more for machines you don't have control over. I would assume you would have a local machine not subject to AWS port scanning restrictions to use. But, if you are in that edge case situation where you must run nmap with AWS, I suppose this warning would be helpful.

            – BradChesney79
            Jan 15 '18 at 19:51













            Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

            – Micah R Ledbetter
            Feb 7 '18 at 17:40





            Using nmap to read the SSH host key from your workstation and then trusting that value is no different than connecting via SSH with StructHostKeyChecking turned off. Its just as vulnerable to a man-in-the-middle attack.

            – Micah R Ledbetter
            Feb 7 '18 at 17:40













            ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

            – BradChesney79
            Feb 7 '18 at 19:06





            ...@MicahRLedbetter which is why I suggested that "more comparisons from different computers & networks will usually increase your ability to trust the connection". But, that is my point. If you only ever check your target host from one set of environment conditions then how would you ever know of any discrepancies? Did you have any better suggestions?

            – BradChesney79
            Feb 7 '18 at 19:06













            This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

            – vastlysuperiorman
            Jun 26 '18 at 17:28





            This is security theater. Doing something complicated to create the appearance of greater security. It doesn't matter how many different methods you use to ask the host for its key. Like asking the same person multiple times if you can trust them (maybe you call, email, text, and snail mail) . They'll always say yes, but if you're asking the wrong person, it doesn't matter.

            – vastlysuperiorman
            Jun 26 '18 at 17:28











            4














            I do a one-liner script, a bit long but useful to make this task for hosts with multiples IPs, using dig and bash



            (host=github.com; ssh-keyscan -H $host; for ip in $(dig @8.8.8.8 github.com +short); do ssh-keyscan -H $host,$ip; ssh-keyscan -H $ip; done) 2> /dev/null >> .ssh/known_hosts





            share|improve this answer



























              4














              I do a one-liner script, a bit long but useful to make this task for hosts with multiples IPs, using dig and bash



              (host=github.com; ssh-keyscan -H $host; for ip in $(dig @8.8.8.8 github.com +short); do ssh-keyscan -H $host,$ip; ssh-keyscan -H $ip; done) 2> /dev/null >> .ssh/known_hosts





              share|improve this answer

























                4












                4








                4







                I do a one-liner script, a bit long but useful to make this task for hosts with multiples IPs, using dig and bash



                (host=github.com; ssh-keyscan -H $host; for ip in $(dig @8.8.8.8 github.com +short); do ssh-keyscan -H $host,$ip; ssh-keyscan -H $ip; done) 2> /dev/null >> .ssh/known_hosts





                share|improve this answer













                I do a one-liner script, a bit long but useful to make this task for hosts with multiples IPs, using dig and bash



                (host=github.com; ssh-keyscan -H $host; for ip in $(dig @8.8.8.8 github.com +short); do ssh-keyscan -H $host,$ip; ssh-keyscan -H $ip; done) 2> /dev/null >> .ssh/known_hosts






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 18 '17 at 21:01









                Felipe AlcacibarFelipe Alcacibar

                15616




                15616





















                    4














                    The following avoid duplicate entries in ~/.ssh/known_hosts:



                    if ! grep "$(ssh-keyscan github.com 2>/dev/null)" ~/.ssh/known_hosts > /dev/null; then
                    ssh-keyscan github.com >> ~/.ssh/known_hosts
                    fi





                    share|improve this answer


















                    • 1





                      This is not the way to do it. MITM.

                      – jameshfisher
                      Nov 28 '17 at 16:42











                    • I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                      – Martin Bramwell
                      Mar 5 at 23:00















                    4














                    The following avoid duplicate entries in ~/.ssh/known_hosts:



                    if ! grep "$(ssh-keyscan github.com 2>/dev/null)" ~/.ssh/known_hosts > /dev/null; then
                    ssh-keyscan github.com >> ~/.ssh/known_hosts
                    fi





                    share|improve this answer


















                    • 1





                      This is not the way to do it. MITM.

                      – jameshfisher
                      Nov 28 '17 at 16:42











                    • I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                      – Martin Bramwell
                      Mar 5 at 23:00













                    4












                    4








                    4







                    The following avoid duplicate entries in ~/.ssh/known_hosts:



                    if ! grep "$(ssh-keyscan github.com 2>/dev/null)" ~/.ssh/known_hosts > /dev/null; then
                    ssh-keyscan github.com >> ~/.ssh/known_hosts
                    fi





                    share|improve this answer













                    The following avoid duplicate entries in ~/.ssh/known_hosts:



                    if ! grep "$(ssh-keyscan github.com 2>/dev/null)" ~/.ssh/known_hosts > /dev/null; then
                    ssh-keyscan github.com >> ~/.ssh/known_hosts
                    fi






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jul 2 '17 at 11:41









                    Amadu BahAmadu Bah

                    1813




                    1813







                    • 1





                      This is not the way to do it. MITM.

                      – jameshfisher
                      Nov 28 '17 at 16:42











                    • I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                      – Martin Bramwell
                      Mar 5 at 23:00












                    • 1





                      This is not the way to do it. MITM.

                      – jameshfisher
                      Nov 28 '17 at 16:42











                    • I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                      – Martin Bramwell
                      Mar 5 at 23:00







                    1




                    1





                    This is not the way to do it. MITM.

                    – jameshfisher
                    Nov 28 '17 at 16:42





                    This is not the way to do it. MITM.

                    – jameshfisher
                    Nov 28 '17 at 16:42













                    I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                    – Martin Bramwell
                    Mar 5 at 23:00





                    I like this answer best. For scripting initial setup of a random VPS of no importance to anyone but me, MITM risk is vanishingly small. Infinitesimal quibble ... first line needs to be mkdir -p ~/.ssh/known_hosts;

                    – Martin Bramwell
                    Mar 5 at 23:00











                    3














                    To do this properly, what you really want to do is collect the host public keys of the VMs as you create them and drop them into a file in known_hosts format. You can then use the -o GlobalKnownHostsFile=..., pointing to that file, to ensure that you're connecting to the host you believe you should be connecting to. How you do this depends on how you're setting up the virtual machines, however, but reading it off the virtual filesystem, if possible, or even getting the host to print the contents of /etc/ssh/ssh_host_rsa_key.pub during configuration may do the trick.



                    That said, this may not be worthwhile, depending on what sort of environment you're working in and who your anticipated adversaries are. Doing a simple "store on first connect" (via a scan or simply during the first "real" connection) as described in several other answers above may be considerably easier and still provide some modicum of security. However, if you do this I strongly suggest you change the user known hosts file (-o UserKnownHostsFile=...) to a file specific
                    for this particular test installation; this will avoid polluting your personal known hosts file with test information and make it easy to clean up the now useless public keys when you delete your VMs.






                    share|improve this answer



























                      3














                      To do this properly, what you really want to do is collect the host public keys of the VMs as you create them and drop them into a file in known_hosts format. You can then use the -o GlobalKnownHostsFile=..., pointing to that file, to ensure that you're connecting to the host you believe you should be connecting to. How you do this depends on how you're setting up the virtual machines, however, but reading it off the virtual filesystem, if possible, or even getting the host to print the contents of /etc/ssh/ssh_host_rsa_key.pub during configuration may do the trick.



                      That said, this may not be worthwhile, depending on what sort of environment you're working in and who your anticipated adversaries are. Doing a simple "store on first connect" (via a scan or simply during the first "real" connection) as described in several other answers above may be considerably easier and still provide some modicum of security. However, if you do this I strongly suggest you change the user known hosts file (-o UserKnownHostsFile=...) to a file specific
                      for this particular test installation; this will avoid polluting your personal known hosts file with test information and make it easy to clean up the now useless public keys when you delete your VMs.






                      share|improve this answer

























                        3












                        3








                        3







                        To do this properly, what you really want to do is collect the host public keys of the VMs as you create them and drop them into a file in known_hosts format. You can then use the -o GlobalKnownHostsFile=..., pointing to that file, to ensure that you're connecting to the host you believe you should be connecting to. How you do this depends on how you're setting up the virtual machines, however, but reading it off the virtual filesystem, if possible, or even getting the host to print the contents of /etc/ssh/ssh_host_rsa_key.pub during configuration may do the trick.



                        That said, this may not be worthwhile, depending on what sort of environment you're working in and who your anticipated adversaries are. Doing a simple "store on first connect" (via a scan or simply during the first "real" connection) as described in several other answers above may be considerably easier and still provide some modicum of security. However, if you do this I strongly suggest you change the user known hosts file (-o UserKnownHostsFile=...) to a file specific
                        for this particular test installation; this will avoid polluting your personal known hosts file with test information and make it easy to clean up the now useless public keys when you delete your VMs.






                        share|improve this answer













                        To do this properly, what you really want to do is collect the host public keys of the VMs as you create them and drop them into a file in known_hosts format. You can then use the -o GlobalKnownHostsFile=..., pointing to that file, to ensure that you're connecting to the host you believe you should be connecting to. How you do this depends on how you're setting up the virtual machines, however, but reading it off the virtual filesystem, if possible, or even getting the host to print the contents of /etc/ssh/ssh_host_rsa_key.pub during configuration may do the trick.



                        That said, this may not be worthwhile, depending on what sort of environment you're working in and who your anticipated adversaries are. Doing a simple "store on first connect" (via a scan or simply during the first "real" connection) as described in several other answers above may be considerably easier and still provide some modicum of security. However, if you do this I strongly suggest you change the user known hosts file (-o UserKnownHostsFile=...) to a file specific
                        for this particular test installation; this will avoid polluting your personal known hosts file with test information and make it easy to clean up the now useless public keys when you delete your VMs.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 12 '16 at 2:27









                        Curt J. SampsonCurt J. Sampson

                        8411821




                        8411821





















                            3














                            This whole



                            • ssh-key-scan

                            • ssh-copy-id

                            • ECSDA key warning

                            business kept annoying me so I opted for



                            One script to rule them all



                            This is a variant of the script at https://askubuntu.com/a/949731/129227 with Amadu Bah's answer https://serverfault.com/a/858957/162693 in a loop.



                            example call



                            ./sshcheck somedomain site1 site2 site3



                            The script will loop over the names sites and modify the .ssh/config and .ssh/known_hosts file and do ssh-copy-id on request - for the last feature just the let the ssh test calls fail e.g. by hitting enter 3 times on the password request.



                            sshcheck script



                            #!/bin/bash
                            # WF 2017-08-25
                            # check ssh access to bitplan servers

                            #ansi colors
                            #http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
                            blue='33[0;34m'
                            red='33[0;31m'
                            green='33[0;32m' # 'e[1;32m' is too bright for white bg.
                            endColor='33[0m'

                            #
                            # a colored message
                            # params:
                            # 1: l_color - the color of the message
                            # 2: l_msg - the message to display
                            #
                            color_msg()
                            local l_color="$1"
                            local l_msg="$2"
                            echo -e "$l_color$l_msg$endColor"


                            #
                            # error
                            #
                            # show an error message and exit
                            #
                            # params:
                            # 1: l_msg - the message to display
                            error()
                            local l_msg="$1"
                            # use ansi red for error
                            color_msg $red "Error: $l_msg" 1>&2
                            exit 1


                            #
                            # show the usage
                            #
                            usage()
                            echo "usage: $0 domain sites"
                            exit 1


                            #
                            # check known_hosts entry for server
                            #
                            checkknown()
                            local l_server="$1"
                            #echo $l_server
                            local l_sid="$(ssh-keyscan $l_server 2>/dev/null)"
                            #echo $l_sid
                            if (! grep "$l_sid" $sknown) > /dev/null
                            then
                            color_msg $blue "adding $l_server to $sknown"
                            ssh-keyscan $l_server >> $sknown 2>&1
                            fi


                            #
                            # check the given server
                            #
                            checkserver() yes) ssh-copy-id $l_server
                            esac
                            fi


                            #
                            # check all servers
                            #
                            checkservers()
                            me=$(hostname -f)
                            for server in $(echo $*

                            #
                            # check configuration
                            #
                            checkconfig()
                            #https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh
                            if [ -f $sconfig ]
                            then
                            color_msg $green "$sconfig exists"
                            ls -l $sconfig
                            fi


                            sconfig=~/.ssh/config
                            sknown=~/.ssh/known_hosts

                            case $# in
                            0) usage ;;
                            1) usage ;;
                            *)
                            domain=$1
                            shift
                            color_msg $blue "checking ssh configuration for domain $domain sites $*"
                            checkconfig
                            checkservers $*
                            #for server in $(echo $* | sort)
                            ##do
                            # checkknown $server
                            #done
                            ;;
                            esac





                            share|improve this answer





























                              3














                              This whole



                              • ssh-key-scan

                              • ssh-copy-id

                              • ECSDA key warning

                              business kept annoying me so I opted for



                              One script to rule them all



                              This is a variant of the script at https://askubuntu.com/a/949731/129227 with Amadu Bah's answer https://serverfault.com/a/858957/162693 in a loop.



                              example call



                              ./sshcheck somedomain site1 site2 site3



                              The script will loop over the names sites and modify the .ssh/config and .ssh/known_hosts file and do ssh-copy-id on request - for the last feature just the let the ssh test calls fail e.g. by hitting enter 3 times on the password request.



                              sshcheck script



                              #!/bin/bash
                              # WF 2017-08-25
                              # check ssh access to bitplan servers

                              #ansi colors
                              #http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
                              blue='33[0;34m'
                              red='33[0;31m'
                              green='33[0;32m' # 'e[1;32m' is too bright for white bg.
                              endColor='33[0m'

                              #
                              # a colored message
                              # params:
                              # 1: l_color - the color of the message
                              # 2: l_msg - the message to display
                              #
                              color_msg()
                              local l_color="$1"
                              local l_msg="$2"
                              echo -e "$l_color$l_msg$endColor"


                              #
                              # error
                              #
                              # show an error message and exit
                              #
                              # params:
                              # 1: l_msg - the message to display
                              error()
                              local l_msg="$1"
                              # use ansi red for error
                              color_msg $red "Error: $l_msg" 1>&2
                              exit 1


                              #
                              # show the usage
                              #
                              usage()
                              echo "usage: $0 domain sites"
                              exit 1


                              #
                              # check known_hosts entry for server
                              #
                              checkknown()
                              local l_server="$1"
                              #echo $l_server
                              local l_sid="$(ssh-keyscan $l_server 2>/dev/null)"
                              #echo $l_sid
                              if (! grep "$l_sid" $sknown) > /dev/null
                              then
                              color_msg $blue "adding $l_server to $sknown"
                              ssh-keyscan $l_server >> $sknown 2>&1
                              fi


                              #
                              # check the given server
                              #
                              checkserver() yes) ssh-copy-id $l_server
                              esac
                              fi


                              #
                              # check all servers
                              #
                              checkservers()
                              me=$(hostname -f)
                              for server in $(echo $*

                              #
                              # check configuration
                              #
                              checkconfig()
                              #https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh
                              if [ -f $sconfig ]
                              then
                              color_msg $green "$sconfig exists"
                              ls -l $sconfig
                              fi


                              sconfig=~/.ssh/config
                              sknown=~/.ssh/known_hosts

                              case $# in
                              0) usage ;;
                              1) usage ;;
                              *)
                              domain=$1
                              shift
                              color_msg $blue "checking ssh configuration for domain $domain sites $*"
                              checkconfig
                              checkservers $*
                              #for server in $(echo $* | sort)
                              ##do
                              # checkknown $server
                              #done
                              ;;
                              esac





                              share|improve this answer



























                                3












                                3








                                3







                                This whole



                                • ssh-key-scan

                                • ssh-copy-id

                                • ECSDA key warning

                                business kept annoying me so I opted for



                                One script to rule them all



                                This is a variant of the script at https://askubuntu.com/a/949731/129227 with Amadu Bah's answer https://serverfault.com/a/858957/162693 in a loop.



                                example call



                                ./sshcheck somedomain site1 site2 site3



                                The script will loop over the names sites and modify the .ssh/config and .ssh/known_hosts file and do ssh-copy-id on request - for the last feature just the let the ssh test calls fail e.g. by hitting enter 3 times on the password request.



                                sshcheck script



                                #!/bin/bash
                                # WF 2017-08-25
                                # check ssh access to bitplan servers

                                #ansi colors
                                #http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
                                blue='33[0;34m'
                                red='33[0;31m'
                                green='33[0;32m' # 'e[1;32m' is too bright for white bg.
                                endColor='33[0m'

                                #
                                # a colored message
                                # params:
                                # 1: l_color - the color of the message
                                # 2: l_msg - the message to display
                                #
                                color_msg()
                                local l_color="$1"
                                local l_msg="$2"
                                echo -e "$l_color$l_msg$endColor"


                                #
                                # error
                                #
                                # show an error message and exit
                                #
                                # params:
                                # 1: l_msg - the message to display
                                error()
                                local l_msg="$1"
                                # use ansi red for error
                                color_msg $red "Error: $l_msg" 1>&2
                                exit 1


                                #
                                # show the usage
                                #
                                usage()
                                echo "usage: $0 domain sites"
                                exit 1


                                #
                                # check known_hosts entry for server
                                #
                                checkknown()
                                local l_server="$1"
                                #echo $l_server
                                local l_sid="$(ssh-keyscan $l_server 2>/dev/null)"
                                #echo $l_sid
                                if (! grep "$l_sid" $sknown) > /dev/null
                                then
                                color_msg $blue "adding $l_server to $sknown"
                                ssh-keyscan $l_server >> $sknown 2>&1
                                fi


                                #
                                # check the given server
                                #
                                checkserver() yes) ssh-copy-id $l_server
                                esac
                                fi


                                #
                                # check all servers
                                #
                                checkservers()
                                me=$(hostname -f)
                                for server in $(echo $*

                                #
                                # check configuration
                                #
                                checkconfig()
                                #https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh
                                if [ -f $sconfig ]
                                then
                                color_msg $green "$sconfig exists"
                                ls -l $sconfig
                                fi


                                sconfig=~/.ssh/config
                                sknown=~/.ssh/known_hosts

                                case $# in
                                0) usage ;;
                                1) usage ;;
                                *)
                                domain=$1
                                shift
                                color_msg $blue "checking ssh configuration for domain $domain sites $*"
                                checkconfig
                                checkservers $*
                                #for server in $(echo $* | sort)
                                ##do
                                # checkknown $server
                                #done
                                ;;
                                esac





                                share|improve this answer















                                This whole



                                • ssh-key-scan

                                • ssh-copy-id

                                • ECSDA key warning

                                business kept annoying me so I opted for



                                One script to rule them all



                                This is a variant of the script at https://askubuntu.com/a/949731/129227 with Amadu Bah's answer https://serverfault.com/a/858957/162693 in a loop.



                                example call



                                ./sshcheck somedomain site1 site2 site3



                                The script will loop over the names sites and modify the .ssh/config and .ssh/known_hosts file and do ssh-copy-id on request - for the last feature just the let the ssh test calls fail e.g. by hitting enter 3 times on the password request.



                                sshcheck script



                                #!/bin/bash
                                # WF 2017-08-25
                                # check ssh access to bitplan servers

                                #ansi colors
                                #http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
                                blue='33[0;34m'
                                red='33[0;31m'
                                green='33[0;32m' # 'e[1;32m' is too bright for white bg.
                                endColor='33[0m'

                                #
                                # a colored message
                                # params:
                                # 1: l_color - the color of the message
                                # 2: l_msg - the message to display
                                #
                                color_msg()
                                local l_color="$1"
                                local l_msg="$2"
                                echo -e "$l_color$l_msg$endColor"


                                #
                                # error
                                #
                                # show an error message and exit
                                #
                                # params:
                                # 1: l_msg - the message to display
                                error()
                                local l_msg="$1"
                                # use ansi red for error
                                color_msg $red "Error: $l_msg" 1>&2
                                exit 1


                                #
                                # show the usage
                                #
                                usage()
                                echo "usage: $0 domain sites"
                                exit 1


                                #
                                # check known_hosts entry for server
                                #
                                checkknown()
                                local l_server="$1"
                                #echo $l_server
                                local l_sid="$(ssh-keyscan $l_server 2>/dev/null)"
                                #echo $l_sid
                                if (! grep "$l_sid" $sknown) > /dev/null
                                then
                                color_msg $blue "adding $l_server to $sknown"
                                ssh-keyscan $l_server >> $sknown 2>&1
                                fi


                                #
                                # check the given server
                                #
                                checkserver() yes) ssh-copy-id $l_server
                                esac
                                fi


                                #
                                # check all servers
                                #
                                checkservers()
                                me=$(hostname -f)
                                for server in $(echo $*

                                #
                                # check configuration
                                #
                                checkconfig()
                                #https://askubuntu.com/questions/87449/how-to-disable-strict-host-key-checking-in-ssh
                                if [ -f $sconfig ]
                                then
                                color_msg $green "$sconfig exists"
                                ls -l $sconfig
                                fi


                                sconfig=~/.ssh/config
                                sknown=~/.ssh/known_hosts

                                case $# in
                                0) usage ;;
                                1) usage ;;
                                *)
                                domain=$1
                                shift
                                color_msg $blue "checking ssh configuration for domain $domain sites $*"
                                checkconfig
                                checkservers $*
                                #for server in $(echo $* | sort)
                                ##do
                                # checkknown $server
                                #done
                                ;;
                                esac






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 25 '17 at 15:39

























                                answered Aug 25 '17 at 13:16









                                Wolfgang FahlWolfgang Fahl

                                2721311




                                2721311





















                                    3














                                    How are you building these machines? can you run a dns update script? can you join an IPA Domain?



                                    FreeIPA does this automatically, but essentially all you need is SSHFP dns records and DNSSEC on your zone (freeipa provides as configurable options (dnssec disabled by default)).



                                    You can get the existing SSHFP records from your host by running.



                                    ssh-keygen -r jersey.jacobdevans.com




                                    jersey.jacobdevans.com IN SSHFP 1 1 4d8589de6b1a48e148d8fc9fbb967f1b29f53ebc jersey.jacobdevans.com IN SSHFP 1 2 6503272a11ba6d7fec2518c02dfed88f3d455ac7786ee5dbd72df63307209d55
                                    jersey.jacobdevans.com IN SSHFP 3 1 5a7a1e8ab8f25b86b63c377b303659289b895736 > jersey.jacobdevans.com IN SSHFP 3 2 1f50f790117dfedd329dbcf622a7d47551e12ff5913902c66a7da28e47de4f4b




                                    then once published, you'd add VerifyHostKeyDNS yes to your ssh_config or ~/.ssh/config



                                    If/When google decides to flip on DNSSEC, you could ssh in without a hostkey prompt.



                                    ssh jersey.jacobdevans.com



                                    BUT my domain is not signed yet, so for now you'd see....




                                    debug1: Server host key: ecdsa-sha2-nistp256 SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s



                                    debug1: found 4 insecure fingerprints in DNS



                                    debug1: matching host key fingerprint



                                    found in DNS The authenticity of host 'jersey.jacobdevans.com (2605:6400:10:434::10)' can't be established. ECDSA key fingerprint is
                                    SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s. Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? no







                                    share|improve this answer





























                                      3














                                      How are you building these machines? can you run a dns update script? can you join an IPA Domain?



                                      FreeIPA does this automatically, but essentially all you need is SSHFP dns records and DNSSEC on your zone (freeipa provides as configurable options (dnssec disabled by default)).



                                      You can get the existing SSHFP records from your host by running.



                                      ssh-keygen -r jersey.jacobdevans.com




                                      jersey.jacobdevans.com IN SSHFP 1 1 4d8589de6b1a48e148d8fc9fbb967f1b29f53ebc jersey.jacobdevans.com IN SSHFP 1 2 6503272a11ba6d7fec2518c02dfed88f3d455ac7786ee5dbd72df63307209d55
                                      jersey.jacobdevans.com IN SSHFP 3 1 5a7a1e8ab8f25b86b63c377b303659289b895736 > jersey.jacobdevans.com IN SSHFP 3 2 1f50f790117dfedd329dbcf622a7d47551e12ff5913902c66a7da28e47de4f4b




                                      then once published, you'd add VerifyHostKeyDNS yes to your ssh_config or ~/.ssh/config



                                      If/When google decides to flip on DNSSEC, you could ssh in without a hostkey prompt.



                                      ssh jersey.jacobdevans.com



                                      BUT my domain is not signed yet, so for now you'd see....




                                      debug1: Server host key: ecdsa-sha2-nistp256 SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s



                                      debug1: found 4 insecure fingerprints in DNS



                                      debug1: matching host key fingerprint



                                      found in DNS The authenticity of host 'jersey.jacobdevans.com (2605:6400:10:434::10)' can't be established. ECDSA key fingerprint is
                                      SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s. Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? no







                                      share|improve this answer



























                                        3












                                        3








                                        3







                                        How are you building these machines? can you run a dns update script? can you join an IPA Domain?



                                        FreeIPA does this automatically, but essentially all you need is SSHFP dns records and DNSSEC on your zone (freeipa provides as configurable options (dnssec disabled by default)).



                                        You can get the existing SSHFP records from your host by running.



                                        ssh-keygen -r jersey.jacobdevans.com




                                        jersey.jacobdevans.com IN SSHFP 1 1 4d8589de6b1a48e148d8fc9fbb967f1b29f53ebc jersey.jacobdevans.com IN SSHFP 1 2 6503272a11ba6d7fec2518c02dfed88f3d455ac7786ee5dbd72df63307209d55
                                        jersey.jacobdevans.com IN SSHFP 3 1 5a7a1e8ab8f25b86b63c377b303659289b895736 > jersey.jacobdevans.com IN SSHFP 3 2 1f50f790117dfedd329dbcf622a7d47551e12ff5913902c66a7da28e47de4f4b




                                        then once published, you'd add VerifyHostKeyDNS yes to your ssh_config or ~/.ssh/config



                                        If/When google decides to flip on DNSSEC, you could ssh in without a hostkey prompt.



                                        ssh jersey.jacobdevans.com



                                        BUT my domain is not signed yet, so for now you'd see....




                                        debug1: Server host key: ecdsa-sha2-nistp256 SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s



                                        debug1: found 4 insecure fingerprints in DNS



                                        debug1: matching host key fingerprint



                                        found in DNS The authenticity of host 'jersey.jacobdevans.com (2605:6400:10:434::10)' can't be established. ECDSA key fingerprint is
                                        SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s. Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? no







                                        share|improve this answer















                                        How are you building these machines? can you run a dns update script? can you join an IPA Domain?



                                        FreeIPA does this automatically, but essentially all you need is SSHFP dns records and DNSSEC on your zone (freeipa provides as configurable options (dnssec disabled by default)).



                                        You can get the existing SSHFP records from your host by running.



                                        ssh-keygen -r jersey.jacobdevans.com




                                        jersey.jacobdevans.com IN SSHFP 1 1 4d8589de6b1a48e148d8fc9fbb967f1b29f53ebc jersey.jacobdevans.com IN SSHFP 1 2 6503272a11ba6d7fec2518c02dfed88f3d455ac7786ee5dbd72df63307209d55
                                        jersey.jacobdevans.com IN SSHFP 3 1 5a7a1e8ab8f25b86b63c377b303659289b895736 > jersey.jacobdevans.com IN SSHFP 3 2 1f50f790117dfedd329dbcf622a7d47551e12ff5913902c66a7da28e47de4f4b




                                        then once published, you'd add VerifyHostKeyDNS yes to your ssh_config or ~/.ssh/config



                                        If/When google decides to flip on DNSSEC, you could ssh in without a hostkey prompt.



                                        ssh jersey.jacobdevans.com



                                        BUT my domain is not signed yet, so for now you'd see....




                                        debug1: Server host key: ecdsa-sha2-nistp256 SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s



                                        debug1: found 4 insecure fingerprints in DNS



                                        debug1: matching host key fingerprint



                                        found in DNS The authenticity of host 'jersey.jacobdevans.com (2605:6400:10:434::10)' can't be established. ECDSA key fingerprint is
                                        SHA256:H1D3kBF9/t0ynbz2IqfUdVHhL/WROQLGan2ijkfeT0s. Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? no








                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Aug 28 '17 at 12:41

























                                        answered Oct 5 '16 at 22:07









                                        Jacob EvansJacob Evans

                                        5,53321337




                                        5,53321337





















                                            1














                                            Here is how to do a collection of hosts



                                            define a collection of hosts



                                            ssh_hosts:
                                            - server1.domain.com
                                            - server2.domain.com
                                            - server3.domain.com
                                            - server4.domain.com
                                            - server5.domain.com
                                            - server6.domain.com
                                            - server7.domain.com
                                            - server8.domain.com
                                            - server9.domain.com


                                            Then define two tasks to add the keys to known hosts:



                                            - command: "ssh-keyscan item"
                                            register: known_host_keys
                                            with_items: "ssh_hosts"
                                            tags:
                                            - "ssh"

                                            - name: Add ssh keys to know hosts
                                            known_hosts:
                                            name: "item.item"
                                            key: "item.stdout"
                                            path: ~/.ssh/known_hosts
                                            with_items: "known_host_keys.results"





                                            share|improve this answer



























                                              1














                                              Here is how to do a collection of hosts



                                              define a collection of hosts



                                              ssh_hosts:
                                              - server1.domain.com
                                              - server2.domain.com
                                              - server3.domain.com
                                              - server4.domain.com
                                              - server5.domain.com
                                              - server6.domain.com
                                              - server7.domain.com
                                              - server8.domain.com
                                              - server9.domain.com


                                              Then define two tasks to add the keys to known hosts:



                                              - command: "ssh-keyscan item"
                                              register: known_host_keys
                                              with_items: "ssh_hosts"
                                              tags:
                                              - "ssh"

                                              - name: Add ssh keys to know hosts
                                              known_hosts:
                                              name: "item.item"
                                              key: "item.stdout"
                                              path: ~/.ssh/known_hosts
                                              with_items: "known_host_keys.results"





                                              share|improve this answer

























                                                1












                                                1








                                                1







                                                Here is how to do a collection of hosts



                                                define a collection of hosts



                                                ssh_hosts:
                                                - server1.domain.com
                                                - server2.domain.com
                                                - server3.domain.com
                                                - server4.domain.com
                                                - server5.domain.com
                                                - server6.domain.com
                                                - server7.domain.com
                                                - server8.domain.com
                                                - server9.domain.com


                                                Then define two tasks to add the keys to known hosts:



                                                - command: "ssh-keyscan item"
                                                register: known_host_keys
                                                with_items: "ssh_hosts"
                                                tags:
                                                - "ssh"

                                                - name: Add ssh keys to know hosts
                                                known_hosts:
                                                name: "item.item"
                                                key: "item.stdout"
                                                path: ~/.ssh/known_hosts
                                                with_items: "known_host_keys.results"





                                                share|improve this answer













                                                Here is how to do a collection of hosts



                                                define a collection of hosts



                                                ssh_hosts:
                                                - server1.domain.com
                                                - server2.domain.com
                                                - server3.domain.com
                                                - server4.domain.com
                                                - server5.domain.com
                                                - server6.domain.com
                                                - server7.domain.com
                                                - server8.domain.com
                                                - server9.domain.com


                                                Then define two tasks to add the keys to known hosts:



                                                - command: "ssh-keyscan item"
                                                register: known_host_keys
                                                with_items: "ssh_hosts"
                                                tags:
                                                - "ssh"

                                                - name: Add ssh keys to know hosts
                                                known_hosts:
                                                name: "item.item"
                                                key: "item.stdout"
                                                path: ~/.ssh/known_hosts
                                                with_items: "known_host_keys.results"






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jan 23 '18 at 10:51









                                                Vackar AfzalVackar Afzal

                                                111




                                                111



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Server Fault!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f132970%2fcan-i-automatically-add-a-new-host-to-known-hosts%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                                                    Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                                                    Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020