I am trying to read a config file contains ip and port numbers.
i want to read each line of the config file and check ssh connection is happening or not.
What happens if you try the following script instead?
#!/bin/sh
set -xv
while read -r hosts port
do
ssh -q -o "BatchMode=yes" -p "$port" "$hosts" "echo 2>&1"
[ $? -eq 0 ] && echo "Connected to ${hosts} for port ${port}" || echo "Connection refused to ${hosts} for port ${port}, Please check"
done < /home/ssh_configfile
For half of your configuration entries you don't need the ssh test as they don't comply to the "dotted quad" notation. And, as already implied by Don Cragun's proposal, the || [[ -n $lines ]] is not necessary because it would be executed only if the read failed anyhow (e.g. at enf of file), terminating the while loop.
What is not working?
We need the output to understand...
also Looking at don's code I cant believe it failed reading a line, to convince yourself, add a counter in the loop as you know what is expected based on the config file given in input
while read -r hosts port
do
ssh -q -o "BatchMode=yes" -p "$port" "$hosts" "echo 2>&1"
[ $? -eq 0 ] && echo "Connected to ${hosts} for port ${port}" || echo "Connection refused to ${hosts} for port ${port}, Please check"
done < /home/ssh_configfile
+ read -r hosts port
+ ssh -q -o BatchMode=yes -p 22 abc@1.2.3.42 'echo 2>&1'
+ '[' 0 -eq 0 ']'
+ echo 'Connected to abc@1.2.3.42 for port 22'
Connected to abc@1.2.3.42 for port 22
+ read -r hosts port
i have multiple server and its reading only 1st ip for rest it is not reading and checking the connection.
If anyone who can be humble and kind enough to guide me on the right direction.
Regards,
Sadique
---------- Post updated at 06:06 AM ---------- Previous update was at 06:01 AM ----------
Thanks Rudic your observation worked for me now with my original code i am able to connect to all the ip with their host and validate the connection.
Also as u suggested i have removed the
It would seem that the ssh inside your loop may be consuming all the other input lines.
Perhaps a small adjustment like this might help:-
exec 99</home/ssh_configfile
while read -u 99 -r host port
do
ssh -q -o "BatchMode=yes" -p "$port" "$hosts" "echo 2>&1"
[ $? -eq 0 ] && echo "Connected to ${hosts} for port ${port}" || echo "Connection refused to ${hosts} for port ${port}, Please check"
done
Does that help? It is forcing the loop to read from a nominated file descriptor leaving ssh to read STDIN if it wishes.
Can you show us the output (with a set -x before this bit) if it is still stuck? Perhaps just a two line input file would suffice to keep the output small.