針對 WordPress 站點被注入惡意代碼(如 eval(gzinflate(base64_decode(...)))、混淆變數名、駭客後門)的緊急清理方案。提供兩版腳本:單次掃描版與支援大量檔案的遞歸版,均含自動備份機制。
典型特徵:
<?php if(!isset($GLOBALS["\x61\156\x75\156\x61"])) 十六進制混淆$bssaiikhvn、$jtgibaqypx 等隨機變數名%x5c%x78 URL 編碼字符串拼接$jtgibaqypx=$urvbwkljhb; $jtgibaqypx=(775-654); $bssaiikhvn=$jtgibaqypx-1; ?>$pattern = '@<\?php\s*if\(!isset\(\$GLOBALS\["\\\x61\\\156\\\x75\\\156\\\x61"\]\)\).*\$bssaiikhvn=\$jtgibaqypx-1;\s*\?>@si';
@...@si:s 讓 . 匹配換行,i 忽略大小寫<?php 到結尾特徵代碼的整個惡意區塊<?php
$path = __DIR__;
$bakPath = $path . DIRECTORY_SEPARATOR . basename(__FILE__, '.php');
$fileType = ['php'];
$search = [$pattern]; // 上述正則
$stats = ['all'=>0, 'clean'=>0, 'infected'=>0];
$files = listDir($path, $fileType);
foreach ($files as $file) {
$stats['all']++;
$content = file_get_contents($file);
$clean = preg_replace($search, '', $content);
if (strlen($content) !== strlen($clean)) {
$stats['infected']++;
// 備份
$bakFile = str_replace($path, $bakPath, $file);
@mkdir(dirname($bakFile), 0777, true);
file_put_contents($bakFile, $content);
// 寫入清理後內容
file_put_contents($file, $clean);
} else {
$stats['clean']++;
}
}
echo sprintf('掃描 %d 個檔案,清理 %d 個感染檔案,備份至 %s', $stats['all'], $stats['infected'], $bakPath);
// 遞歸列出目錄下所有 php 檔
function listDir($dir, $exts) {
$res = [];
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($it as $f) {
if ($f->isFile() && in_array(strtolower($f->getExtension()), $exts)) {
$res[] = $f->getPathname();
}
}
return $res;
}
<?php
set_time_limit(0);
ignore_user_abort(true);
$path = __DIR__;
$bakPath = $path . DIRECTORY_SEPARATOR . basename(__FILE__, '.php');
$fileType = ['php'];
$search = [$pattern];
$stats = ['all'=>0, 'fixed'=>0];
replaceUnwantedCode($path);
echo sprintf('完成:掃描 %d,修復 %d,備份 %s', $stats['all'], $stats['fixed'], $bakPath);
function replaceUnwantedCode($dir) {
global $bakPath, $fileType, $search, $stats;
$it = new DirectoryIterator($dir);
foreach ($it as $f) {
if ($f->isDot()) continue;
$path = $f->getPathname();
if ($f->isDir()) {
replaceUnwantedCode($path);
} elseif (in_array(strtolower($f->getExtension()), $fileType)) {
$stats['all']++;
$content = file_get_contents($path);
$clean = preg_replace($search, '', $content);
if (strlen($content) !== strlen($clean)) {
$stats['fixed']++;
$bakFile = str_replace($dir, $bakPath, $path);
@mkdir(dirname($bakFile), 0777, true);
file_put_contents($bakFile, $content);
file_put_contents($path, $clean);
}
}
}
}
wp-content、plugins、themes 子目錄)https://yoursite.com/delUnwantedCode.php 或 CLI 執行 php delAllUnwantedCode.phpwp-config.php、.htaccess、index.php 是否被篡改wp_options、wp_posts、wp_users 可疑內容僅針對**已知特徵**的惡意代碼變體。新型混淆、多態病毒、文件少型後門需人工排查或專業掃描工具(如 maldet、clamav、Wordfence CLI)。