Useful Snippets

Useful Snippets


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

August 2020
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Categories


Cleaning up hacked WordPress spam, content injection and defacement using WP-CLI regex search

Stanislav KhromovStanislav Khromov

This post will show how you can use the build in search-replace function in WP-CLI with regex matching to batch remove harmful content from your WordPress site. This means that you can remove hundreds or thousands of injections in a matter of seconds instead of going through content and dumps manually.

Example of post_content injection:

...
Lorem ipsum dolor sit amet. <script src="https://nameserverdom.tk/assdhdfer" type="text/javascript"></script><script src="https://nameserverdom.tk/assdhdfer" type="text/javascript"> </script>Lorem ipsum dolor sit amet.
...

Go to https://regex101.com/ and figure out a good regex that fits your type of defacement.

For the defacement above, I settled with:

<script.*?tk.*?<\/script>

Now it’s time to run WP-CLI to remove the defacement.

It’s always good to test first with the --dry-run flag, which simulates a run but doesn’t actually do any replacements.

wp search-replace '<script.*?tk.*?<\/script>' '' --all-tables --dry-run --report-changed-only --precise --regex --regex-delimiter='/'

WP-CLI will tell you how many replacements are expected. When you feel like you’ve got a good result, remove --dry-run and you get the final command to run:

wp search-replace '<script.*?tk.*?<\/script>' '' --all-tables --report-changed-only --precise --regex --regex-delimiter='/'

Related

Using Regex with WP CLI to Search & Replace in the Database

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.