16

I have the following command works in my script that adds the host to the known hosts in ssh.

VAR2=$(expect -c '
 spawn ssh -o StrictHostKeyChecking=no '"$REMOTE_HOST_USER@$REMOTE_HOST_IP"'
 expect "*?assword:*"
 send "'"$REMOTE_HOST_PASSWD"'\r"
 expect { 
 "Permission denied, please try again." {
 exit '"$WRONG_PASSWORD"' 
 }
 }
 ')

Works fine, but I need to control before the command if the host is already in known_hosts and not execute command if it is already in known_hosts. How can i check if an host is in known_hosts?

barp
  • 6,489
  • 9
  • 30
  • 37

2 Answers2

44

Try: ssh-keygen -F <hostname>

Will show the known_hosts line(s) if the hostname fingerprint is found and the command returns 0, otherwise nothing is shown and the command returns 1.

Community
  • 1
  • 1
complex857
  • 20,425
  • 6
  • 51
  • 54
  • This doesn't seem to do anything, or even print anything to the screen. Strange. – secondman Mar 25 '13 at 07:24
  • @VinceKronlein, That should happen when no match found for your hostname. Only full matches returned. – complex857 Mar 25 '13 at 07:58
  • Yeah that was my bad. I wasn't using just the hostname ie: google.com, I was trying to look for a key for a git repo using the git host ie: git@google.com ... once I used just the hostname alone it worked great. – secondman Mar 26 '13 at 01:58
  • if you like I trying to find out if there exists the key of SSH server listening to non-standard port (other than 22), use the following command: `ssh-keygen -F "[gerrit.example.com]:29418"` – maoizm Jan 08 '22 at 13:22
3

According to ssh-keygen(1) man page

-F hostname Search for the specified hostname in a known_hosts file, listing any occurrences found. This option is useful to find hashed host names or addresses and may also be used in conjunction with the -H option to print found keys in a hashed format.

hostmaster
  • 1,822
  • 16
  • 17