正则表达式删除和保留行

I'm looking to use the following regex line to remove malicious code from my site;

find -type f -name \*.php -exec sed -i 's/.*eval(base64_decode(\"CmVycm.*/<?php/g' {} \;

This will preserve <?php which I want but I noticed that many of the injections are throughout php files on multiple lines, meaning not just the very first <?php So is it possible to do an if do otherwise statement where if its on line 1 of a php file preserve the php tag otherwise remove the entire line if its anywhere else?

dongxun2903
dongxun2903 备份失败..:(
大约 7 年之前 回复
douyu7210
douyu7210 只需在攻击发生之前恢复站点代码的备份。你有备份,对吧?
大约 7 年之前 回复
dpfz27768
dpfz27768 不,它以<?phpeval(base64......等)开头,但请注意我有保留php的语法
大约 7 年之前 回复
doufei4418
doufei4418 恶意代码是否以特定字符串开头?它总是以eval开头吗?
大约 7 年之前 回复

2个回答

Instead of saying:

sed -i 's/.*eval(base64_decode(\"CmVycm.*/<?php/g'

say:

sed -i 's/eval[(]base64_decode[(]["]CmVycm.*//g'

This would preserve the <?php tag and also remove the malicious code from lines where the tag doesn't exist!

EDIT: As commented by Birei, you can say:

sed -i -e '1 s/.*eval[(]base64_decode[(]["]CmVycm.*/<?php/g' -e '2,$ s/.*eval[(]base64_decode[(]["]CmVycm.*//g'
douwei9973
douwei9973 BTW Birei的工作时间就像一个魅力! 那很完美!!
大约 7 年之前 回复
dowjgrm6787
dowjgrm6787 正确的dave但浮动<?php不会结束,所以它会抛出错误
大约 7 年之前 回复
douyi3760
douyi3760 您不必担心删除PHP标记,您只需删除实际的恶意代码行,留下浮动<?php?>不会破坏任何内容。
大约 7 年之前 回复
dongzhen4180
dongzhen4180 sed可以区分如何将替换命令应用于不同的行。 第一行使用1 s / ...,其余使用2,$ s / ....
大约 7 年之前 回复
dtvnbe1428
dtvnbe1428 不,我不认为你理解。 所有代码实例都存在php标记。 我希望它删除php标签EXCEPT如果它的第一行,即php文件中的行号1。 您提供的删除工作用于保留php标记,但它也保留了其他实例,这些实例也不在第1行
大约 7 年之前 回复

The response from devnull isnt accepted, so here's mine

If the malicious code takes one line, you can easily do :

sed -i "/eval(base64_decode(/d" filename

which will delete the all line.

if you worry about the first <?php

sed -i -e "/<?php/! {1 s/^/<?php /}" filename

It will add a <?php tag if it does not exist at the first line. How does it work ?

/<?php/! will match lines without <?php in it.

{1 s/^/<?php /} In the first line, add <?php at the beginning

More ?

If the code takes 2 lines :

<?php
exec(base64_decode() ... ?>

sed -i '/<?php/{N;/exec(base64_decode/d;}' filename

If a line matches <?php and the next line matches exec(base64_decode, delete both lines.

N; is for loading the next line in the current buffer. d; delete the current buffer ( = both lines )

If the code takes 3 lines :

<?php
exec(base64_decode() ...
?> 

sed -i '/<?php/{N;/exec(base64_decode/{N;d;};}' filename

Idem, but load the third line before deleting (N;d;)

Not enough?

Paste a full example of the string injected.

Hope this help, cheers

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问