1

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

euan
  • 11
  • 1
  • 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. – user9517 Feb 18 '11 at 11:06

2 Answers2

5

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

coredump
  • 12,713
  • 2
  • 36
  • 56
  • 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// {} \; ". – 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//g {} \; ". – rems Feb 18 '11 at 11:34
2
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'

rems
  • 2,260
  • 13
  • 11