Ssh – Submitting “ps” across multiple servers, output going to one text file

psscriptingssh

I'm trying to build a script that'll output all defunct processes across 66 redhat boxes to a single text file. I understand the principles of doing this on one box, but I'm not sure how to shoehorn that process into something that'll run on one box, but query several boxes.

So, I've found this little script:

for host in $(cat hosts.txt); do ssh "$host" "$command" >"output.$host"; done

I understand that I could essentially submit ps -ef | grep "defunct" as the $command, but I think any output file I create will be dropped onto the host it's running on.

I need to make this run from one box, storing the output on that one box, but containing the information for the other 65 boxes?

I believe we have passwordless ssh in place. My knowledge of Unix is sort of intermediate, I know bits of it because I'm using SAS.

Best Answer

The redirection happens on the calling machine, not on the remote machine, so the result file will be local. Also, the grep does not need to run remotely:

while read -r host; do
    ssh "$host" ps -ef | grep "defunct" >"output.$host"
done <hosts.txt

This executes ps -ef on each host and grep will extract the defunct lines of output. The grep will run locally, not remotely. The result file, likewise, is created locally.

If you want a single output file:

while read -r host; do
    ssh "$host" ps -ef | grep "defunct"
done <hosts.txt >output.txt

Or even (for a single invocation of grep)

while read -r host; do
    ssh "$host" ps -ef 
done <hosts.txt | grep "defunct" >output.txt
Related Question