Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

We need a shell script to find and replace a piece of injected code within all index.php files within a /home folder

share|improve this question
3  
Actually what you want is to recover your system from know good backups as you now have no idea what else has been done to your system. –  Iain Feb 18 '11 at 11:06
add comment

2 Answers 2

You can do it with sed. Here's a good tutorial about it. It may be as simple as find /home/user -iname index.php -exec sed -i s/<piece of code to find/<replace with that>/ {} \;

I suggest you to backup before doing that and running some tests to see if it works ok. Remember that the stuff between the / / are regular expressions and depending on its format you may end matching more stuff you need. As I said, test before running this on your 'live' files.

EDIT: fixed the find command, thanks rems

share|improve this answer
1  
I think you will need a " \; " at the end of the previous find command after having used the "exec". So " find /home/user -iname index.php -exec sed -i s/<piece of code to find/<replace with that>/ {} \; ". –  rems Feb 18 '11 at 11:32
1  
Adn if the injected code appears several times on a single line and you want to substitute all of the matches in one line, you will have to add "g" to the "s" command: " find /home/user -iname index.php -exec sed -i s/<piece of code to find/<replace with that>/g {} \; ". –  rems Feb 18 '11 at 11:34
add comment
for file in $(find /home/user -iname index.php)
do
  echo "replacing in file $file ..."
  sed -i 's/<piece of code to find>/<replace with that>/g' $file
done

If you want to TEST it first, you may put it first in a temporary file, check if it's correct, and overwrite the original file afterwards:

for file in $(find /home/user -iname index.php)
do
  echo "reading from $file, writing to $file.tmp ..."
  sed 's/<piece of code to find>/<replace with that>/g' $file > $file.tmp
done

Now go through some of your files and check if the replacement was done correctly. IF everything is ok, then rename the new index.php.tmp files to index.php with

for file in $(find /home/user -iname index.php.tmp)
do
  echo "moving $file.tmp to $file ..."
  mv $file.tmp $file
done

If the code you want to replace has slashes ( "/" ) in it, then you can use another delimiter in the sed substitute command: 's# piece of code to find # replace with this #g'

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.