0

I want to run a program on a linux server A. Linux server B can monitor power metric of server A. But in order to get measure for a program running on server A, I need to open the meaurement script on server B at the start of program on server A and end manually it on server B afterwards.

So to summerize, how to ssh into a server to run a program and terminate it afterwards, via script?

JP Zhang
  • 767
  • 1
  • 7
  • 27

1 Answers1

0

A few tricks needed here. 1. I am using sshpass to auto enter a password to a machine over ssh (stored in plain text in the script insecure). 2. I am writing a script in this script that is then executed over ssh 3. I store the pid of the program running on server A in it's /tmp directory

#!/bin/bash
PROGRAM_TO_RUN_ON_SERVER_A="sleep 1000"
PASSWORD_TO_USER_ON_SERVER_A="password"
SERVER_A_USER="user"
SERVER_A_MACHINE_NAME="machine-name"

# Create a local script to run on server A
SCRIPT=/tmp/script.sh
export SSHPASS=${PASSWORD_TO_USER_ON_SERVER_A}
echo '#!/bin/bash' > $SCRIPT
echo "(( ${PROGRAM_TO_RUN_ON_SERVER_A} 0<&- &>/dev/null & echo $! > /tmp/pid.txt) &)" >> $SCRIPT

# Execute script on server A (This also executes your program)
sshpass -e ssh ${SERVER_A_USER}@${SERVER_A_MACHINE_NAME} 'bash -s' < $SCRIPT

# Do server B timing analysis things here
# ...
# ...
# ...

# Kill the program running on server A
sshpass -e ssh ${SERVER_A_USER}@${SERVER_A_MACHINE_NAME} 'cat /tmp/pid.txt | xargs kill -9'

Getting ssh to execute a command in the background on target machine

Lenna
  • 1,220
  • 6
  • 22
  • Thank you for this script. Just checked with Server B. It's embedding system with limited suport for linux comamnds(it uses a peculiar shell called `ash`). It doesn't support `nohup`. Any workaround? – JP Zhang Mar 24 '20 at 02:54
  • https://stackoverflow.com/questions/29704358/how-to-keep-program-running-in-background-in-ash-shell/60824557#60824557 – Lenna Mar 24 '20 at 03:28
  • Somehow I did it using simpe ampersand at the end. – JP Zhang Mar 24 '20 at 03:33