user
user

Reputation: 77

Redirect stdout to a running process

I know how to redirect stdout to a file, but is it possible to redirect stdout to a process (linux environment)?

For example, if I move an active SSH session to the background via "~^Z", is there a way to then start another program on my local host and redirect its stdout to the SSH session?

Thanks!

Upvotes: 4

Views: 1645

Answers (1)

jedwards
jedwards

Reputation: 30200

Sometimes a trick like

echo "something" > /proc/pid-of-process/fd/0

works, but if they're linked to pseudoterminals, it won't.

So, here's one way to do what you want.

  1. ** Configure your SSH connection to use certificates / passwordless login.
  2. Create a named pipe (eg mkfifo mypipe)
  3. Use tail to read from the pipe and pass that to the SSH process, eg:

    tail -f mypipe | ssh -t -t [email protected]

  4. Send whatever you want to go into the ssh session into the named pipe, eg:

    echo "ls -l" > mypipe

    So if you need to pipe stuff from another program, you'd just do

    ./my-program > /path/to/mypipe

  5. You're done.

Some notes:

  1. ** is optional, but if you don't, you will have to type your password on the terminal you start the SSH session on, you can't pass it through the pipe. In fact, if you try, it will just appear as plaintext passed through the pipe once the SSH connection completes.
  2. Your SSH session is now only as secure as your named pipe. Just a heads up.
  3. You won't be able to use the SSH session, once you connect, from the originating terminal. You'll have to use the named pipe.
  4. You can always ctrl+c the SSH process in the original terminal to kill it and restore functionality of the terminal.
  5. Any output will appear on the original terminal -- probably obvious but I just wanted to point it out.
  6. The -f option to tail is necessary to prevent the SSH process from receiving an EOF when the pipe is empty. There are other ways to prevent the pipe from closing, but this is the easiest in my opinion.
  7. The -t -t option to ssh forces tty allocation, otherwise it would complain since stdin is being piped in your case.
  8. Lastly, there is almost definitely a better way to do what you want -- you should consider finding it if this is anything serious / long term.

Upvotes: 3

Related Questions