0

I need to ssh into memcached servers and execute ensure connectivity. I am supposed to re-use the same ssh connection and keep executing the commands whose output will be stored in some log. This is supposed to be a scheduled job which runs at some specific intervals.

Code 1 makes multiple ssh connections for each execution.

#!/bin/bash
USERNAME=ec2-user
HOSTS="10.243.107.xx 10.243.124.xx"
KEY=/home/xxx/xxx.pem
SCRIPT="echo stats | nc localhost 11211 | grep cmd_flush"
for HOSTNAME in ${HOSTS} ; do
    ssh -l ${USERNAME} -i ${KEY} ${HOSTNAME} "${SCRIPT}"
done

Code 2 hangs after ssh.

#!/bin/bash
USERNAME=ec2-user
KEY=/home/xxx/xxx.pem
ssh -l ${USERNAME} -i ${KEY} 10.243.xx.xx
while:
do
  echo stats | nc localhost 11211 | grep cmd_flush
  sleep 1
done

Is there any better way of doing this?

6
  • I'm not sure what code 2 is trying to do. Is your intention that it will run the infinite while loop on the remote host? Commented May 27, 2021 at 12:29
  • @Reshma: In the second attempt, you open a remote shell, but don't provide any input for it. I see two approaches: Simulate passing the commands via expect, or put all the individual commands together to one big command and execute that. Commented May 27, 2021 at 12:29
  • @joanis yes, I want to establish connection one time, and then execute the command multiple times...every 1min, every 30min, 1hr, 1 day... Commented May 27, 2021 at 12:39
  • 1
    You can use the control master feature to keep the SSH connection alive between subsequent executions of ssh, so that you don't need to reauthenticate each time. Commented May 27, 2021 at 14:07
  • Take a look at stackoverflow.com/questions/22411932/…. Commented May 27, 2021 at 14:16

1 Answer 1

1

Since you want to have Code 2 run the infinite while loop on the remote host, you can pass that whole thing to the ssh command, after fixing the while statement:

#!/bin/bash
USERNAME=ec2-user
KEY=/home/xxx/xxx.pem
ssh -l ${USERNAME} -i ${KEY} 10.243.xx.xx '
  while true
  do
    echo stats | nc localhost 11211 | grep cmd_flush
    sleep 1
  done
'

I have to warn that I think the whole approach is somewhat fragile, though. Long-standing ssh connections tend to die for various reasons, which don't always mean the connectivity is actually broken. Make sure the parent script that calls this notices dropped ssh connections and tries again. I guess you can put this script in a loop, and maybe log a warning each time the connection is dropped, and log an error if the connection cannot be re-established.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.