Ssh – Unable to redirect STDOUT in a remote screen session via SSH

bashgnu-screenssh

I would like to execute a long-running command via SSH/screen and have the output redirected to a file. I'm able to run the command fine (similar to this question), but the output never shows up.

Here is my current command:

ssh user@host screen -dm "ping -c 20 -i 5 localhost > /tmp/ping.out"

On the remote host I can see the session:

> screen -ls
There is a screen on:
        4530..com001     (Detached)
1 Socket in /var/run/screen/S-root.

And attach to view the live output, which terminates as expected with the ping command completes:

PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.060 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.071 ms
..

Everything does just what I need except the file redirect: ssh on the local host immediately disconnects, the command is running live in a screen session on the remote host (I can connect to the screen session and see my ping running), and the screen session terminates as soon as the ping command completes. The /tmp/ping.out file even gets created on the remote host! But the display stays in the screen session rather than getting redirected to the file.

What am I missing here?

(BTW, the ping is just for testing. Eventually I would like to park a 1 – 2 minute tcpdump and collect the output in the background for troubleshooting).

Best Answer

Screen 'output' isn't exactly what you expect as it is designed as a multiplexor. Command you are looking for is:

ssh user@host screen -d -m "sh -c 'ping -c 20 -i 5 localhost > /tmp/ping.out'"

This command will spawn a new shell & work as intended.