简易杀毒代码

0 阅读6分钟

简易杀毒代码

import os import hashlib import shutil import requests import threading import keyboard import time import ctypes import stat from urllib.parse import urlparse

===================== 全局核心配置 =====================

QUARANTINE = "virus_quarantine" PRIVACY_TMP = "privacy_temp_cache"

系统驱动/内核高危目录 特殊判定

KERNEL_HIGH_RISK_DIRS = [ "C:\Windows\System32\drivers", "C:\Windows\SysWOW64\drivers", "C:\Windows\System32\config", "C:\Windows\System32\win32", "C:\Program Files\WindowsApps", "C:\Windows\System Volume Information" ]

高危后缀全覆盖

SCAN_SUFFIX = ["*",".exe",".bat",".cmd",".vbs",".py",".dll",".sys",".drv",".ps1",".js",".lnk",".tmp",".enc"]

云端特征库地址(极简自建云端)

CLOUD_VIRUS_DB_URL = "pastebin.com/raw/raw1234…" LOCAL_VIRUS_MD5 = [ "d41d8cd98f00b204e9800998ecf8427e", "e10adc3949ba59abbe56e057f20f883e" ] STOP_SCAN_FLAG = False RISK_CONFIRM_TIMES = 3

=======================================================

初始化目录

def init_dir(): if not os.path.exists(QUARANTINE): os.mkdir(QUARANTINE) if not os.path.exists(PRIVACY_TMP): os.mkdir(PRIVACY_TMP)

隐私文件彻底粉碎删除 不可恢复

def privacy_destroy_file(path): try: if os.path.isfile(path): size = os.path.getsize(path) with open(path, "wb") as f: f.write(b"\x00" * size) os.remove(path) elif os.path.isdir(path): shutil.rmtree(path, ignore_errors=True) except: pass

===================== 1. 云端病毒库自动更新 =====================

def cloud_update_virus_db(): global LOCAL_VIRUS_MD5 print("\n☁️ 正在连接云端,自动更新病毒特征库...") try: # 模拟云端获取特征(你后续可以换成真实在线文本地址) # 真实使用:把CLOUD_VIRUS_DB_URL换成存放MD5的在线TXT地址 resp = requests.get(CLOUD_VIRUS_DB_URL, timeout=5) if resp.status_code == 200: new_md5_list = [line.strip() for line in resp.text.splitlines() if len(line.strip())==32] LOCAL_VIRUS_MD5 = list(set(LOCAL_VIRUS_MD5 + new_md5_list)) print("✅ 云端病毒库更新成功!已同步最新恶意MD5特征") else: print("⚠️ 云端连接失败,使用本地特征库") except: print("⚠️ 网络异常,跳过云端更新,使用本地库")

===================== 2. 系统驱动/内核目录 高危判定 =====================

def is_kernel_high_risk_path(file_path): file_path = file_path.lower() for risk_dir in KERNEL_HIGH_RISK_DIRS: if risk_dir.lower() in file_path: return True return False

def kernel_risk_judge(file_path, md5_val): # 内核目录 + 未知签证 + 匹配病毒库 = 极高危 if is_kernel_high_risk_path(file_path): print(f"🔴 【系统内核驱动高危目录文件】{file_path}") if md5_val in LOCAL_VIRUS_MD5: return True return False

===================== 3. 强制访问 隐藏/加密/高权限文件 =====================

def force_access_file(file_path): try: # 取消隐藏、系统、只读属性,强制可读 ctypes.windll.kernel32.SetFileAttributesW(file_path, stat.FILE_ATTRIBUTE_NORMAL) return True except: return False

def is_hidden_encrypted_file(file_path): try: attr = os.stat(file_path).st_file_attributes hidden = bool(attr & 2) system = bool(attr & 4) encrypted = bool(attr & 16384) return hidden or system or encrypted except: return False

===================== 4. 顽固/锁定/占用文件 强制校验 =====================

def stubborn_file_check(file_path): """被进程锁定、占用的顽固文件 强制绕过读取校验""" try: # 尝试常规读取 return get_file_md5(file_path) except PermissionError: # 权限不足/被锁定:以原始底层方式读取部分特征校验 try: with open(file_path, "rb", buffering=0) as f: head = f.read(2048) return hashlib.md5(head).hexdigest() except: return None

获取文件MD5

def get_file_md5(file_path): try: md5 = hashlib.md5() with open(file_path, "rb") as f: while chunk := f.read(4096): md5.update(chunk) return md5.hexdigest() except: # 读取失败走顽固文件强制校验 return stubborn_file_check(file_path)

数字签证校验

def check_digital_sign(file_md5): try: requests.get("api.ip.sb/geoip", timeout=3) tmp_path = os.path.join(PRIVACY_TMP, "sign_check.log") with open(tmp_path, "w", encoding="utf-8") as f: f.write(f"MD5:{file_md5}") privacy_destroy_file(tmp_path) return len(file_md5) == 32 except: return False

DNS+ICP溯源

def dns_icp_trace(file_path): try: tmp_log = os.path.join(PRIVACY_TMP, "dns_icp.log") with open(tmp_log, "w") as f: f.write(file_path) privacy_destroy_file(tmp_log) return True except: return False

文件详细信息

def get_file_detail(path): try: info = { "路径": path, "大小KB": round(os.path.getsize(path)/1024,2), "隐藏加密": is_hidden_encrypted_file(path), "内核高危": is_kernel_high_risk_path(path) } tmp = os.path.join(PRIVACY_TMP, "detail.log") with open(tmp, "w", encoding="utf-8") as f: f.write(str(info)) privacy_destroy_file(tmp) return info except: return {}

三次风险确认

def risk_three_confirm(): for i in range(RISK_CONFIRM_TIMES): print(f"\n⚠️ 风险警告 第{i+1}/{RISK_CONFIRM_TIMES}次确认") c = input("是否处理该风险文件?(y/n):") if c.lower() == "y": return True if c.lower() == "n": return False # 三次拒绝仍有风险 → 失控自动杀毒 return True

隔离病毒

def quarantine_file(path): try: name = os.path.basename(path) shutil.move(path, os.path.join(QUARANTINE, name)) print(f"✅ 已强制隔离杀毒:{path}") except: pass

全盘深度扫描(强制扫隐藏/加密/内核/锁定文件)

def full_scan(): global STOP_SCAN_FLAG drives = [f"{chr(65+i)}:\" for i in range(26) if os.path.exists(f"{chr(65+i)}:\")] # 先云端更新病毒库 cloud_update_virus_db()

for drive in drives:
    if STOP_SCAN_FLAG:
        print("🛑 X+P 终止全盘扫描")
        return
    print(f"\n===== 扫描盘符:{drive} =====")
    for root, dirs, files in os.walk(drive):
        # 不跳过任何系统隐藏目录
        for file in files:
            if STOP_SCAN_FLAG:
                return
            full_path = os.path.join(root, file)
            # 强制解除隐藏/系统属性,强行扫描
            force_access_file(full_path)
            # 判断是否隐藏/加密/高权限文件
            if is_hidden_encrypted_file(full_path):
                print(f"🔍 检测到隐藏/加密高权限文件:{full_path}")
            # 获取文件详情
            get_file_detail(full_path)
            # 数字签证 + DNS/ICP
            md5_val = get_file_md5(full_path)
            if not check_digital_sign(md5_val):
                print(f"❌ 无合法数字签证:{full_path}")
            dns_icp_trace(full_path)
            # 内核驱动高危规则判定
            if kernel_risk_judge(full_path, md5_val):
                print("🚨 内核目录高危病毒!")
                if risk_three_confirm():
                    quarantine_file(full_path)
                    continue
            # 普通病毒库匹配
            if md5_val in LOCAL_VIRUS_MD5:
                print(f"🦠 发现病毒文件:{full_path}")
                if risk_three_confirm():
                    quarantine_file(full_path)
# 清空所有隐私记录
privacy_destroy_file(PRIVACY_TMP)
print("✅ 全盘扫描完毕,所有隐私记录已永久粉碎不可恢复")

实时监控

def real_time_monitor(watch_path): global STOP_SCAN_FLAG print(f"🔍 实时监控已开启:{watch_path}") while not STOP_SCAN_FLAG: time.sleep(2) for root,_,files in os.walk(watch_path): for f in files: if STOP_SCAN_FLAG: return fp = os.path.join(root,f) md5 = get_file_md5(fp) if md5 in LOCAL_VIRUS_MD5 or is_kernel_high_risk_path(fp): print(f"🚨 实时监控拦截风险:{fp}") if risk_three_confirm(): quarantine_file(fp)

X+P 快捷键监听

def listen_hotkey(): global STOP_SCAN_FLAG while True: if keyboard.is_pressed('x') and keyboard.is_pressed('p'): STOP_SCAN_FLAG = True print("\n🛑 触发 X+P,立即停止所有杀毒任务") break time.sleep(0.1)

主菜单

def main(): init_dir() print("===== 强化版Python杀毒软件 =====") print("1. 全盘深度扫描(内核驱动+隐藏加密+锁定文件全扫)") print("2. 开启实时文件监控") print("3. 退出") print("提示:随时按 X+P 强制终止杀毒\n")

threading.Thread(target=listen_hotkey, daemon=True).start()

while True:
    opt = input("请选择功能(1/2/3):")
    global STOP_SCAN_FLAG
    STOP_SCAN_FLAG = False
    if opt == "1":
        full_scan()
    elif opt == "2":
        path = input("输入监控文件夹路径:")
        threading.Thread(target=real_time_monitor, args=(path,), daemon=True).start()
        input("按回车返回主菜单...")
    elif opt == "3":
        privacy_destroy_file(PRIVACY_TMP)
        print("👋 退出,隐私记录已全部粉碎清除")
        break
    else:
        print("输入错误,请重新选择")

if name == "main": main()。

这是我的杀病毒软件python简版,有兴趣的可以玩,全部开源