Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*nix: Performing nested -exec with find command

I'm trying do the following thing: Hunt down all 777 directories, and then within those directories, hunt down those php files which contain the string "mail(". My goal is to make this part of a cron-job which runs every night and finds all of the php files which contain mail functions that may have been inserted surreptitiously onto our server. So, I've written this command:

find -type d -perm 777 -exec find {} -name "*.php" \; -exec grep "mail(" {} \;

Which (is supposed to):

1: find the folders with 777 privileges

2: for each such folder, find all php files contained therein

3: for each such file, perform a grep to find the string "mail("

However, it doesn't appear to be working. What it is doing is giving me a list of php files in 777-privileged directories, but it's not performing the grep. I've looked at some SO postings like this:

find -exec with multiple commands

Which lead me to believe that nesting of -exec is possible. Is there anything obvious I'm missing? Thanks in advance for your time!

like image 629
CodeOwl Avatar asked Apr 08 '14 17:04

CodeOwl


2 Answers

You can't nest find -exec, but you can nest sh which in turns calls find -exec. With GNU find, you also have to rewrite the {} in the inner find so that the outer find won't replace it:

find . -type d -perm 777 \
  -exec sh -c 'find "$1" -name "*.php" -exec grep "mail(" {""} \;' _ {} \;

This is the most direct answer to your question. There are multiple ways of simplifying it:

find . -type d -perm 777 \
  -exec find {} -name '*.php' -print0 \; | xargs -0 grep -H 'mail(' 

And an even simpler 90% version would just use grep to recurse:

find . -type d -perm 777 -exec grep -HR 'mail(' \; | grep '\.php'
like image 56
that other guy Avatar answered Oct 19 '22 08:10

that other guy


Try this

find somewhere -type d -perm 777 -execdir grep mail *.php
like image 27
Mark Setchell Avatar answered Oct 19 '22 06:10

Mark Setchell