husvar husvar - 4 months ago 11
Linux Question

Expect - Interrupt program - Ctrl+C

I am running the following script to start a capture on a remote server and download the file afterwards. Currently I have to pause it with Ctrl+C and manually exit.

How can I replace the interact and define a trigger to kill the tcpdump or catch the Ctrl+C and pass it inside the remote server?

spawn ssh "$user_ssh\@$ssh_server"

expect {
"*password" { send "$pass\n"; exp_continue}
"root\@*" { }
timeout { puts "time out expecting password or bash"; exit 1 }

send "sudo tcpdump -i $intf -s0 -w $file -v\n";

spawn scp "$user_ssh\@$ssh_server:$file" .

expect "password:"
send "$pass_ssh\n";
expect "100\%"


To send a Ctrl+C, do:

send \x03

To handle an incoming Ctrl+C, do:

trap {your handler script here} SIGINT

You might want to make the handler script (which can be a multi-line thing) send the signal on to the inner process…

trap {
    send \x03
    send_user "You pressed Ctrl+C\n"

But take care! When the user presses Ctrl+C in a text-mode program (in most GUIs, it's a copy action) they are usually expecting it to go away pretty soon, so you should take care to ensure that you don't spend too long after the signal arrives cleaning everything up.