C#清除网站502错误脚本

查看 172|回复 18
作者:wlm123   
   
我经常上https://www.pc528.net,用的电脑很杂,所以一直在用便携式浏览器,这些UserData特别是浏览器升级后,就容易出现502错误,此时可以直接删除UserData,重新登录一次就解决这个问题了,虽然密码可以导入导出,还是有很多其他内容也要处理。
现在最简单的办法就是让AI直接处理,来得最快。但AI的启动速度慢,用脚本来处理就会更方便。
`User Data\Default\Network\Cookies` 是**一个 640 KB 的 SQLite 数据库**,里面装着**全部 1247 条 Cookie**,所有站点的登录态都保存在同一张表里,即 `cookies` 表。它并没有按站点拆分文件。
因此,`del Cookies` 的效果就等于 “把全部站点一起登出”,这正是你不愿意做的。要做到 “只清 pc528”,必须**在这个数据库里执行一条 `DELETE FROM cookies WHERE host_key LIKE '%pc528%'`**,而不是删除文件。
对比一下就很清楚:
表格
| 目标 | 用 bat 直接操作文件能做到吗 |
| --- | --- |
| 删整个 User Data、删 Cookies 文件 | 能,但等于所有站点重新登录(你已否决) |
| 只删 pc528 的 Cookie | **不能**,这是数据库里的行级操作 |
| 删该站的 Local Storage、IndexedDB | 能,这部分确实是按目录分开的(`IndexedDB\https_www.pc528.net_*`) |
## 为什么 bat 无法完成 SQL 操作
`cmd.exe` 自身不具备任何 SQLite 能力。要执行 SQL,必须能调用 SQLite 引擎。这台机器上:
- `PATH` 里没有 `sqlite3.exe`
- `System32`、CentBrowser 目录里也都没有(刚刚逐个验证过)
- 只有 `C:\Windows\System32\winsqlite3.dll`,它是 C 接口的**动态库**,命令行工具无法调用
所以只有两条路:要么下载一个第三方 `sqlite3.exe`,但杀毒软件容易报毒,而且还要应付文件锁;要么写一个能直接调用这个 DLL 的小程序。后者就是那个 12 KB 的 exe。
## 还有第二个关键限制:文件锁
浏览器开着的时候,`Cookies` 被**独占锁**住,连读取都不行(上一轮实测中,`Copy-Item` 直接报 “正由另一进程使用”,Python 报 `PermissionError 13`)。所以正确顺序必须是:
1. 正常关闭浏览器:只发送关闭窗口消息,不作强制终止,以防 Cookie 丢失
2. 备份 `Cookies` 与 `Local State`
3. 删除指定行
4. 用 `integrity_check` 复查,并确认残留数为 0
5. 重新启动浏览器
这套带条件判断的时序用五条 `goto` 和 `timeout` 在 bat 里勉强能拼出来,但一旦某一步失败,你就会留下一个 “浏览器已关闭、数据库未修改” 或更糟的中间状态。在 C# 里,它只是几行 `if`。
顺带说明:不用 PowerShell,不只是因为你嫌它启动慢;PowerShell 的 .NET 同样**没有**内建 SQLite 提供程序,最终仍然得用同一套 P/Invoke,只是换成在 .ps1 里执行,并且多出 1–2 秒冷启动。既然代码一样,那么做成 exe 更划算。
特别是浏览器种类多时更明显,因为可以用脚来来解决这些问题,以下是我的电脑用C#写的脚本:[ol]// =============================================================================
//  Pc528CookieCleaner  —— 只清除 CentBrowser 中 www.pc528.net(初心精简)的站点数据
//
//  背景:访问该站时出现「502 错误的网关(由 Tengine 提供技术支持)」。
//        实测该站边缘对匿名请求返回 200(X-Static-Cache: HIT),
//        而带登录态(PHPSESSID)的请求必须回源,回源失败时边缘吐 502。
//        清除该站的 Cookie 后回到匿名路径即可恢复,并可重新登录。
//
//  安全性:只删除 host_key LIKE '%pc528%' 的行 + 该 origin 的 IndexedDB 目录,
//          其它网站的 Cookie / 登录态一律不动,删除前完整备份。
//
//  编译(无需安装 SDK,用系统自带 .NET Framework 编译器):
//    csc /target:exe /platform:x64 /optimize /win32manifest:app.manifest
//        /out:pc528fix.exe Pc528CookieCleaner.cs
// =============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
internal static class Sqlite3
{
    private const string Dll = "winsqlite3.dll";   // Windows 自带(System32),无第三方依赖
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    internal static extern int sqlite3_open_v2(string filename, out IntPtr db, int flags, IntPtr vfs);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    internal static extern int sqlite3_prepare_v2(IntPtr db, string sql, int nByte, out IntPtr stmt, IntPtr tail);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sqlite3_step(IntPtr stmt);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sqlite3_column_int(IntPtr stmt, int iCol);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr sqlite3_column_text(IntPtr stmt, int iCol);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sqlite3_finalize(IntPtr stmt);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sqlite3_changes(IntPtr db);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sqlite3_close(IntPtr db);
    [DllImport(Dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    internal static extern IntPtr sqlite3_errmsg(IntPtr db);
}
internal static class Program
{
    private const string ExePath  = @"C:\Program Files\CentBrowser\chrome.exe";
    private const string UserData = @"C:\Program Files\CentBrowser\User Data";
    private const string Pattern  = "%pc528%";                 // 只匹配 www.pc528.net / .pc528.net
    private const string OriginKey = "www.pc528.net_";          // IndexedDB 目录名过滤
    private static bool   _force;
    private static bool   _noRestart;
    private static string _cookiesOverride;                     // 测试用:指向 Cookie 库副本
    private static bool   _failed;
    private static void Say(string text, ConsoleColor color = ConsoleColor.Gray)
    {
        Console.ForegroundColor = color;
        Console.WriteLine("  " + text);
        Console.ResetColor();
    }
    private static int Main(string[] args)
    {
        try { Console.OutputEncoding = Encoding.UTF8; } catch { }
        for (int i = 0; i  profiles = FindProfiles();
        if (profiles.Count == 0)
        {
            Say("错误:任何配置目录下都没有 Network\\Cookies", ConsoleColor.Red);
            return 4;
        }
        var names = new List();
        foreach (string p in profiles) names.Add(new DirectoryInfo(p).Name);
        Say("发现配置目录 " + names.Count + " 个:" + string.Join("、", names.ToArray()));
        if (!_force)
        {
            Say("将执行:关闭 CentBrowser → 备份 Cookie 库 → 只删除 pc528.net 的 Cookie → 重启浏览器", ConsoleColor.Yellow);
            if (!Confirm(6))
            {
                Say("已取消,未做任何修改。", ConsoleColor.Yellow);
                return 1;
            }
        }
        bool wasRunning = CbProcesses().Count > 0;
        if (wasRunning)
        {
            Say("正在正常关闭 CentBrowser ...");
            if (!StopBrowser())
            {
                Say("错误:浏览器未能在 25 秒内退出(可能弹出「确认离开此页面」对话框)。", ConsoleColor.Red);
                Say("已中止,Cookie 库未被修改。请手动关闭浏览器后重试。", ConsoleColor.Red);
                return 3;
            }
            Say("浏览器已退出。");
        }
        else
        {
            Say("浏览器当前未运行。");
        }
        string backupDir = PrepareBackupDir();
        string stamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
        string localState = Path.Combine(UserData, "Local State");
        if (File.Exists(localState))
        {
            try { File.Copy(localState, Path.Combine(backupDir, "Local State_" + stamp), true); } catch { }
        }
        int deleted = 0;
        foreach (string prof in profiles)
        {
            string name   = new DirectoryInfo(prof).Name;
            string dbPath = Path.Combine(prof, "Network", "Cookies");
            try { File.Copy(dbPath, Path.Combine(backupDir, "Cookies_" + name + "_" + stamp + ".db"), true); }
            catch (Exception ex)
            {
                Say("警告:备份 " + name + " 失败:" + ex.Message, ConsoleColor.Yellow);
                _failed = true;
            }
            Result r = CleanOne(dbPath, name);
            deleted += r.Deleted;
            CleanSiteFolders(prof);
        }
        if (wasRunning && !_noRestart)
        {
            try
            {
                Process.Start(new ProcessStartInfo(ExePath)
                {
                    WorkingDirectory = Path.GetDirectoryName(ExePath),
                    UseShellExecute = true
                });
                Say("已重新启动 CentBrowser。");
            }
            catch (Exception ex) { Say("启动浏览器失败:" + ex.Message, ConsoleColor.Yellow); }
        }
        Say("");
        Say("完成:本次共删除 " + deleted + " 行 Cookie;备份目录:" + backupDir, ConsoleColor.Cyan);
        Say("请在该站按 Ctrl+F5 强制刷新,然后重新登录。", ConsoleColor.Cyan);
        Say("");
        if (_failed)          return 4;
        if (deleted == 0)     return 2;
        return 0;
    }
    private struct Result
    {
        public bool Ok;
        public int  Deleted;
    }
    // ------------------------------------------------------------------ 权限
    private static bool IsAdmin()
    {
        try
        {
            using (WindowsIdentity id = WindowsIdentity.GetCurrent())
                return new WindowsPrincipal(id).IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch { return false; }
    }
    // ------------------------------------------------------------------ 配置目录
    private static List FindProfiles()
    {
        var list = new List();
        try
        {
            foreach (string dir in Directory.GetDirectories(UserData))
            {
                if (File.Exists(Path.Combine(dir, "Network", "Cookies"))) list.Add(dir);
            }
        }
        catch { }
        return list;
    }
    // ------------------------------------------------------------------ 浏览器
    private static List CbProcesses()
    {
        var list = new List();
        foreach (Process p in Process.GetProcessesByName("chrome"))
        {
            try
            {
                string f = p.MainModule.FileName;
                if (string.Equals(f, ExePath, StringComparison.OrdinalIgnoreCase)) list.Add(p);
            }
            catch { /* 无权限的进程忽略 */ }
        }
        return list;
    }
    private static bool StopBrowser()
    {
        foreach (Process p in CbProcesses())
        {
            try { if (p.MainWindowHandle != IntPtr.Zero) p.CloseMainWindow(); } catch { }
        }
        for (int i = 0; i  0)
            {
                int changed  = Dml(db, "DELETE FROM cookies WHERE host_key LIKE '" + Pattern + "'");
                int left     = Scalar(db, "SELECT count(*) FROM cookies WHERE host_key LIKE '" + Pattern + "'");
                string integ = Text(db, "PRAGMA integrity_check");
                Say("[" + label + "] 已删除 " + changed + " 行;残留 " + left + ";integrity_check=" + integ, ConsoleColor.Green);
                if (left != 0) _failed = true;
                result.Deleted = changed;
            }
            else
            {
                Say("[" + label + "] 没有 pc528 的 Cookie,无需删除");
            }
            int totalAfter = Scalar(db, "SELECT count(*) FROM cookies");
            Say("[" + label + "] 清理后全库 " + totalAfter + " 条(原 " + totalBefore + ")");
            result.Ok = true;
            return result;
        }
        catch (Exception ex)
        {
            Say("错误 [" + label + "] " + ex.Message, ConsoleColor.Red);
            _failed = true;
            return result;
        }
        finally
        {
            try { Sqlite3.sqlite3_close(db); } catch { }
        }
    }
    // ------------------------------------------------------------------ 清理站点存储目录
    private static void CleanSiteFolders(string profileDir)
    {
        string idb = Path.Combine(profileDir, "IndexedDB");
        if (!Directory.Exists(idb)) return;
        try
        {
            foreach (string d in Directory.GetDirectories(idb))
            {
                string n = Path.GetFileName(d).ToLowerInvariant();
                if (n.StartsWith("https_" + OriginKey) || n.StartsWith("http_" + OriginKey))
                {
                    try { Directory.Delete(d, true); Say("  已删除站点存储目录:" + n); }
                    catch (Exception ex) { Say("  删除 " + n + " 失败:" + ex.Message, ConsoleColor.Yellow); }
                }
            }
        }
        catch { }
    }
    // ------------------------------------------------------------------ SQL 封装
    private static int Scalar(IntPtr db, string sql)
    {
        IntPtr stmt = IntPtr.Zero;
        if (Sqlite3.sqlite3_prepare_v2(db, sql, -1, out stmt, IntPtr.Zero) != 0)
            throw new Exception("SQL 预处理失败:" + sql);
        try
        {
            int v = 0;
            if (Sqlite3.sqlite3_step(stmt) == 100 /* SQLITE_ROW */) v = Sqlite3.sqlite3_column_int(stmt, 0);
            return v;
        }
        finally { Sqlite3.sqlite3_finalize(stmt); }
    }
    private static string Text(IntPtr db, string sql)
    {
        IntPtr stmt = IntPtr.Zero;
        if (Sqlite3.sqlite3_prepare_v2(db, sql, -1, out stmt, IntPtr.Zero) != 0) return "prepare_failed";
        try
        {
            string v = "";
            if (Sqlite3.sqlite3_step(stmt) == 100)
            {
                IntPtr p = Sqlite3.sqlite3_column_text(stmt, 0);
                if (p != IntPtr.Zero) v = Marshal.PtrToStringAnsi(p);
            }
            return v;
        }
        finally { Sqlite3.sqlite3_finalize(stmt); }
    }
    private static int Dml(IntPtr db, string sql)
    {
        IntPtr stmt = IntPtr.Zero;
        if (Sqlite3.sqlite3_prepare_v2(db, sql, -1, out stmt, IntPtr.Zero) != 0)
            throw new Exception("SQL 预处理失败:" + sql);
        try
        {
            int step = Sqlite3.sqlite3_step(stmt);
            if (step != 101 /* SQLITE_DONE */) throw new Exception("SQL 执行未完成 step=" + step);
            return Sqlite3.sqlite3_changes(db);
        }
        finally { Sqlite3.sqlite3_finalize(stmt); }
    }
    // ------------------------------------------------------------------ 确认
    private static bool Confirm(int seconds)
    {
        bool canReadKeys = true;
        try { bool dummy = Console.KeyAvailable; }
        catch { canReadKeys = false; }
        if (!canReadKeys)
        {
            Console.Write("  输入 y 继续(其它任意输入取消):");
            string s = Console.ReadLine();
            return s != null && s.Trim().Equals("y", StringComparison.OrdinalIgnoreCase);
        }
        for (int i = seconds; i > 0; i--)
        {
            Console.Write("\r  剩余 {0,2} 秒,按任意键立即开始,不按键则取消 ...", i);
            for (int j = 0; j 复制代码

浏览器, 错误, 目录

h404bi   
感谢楼主分享
chenxuhua   
看到了 百分浏览器 CentBrowser,保存试试
ribble   
多谢大佬分享实用的小脚本啊
hu008422   
谢谢分享
4630269wu   
支持折腾
leweishang   
多谢分享!!!
antclt   
楼主的思路很好,有借鉴作用,谢谢
Yadomin   
楼主这个思路很实用,只清出问题的那个站的数据,其他站的登录态都不受影响,比整库删干净得多;先备份再动手这个习惯也很好,值得学习。
qfbjp   
很实用,已解决同样问题。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部