0

I want to ssh to an ip from my bash script and if it asks me to add the public key to the known_hosts file, I want to print a message and exit the script. Also, I don't want to check my known_hosts file because I'm using IDM so the key won't be in known_hosts. I tried this as a quick test but it seems ssh takes over because it's excepting input:

    #!/bin/bash

if ssh localhost | grep -q 'authenticity'; then
   echo "matched"
fi

This is the output I currently get:

[root@host ~]# sh test.sh
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:Nw91ZidjeQLA2/pEGoLpk1lRxk22arS9/xQNTU6gck8.
ECDSA key fingerprint is MD5:d7:f0:66:9c:93:2b:2d:64:34:06:ad:c4:1d:8c:c2:a2.
Are you sure you want to continue connecting (yes/no)?

What I want is if that happen is answer "no" to the above, print "ssh key problem" and exit the script. If that isn't possible, maybe I can answer yes to the above then have the script check known_hosts and error if it's in there?

Bill
  • 123
  • 1
  • 7

1 Answers1

0

You can avoid ssh asking for these things with ssh -o BatchMode=yes yourhost

You'll then find -- and you can already see from your output -- that grep doesn't apply for error messages (see this post about that).

If you want to check for a successful login, you can consider doing:

if ssh -o BatchMode=yes your.host.name true
then
  echo "Successful login"
fi

If you specifically want to check for host key verification:

if LC_ALL=C ssh -o BatchMode=yes your.host.name true 2>&1 | grep -q "Host key verification failed"
then
  echo "Invalid host key"
fi

The 2>&1 makes sure you grep error messages, and LC_ALL=C ensures you get the default English error messages regardless of the user's current language setting.

that other guy
  • 116,971
  • 11
  • 170
  • 194