7

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!

2 Answers 2

5

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why the inner {} works only when expressed as {""}?
@UndergroundCoding The outer find find replaces the two character string {} wherever it sees it, but {""} is a four character string it doesn't recognize
1

Try this

find somewhere -type d -perm 777 -execdir grep mail *.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.