This question already has an answer here:

I have the following script called exec.sh which runs a python script remotely on node01:

ssh node01 "python2.7 /home/user/run.py"

If I kill exec.sh using either CTRL+C or kill -9, then the python script that I was running through ssh is still executing on node01.

What I want is to kill the process that I was running on node01 whenever I kill the exec.sh script.

marked as duplicate by l0b0, Archemar, Rui F Ribeiro, meuh, GAD3R Jul 27 '17 at 11:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


That's because the exec.sh is local, and it executes a command on a remote machine. So, if you kill the local process, the remote process still runs.

To achieve what you want, you need the exec.sh to catch the SIGNAL of CTRL+C, and before killing itself to kill the command on the remote host.

function trap_ctrlc ()
# kill the remote process
  ssh user@pass "pkill -9 python"

  exit 2 

# initialise trap to call trap_ctrlc function
# when signal 2 (SIGINT) is received
trap "trap_ctrlc" 2

your script here

Careful: python is very general process to kill. You better save the process ID when you start it, and then specifically kill it by ID

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