The One
The One

Reputation: 2331

Script to check if ssh connection is success

I have 100 servers. From the first server, i want to check if ssh connection from this first server to other servers is OK or not.

If OK, then it would ouput OK, if not, it would output Failed.

I did some setup before with hostname and key pair, so basically i just enter:

ssh name-server 

Then i would know the result.

For example

Failed case:

[centos@tony]$ ssh server1
Last login: Thu Aug  9 17:01:21 2018 from 172.21.11.5
Connection to server1 closed.

OK case:

[centos@tony]$ ssh server1
Last login: Thu Aug  9 17:01:21 2018 from 172.21.11.5

I have a file list.txt include all hostname of all servers.

server1
server2
...

My script not worked:

#!/bin/bash
for i in $(cat /home/centos/list.txt); do
result=`ssh i | grep closed`
if [ -z "$result" ] ; then
  echo "OK"
fi

Upvotes: 1

Views: 9802

Answers (1)

DevSolar
DevSolar

Reputation: 70283

From man ssh:

EXIT STATUS

ssh exits with the exit status of the remote command or with 255 if an error occurred.

So just execute a simple command on the remote server and check for its success. The simplest command imaginable is true (which just returns 0 / success):

#!/bin/bash
for server in $(cat /home/centos/list.txt)
do
  if ssh $server "true"
  then
    echo "Server $server: OK"
  fi
done

Upvotes: 8

Related Questions