Ssh script to validate ssh connection to multiple serves with status

Hi,

I want to validate ssh connection one after one for multiple servers..... password less keys already setup but now i want to validate if ssh is working fine or not...

I have .sh script like below and i have servers.txt contains all the list of servers

#/bin/bash
for host in $(cat servers.txt); do
        ssh "$host" "$HOSTNAME" > "test.log";
done

its coming as error below...

./ssh.sh: line 5: syntax error near unexpected token `do'
./ssh.sh: line 5: `do ssh "$host" "$HOSTNAME" > "output.$host";'

---------- Post updated at 06:25 PM ---------- Previous update was at 06:13 PM ----------

I don;t have knowledge on scripting much... so just checking if anyone come across same and have code ..

I do not see a syntax error, but you should correct the shebang (1st line) to

#!/bin/bash

Maybe you are on Solaris and failing to run /bin/bash falls back to /bin/sh that does not understand $( )
There is a second problem,
> "test.log"
overwrites the file each time.
Either change to
>> "test.log"
Or move it to the "done" as follows

...
done > "test.log"

that is more efficient because it opens+creates the file once (when the loop starts).
Or

...
done >> "test.log"

That opens+appends it once.

Welcome to the forum.

That error message for line 5 doesn't match your posted code that has four lines only, "test.log" is not "output.$host", and are you sure what the HOSTNAME variable means? So please post the entire code along with a few lines of servers.txt

Depending how many you are poking, you might consider these adjustments too:-

#!/bin/bash
for host in $(cat servers.txt)
do
        ssh -q -o ConnectTimeout=3 "$host" "hostname"
done > test.log

The blue -q is to suppress some of the normal output to keep your log file a little clearer, however the log file will probably still collect anything that is displaed by the server login process e.g. from /etc/profile or ~/.bashrc

I've added the green to speed up the timeout if the server does not respond. You might want to adjust it depending on what your network will allow.

The red hostname is a command to run on the server you are connecting to. You have $HOSTNAME which may be undefined or set to anything in the shell's environment prior to this script.

What output do you actually want? Is it a list of hosts you could not connect to? If you can open the IP connection, but if fails to sign in how would you handle that? You script would probably just hang. Other conditions may cause your script to carry on to the next host immediately, e.g. the server's public key is different and you get an alert about a possible man-in-the-middle attack. The ssh exits with a non-zero return code, but you don't check. Perhaps you just want a list of successes to then target those that don't let you connect. Knowing the goal would be useful for us.

Robin