Thursday, June 7, 2012

Issues while Executing ssh command from within Bash Script



I was trying to execute ssh command from bash script which will: 
1. Connect to the Host using ssh. 
2.  Execute the date command on it.
3.  Print the output of step 2 on screen. 
So basically I have several servers running on Amazon's EC2 and I want to actually see what's the date/time on all those servers for the reasons that I've seen some time drift on Amazon Instances. I have set up password less entry to remote host and also added host key to remote host.
Here is the code that I'm executing: 
inputfile="myfile.csv"
OLDIFS="$IFS"
IFS=","
while read IP; do
        echo "Instance $IP Date/Time is:" `ssh ubuntu@$IP date`
done < "$inputfile"
The problem is: When I execute this script it returns the date time for a few servers like sometimes 1, sometimes 2 or 4 and so on and then exits. 
After having spent hours on this problem finally I figured that ssh was consuming stdin. After adding a -n option to ssh all worked great. 
So here is how I should have actually used it: 
        echo "Instance $IP Date/Time is:" `ssh -n ubuntu@$IP date`
Easy.. Isn't It?


No comments:

Post a Comment