0

I am writing a script to get the command information of the remote machine usinf while and for loop. PFB the script. But the script ends by giving the single command information only. I have multiple commands in this file (CMDS=$HOMEDIR/cmnd.txt). If I don't use ssh all the commands working fine, but when I use ssh it executes first command only.

#!/bin/bash
HOMEDIR=/home/448130
CMDS=$HOMEDIR/cmnd.txt
while read -r line
do
  for i in $(cat hostname.txt);
  do
    echo "*****************************  $line output begins  ********************************";
    #echo $line
    ssh $i $line
    echo "*****************************  $line output ends  ********************************";
  done
done < $CMDS

Please help me to fix this.

  • Could you please clarify a little more what you actually want to achieve? You may find several methods for running local commands remotely at backreference.org/2011/08/10/… And a pretty similar question: stackoverflow.com/questions/8376166/… – doktor5000 May 20 '15 at 7:48
  • I am trying to fetch some details like uptime, uname, etc from a remote machine over ssh. For this I am calling the commands from a txt file. – user2688372 May 20 '15 at 8:58
  • When i execute the script without ssh locally it gives the output how i am expecting. But when i executes wth ssh command it executes the first command of the input file only. – user2688372 May 20 '15 at 8:59
  • ***************************** uptime output begins ****************************** 14:37:25 up 3 days, 13 min, 3 users, load average: 0.07, 0.18, 0.14 ***************************** uptime output ends ******************************** ***************************** uname output begins ****************************** Linux ***************************** uname output ends ******************************** This kind of output i am expecting – user2688372 May 20 '15 at 9:09
  • I am able to get the output perfectly, when executing the script locally. but when is use "ssh $i $line" it executes first command from the file only and then the loop ends – user2688372 May 20 '15 at 9:11
0

When you run ssh, the standard input is passed to the remote command. The remote command doesn't actually do anything with it, but the local ssh process has no way to know. To avoid this, since you don't want to pass any input to the remote command, redirect the input of ssh to /dev/null.

Don't forget to double quote variable substitutions.

while IFS= read -r line
do
  for i in $(cat hostname.txt);
  do
    echo "*****************************  $line output begins  ********************************";
    #echo $line
    ssh "$i" "$line" </dev/null
    echo "*****************************  $line output ends  ********************************";
  done
done < "$CMDS"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.