Prevent wrong user from using shell script for multiple remote servers

Hi,

I am running a shell script from a central server to multiple remote servers using the following code:

application_check()
{
# Linux/UNIX box with ssh key based login
SERVERS=`cat /tmp/server-details`
# SSH User name
USR="user"
# create new file
> /tmp/abc.log
 
# connect each host and pull up user listing
for host in SERVERS
do
echo "--------------------------------" >> /tmp/abc.log
echo "HOST: $host " >> /tmp/abc.log
echo "--------------------------------" >> /tmp/abc.log
 
ssh -q $USR@$host '
       command 1
      command 2
      echo "EOF"
         ' >> /tmp/abc.log
}

Now, when someone runs this script using another user for which the ssh keys are not shared in the remote servers, the script gets stuck initially asking for authentication or password.

 The authenticity of host '10.1.1.1 (10.1.1.1)' can't be established.
RSA key fingerprint is 32:f8:ac:a4:af:ab:dc:3a:02:29:e8:0e:36:2d:06:e4.
Are you sure you want to continue connecting (yes/no)? 

or

 $hosts's password: 

I want to have a check within my script that if it encounters the above two outputs on screen, then it should exit the script by giving an error.

I cannot use expect.

Please suggest a resolution.

Thanks in advance//

Use the following: first check for the existence of the key in the known_hosts file and if it is there then run ssh with publickey as the only authentication option:

if grep "$host" ~/.ssh/known_hosts > /dev/null; then
   ssh -q -o PreferredAuthentications=publickey $USR@$host '
      command 1
      command 2
      echo "EOF"
    ' >> /tmp/abc.log
fi

ssh will exit with an error exit code (!=0) if the publickey authentication is not possible. Your script will not be interrupted.

1 Like

Thanks, The code given by you resolves the issue.