Siddharthan Asokan Siddharthan Asokan - 3 months ago 13
Node.js Question

Script to SSH to an instance and launch node app.js

I'm trying to ssh to 2 servers one by one and run the following command:

sudo node app.js


Here is my code:

#!/bin/bash
while read line; do
ssh -i "sshtest.pem" ec2-user@$line "sudo node app.js"
done < ips.txt


After sudo node app.js is executed the control doesn't pass over to the next ip in the loop. Can someone point me what I could do to improve this?

Answer

Try exiting after your ssh:

#!/bin/bash
COMMAND="sudo node app.js && exit"
PEM="sshtest.pem"
USER="ec2-user"
IN="ips.txt"

while read LINE; do  
    ssh -i $PEM $USER@$LINE $COMMAND     
done < $IN

If you'd like rather not block, background each ssh:

#!/bin/bash
COMMAND="sudo node app.js && exit"
PEM="sshtest.pem"
USER="ec2-user"
IN="ips.txt"

while read LINE; do  
    ssh -i $PEM $USER@$LINE $COMMAND &
done < $IN

The biggest issue you're going to have is with sudo. Having to elevate privilege will require you to enter a password. This might help you re-design your approach.