I use interactive bash shell over TCP network, but can't figure out how to send CTRL+c sequence to the remote bash.

I first run netcat instance (this is where I interact with remote bash):

nc -nvlp 8000

Then, from the remote I run (for simplicity, I use localhost so you can try it out locally in another terminal):

bash -i >& /dev/tcp/localhost/8000 0>&1

Now, in the netcat terminal the interactive bash appeared and I can send commands to it, which get executed and the result is shown.

What I didn't figure out yet, is how to propagate CTRL+c sequence to the remote bash and ignore it within the netcat process.

Here is what I've tried so far:

nc -nvlp 8000 & trap "printf '\003' >/proc/$!/fd/0" INT; fg; trap 0 INT

This starts netcat in the background, sets up trap, which prints end-of-file sequence (0x03) to the stdin of the netcat if SIGINT is received.

Then, using the fg command, the netcat process is brought to the foreground so that the interactive session can begin. Executing commands works just fine, but when I use CTRL+c sequence, netcat dies with 130 return code, printing nothing in either the netcat, nor the bash terminal.

The final trap resets the SIGINT handler.

The bash process ends with 0 return code, indicating success.

Any ideas, how this could be done?

  • 4
    You cannot do that. Instead of netcat or /dev/tcp you'll have to use something that allocates a pty on the remote side and run bash in it. By the time you got all that, you've reinvented ssh ;-) May 2 '19 at 12:08
  • 3
    The shell (or in general any program which reads the terminal in "cooked" mode) never actually reads a Control-C character; what happens is that the terminal driver sees the Control-C and sends a signal to the shell. That's why @UncleBilly said that you need to allocate a pseudoterminal...
    – AlexP
    May 2 '19 at 12:43

I'm not sure if this is what you were looking for, but you can background the netcat process (hit CTRL+Z), type stty raw -echo and then resume the process. Now it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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