Wednesday, February 7, 2024

[SOLVED] pipe timely commands to ssh

Issue

I am trying to pipe commands to an opened SSH session. The commands will be generated by a script, analyzing the results, and sending the next commands in accordance.

I do not want to put all the commands in a script on the remote host, and just run that script, because I am interested also in the status of the SSH process: sending locally the commands allow to "test" whether the SSH connection is alive or not, and get the appropriate return code from the SSH process.

I tried using something along these lines:

$ mkfifo /tpm/commands
$ ssh -t remote </tmp/commands

And from another term:

$ echo "command" >> /tmp/commands

Problem: SSH tells me that no pseudo-tty will be opened for stdin, and closes the connection as soon as "command" terminates.

I tried another approach:

$ ssh -t remote <<EOF 
$(echo "command"; while true; do sleep 10; echo "command"; done)
EOF

But then, nothing is flushed to ssh until EOF is reached (in my case, never).

Do any of you have a solution ?


Solution

Stop closing /tmp/commands before you're done with it. When you close the pipe, ssh stops reading from it.

exec 7> /tmp/commands. # open once
echo foo >&7           # write multiple times
echo bar >&7
exec 7>&-              # close once    

You can additionally use ssh -tt to force ssh to open a tty on the remote.



Answered By - that other guy
Answer Checked By - Willingham (WPSolving Volunteer)