#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 自动化木马清理与静态代码脱毒清洗工具 """ import os import shutil BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MALICIOUS_JS_INJECTION = "" MALICIOUS_HTML_INJECTION = '' def remove_malware_directories(): """清理恶意生成的递归目录""" dirs_to_remove = [ os.path.join(BASE_DIR, 'public', 'images', 'images'), os.path.join(BASE_DIR, 'public', 'template', 'template'), ] for d in dirs_to_remove: if os.path.exists(d): print(f"Removing malicious directory: {d}") shutil.rmtree(d, ignore_errors=True) def remove_malware_php_files(): """清理 public 静态目录下的 PHP 木马与后门文件""" search_dirs = [ os.path.join(BASE_DIR, 'public', 'assets'), os.path.join(BASE_DIR, 'public', 'images'), os.path.join(BASE_DIR, 'public', 'template'), ] removed_files = [] for sdir in search_dirs: if not os.path.exists(sdir): continue for root, dirs, files in os.walk(sdir): for f in files: if f.lower().endswith('.php'): fp = os.path.join(root, f) print(f"Deleting backdoor php: {fp}") os.remove(fp) removed_files.append(fp) elif f == '.htaccess' and ('images' in root or 'template' in root): fp = os.path.join(root, f) print(f"Deleting malicious htaccess: {fp}") os.remove(fp) removed_files.append(fp) print(f"Total backdoor files deleted: {len(removed_files)}") def sanitize_infected_files(): """精准清洗所有被注入暗链的 JS 与 HTML 文件""" cleaned_count = 0 ignore_dirs = {'.git', 'runtime', 'tests', '.gemini'} for root, dirs, files in os.walk(BASE_DIR): dirs[:] = [d for d in dirs if d not in ignore_dirs] for f in files: file_path = os.path.join(root, f) try: with open(file_path, 'r', encoding='utf-8', errors='ignore') as fp: content = fp.read() except Exception: continue continue orig_len = len(content) # 1. 替换 JS 注入行 if MALICIOUS_JS_INJECTION in content: # 处理带换行或不带换行 content = content.replace(MALICIOUS_JS_INJECTION + '\n', '') content = content.replace(MALICIOUS_JS_INJECTION + '\r\n', '') content = content.replace(MALICIOUS_JS_INJECTION, '') # 2. 替换 HTML 注入行 if MALICIOUS_HTML_INJECTION in content: content = content.replace(MALICIOUS_HTML_INJECTION + '\n', '') content = content.replace(MALICIOUS_HTML_INJECTION + '\r\n', '') content = content.replace(MALICIOUS_HTML_INJECTION, '') lines = content.splitlines(keepends=True) content = ''.join(filtered_lines) if len(content) != orig_len: with open(file_path, 'w', encoding='utf-8') as fp: fp.write(content) cleaned_count += 1 print(f"Cleaned: {file_path}") print(f"Total files sanitized: {cleaned_count}") if __name__ == '__main__': print("=== 开始执行木马清理 ===") remove_malware_directories() remove_malware_php_files() sanitize_infected_files() print("=== 木马清理完成 ===")