I have left a script running on a remote machine from when I was locally working at it. I can connect over SSH to the machine as the same user and see the script running in ps
.
$ ps aux | grep ipcheck
myuser 18386 0.0 0.0 18460 3476 pts/0 S+ Dec14 1:11 /bin/bash ./ipchecker.sh
It is simply outputting to stdout on a local session (I ran ./ipchecker.sh
form a local terminal window, no redirection, no use of screen
etc).
Is there anyway from an SSH session I can view the output of this running command (without stopping it)?
So far the best I have found is to use strace -p 18386
but I get hordes of text flying up the screen, its far too detailed. I can stop strace
and then sift through the output and find the text bring printed to stdout but its very long and confusing, and obviously whilst it's stopped I might miss something. I would like to find a way to see the script output live as if I was working locally.
Can anyone improve on this? The obvious answer is to restart the script with redirection or in a screen
session etc, this isn't a mission critical script so I could do that. Rather though, I see this as a fun learning exercise.
Best Answer
If all you want to do is spy on the existing process, you can use
strace -p1234 -s9999 -e write
where 1234 is the process ID. (-s9999
avoids having strings truncated to 32 characters, andwrite
the system call that produces output.) If you want to view only data written on a particular file descriptor, you can use something likestrace -p1234 -e trace= -e write=3
to see only data written to file descriptor 3 (-e trace=
prevents the system calls from being loged). That won't give you output that's already been produced.If the output is scrolling by too fast, you can pipe it into a pager such as
less
, or send it to a file withstrace -o trace.log …
.With many programs, you can divert subsequent output with a ptrace hack, either to your current terminal or to a new screen session. See How can I disown a running process and associate it to a new screen shell? and other linked threads.
Note that depending on how your system is set up, you may need to run all these
strace
commands as root even if the process is running under your user with no extra privileges. (If the process is running as a different user or is setuid or setgid, you will need to runstrace
as root.) Most distributions only allow a process to trace its children (this provides a moderate security benefit — it prevents some direct malware injection, but doesn't prevent indirect injection by modifying files). This is controlled by thekernel.yama.ptrace_scome
sysctl.