tags:

views:

2811

answers:

4

In a bash script I execute a command on a remote machine through ssh. If user breaks the script by pressing Ctrl+C it only stops the script - not even ssh client. Moreover even if I kill ssh client the remote command is still running...

How can make bash to kill local ssh client and remote command invocation on Crtl+c?

A simple script:

#/bin/bash
ssh -n -x root@db-host 'mysqldump db' -r file.sql
A: 
trap "some_command" SIGINT

will execute some_command locally when you press Ctrl+C . help trap will tell you about its other options.

Regarding the ssh issue, i don't know much about ssh. Maybe you can make it call ssh -n -x root@db-host 'killall mysqldump' instead of some_command to kill the remote command?

Johannes Schaub - litb
+2  A: 

Do you know what the options you're passing to ssh do? I'm guessing not. The -n option redirects input from /dev/null, so the process you're running on the remote host probably isn't seeing SIGINT from Ctrl-C.

Now, let's talk about how bad an idea it is to allow remote root logins:

It's a really, really bad idea. Have a look at HOWTO: set up ssh keys for some suggestions how to securely manage remote process execution over ssh. If you need to run something with privileges remotely you'll probably want a solution that involves a ssh public key with embedded command and a script that runs as root courtesy of sudo.

converter42
+3  A: 

Eventual I found a solution like that:

#/bin/bash
ssh -t -x root@db-host 'mysqldump db' -r file.sql

So - I use '-t' instead of '-n'. Removing '-n', or using different user than root does not help.

tkokoszka
A: 

When your ssh session ends, your shell will get a SIGHUP. (hang-up signal). You need to make sure it sends that on to all processes started from it. For bash, try shopt -s huponexit; your_command. That may not work, because the man page says huponexit only works for interactive shells.

I remember running into this with users running jobs on my cluster, and whether they had to use nohup or not (to get the opposite behaviour of what you want) but I can't find anything in the bash man page about whether child processes ignore SIGHUP by default. Hopefully huponexit will do the trick. (You could put that shopt in your .bashrc, instead of on the command line, I think.)

Your ssh -t should work, though, since when the connection closes, reads from the terminal will get EOF or an error, and that makes most programs exit.

Peter Cordes