技术指南:如何安全导出浏览器Cookie实现命令行工具集成

📅 发布时间:2026/8/3 0:11:58
技术指南:如何安全导出浏览器Cookie实现命令行工具集成 技术指南如何安全导出浏览器Cookie实现命令行工具集成【免费下载链接】Get-cookies.txt-LOCALLYGet cookies.txt, NEVER send information outside.项目地址: https://gitcode.com/gh_mirrors/ge/Get-cookies.txt-LOCALLY在开发自动化脚本、进行Web爬虫测试或跨设备同步登录状态时开发者和技术爱好者经常需要访问受认证保护的网站资源。传统方法如手动登录或使用硬编码凭证存在安全风险且效率低下。Get cookies.txt LOCALLY提供了一个完整的本地Cookie导出解决方案通过Chrome扩展API实现100%本地处理的浏览器Cookie导出支持Netscape和JSON格式兼容curl、wget、Python等主流命令行工具确保隐私安全和数据控制。技术问题分析浏览器Cookie管理的安全挑战隐私泄露风险与数据控制需求现代Web开发中Cookie作为HTTP状态管理机制存储了用户的会话标识、认证令牌和个性化设置等敏感信息。传统在线Cookie导出工具面临以下技术挑战数据外泄风险第三方服务可能收集或存储用户的Cookie数据跨站脚本攻击不当的Cookie处理可能导致XSS漏洞API兼容性问题不同浏览器对Cookie访问API的实现存在差异格式转换复杂性Netscape格式与JSON格式的技术实现差异浏览器扩展开发的技术限制Chrome扩展Manifest V3引入了更严格的安全策略对Cookie访问权限进行了细粒度控制。Firefox的WebExtensions API虽然兼容Chrome扩展但在某些API实现上存在差异特别是chrome.downloadsAPI在弹出窗口中的使用限制。解决方案架构模块化设计的本地Cookie导出系统核心模块技术实现Get cookies.txt LOCALLY采用模块化架构设计将功能分解为三个核心模块Cookie获取模块(src/modules/get_all_cookies.mjs)export default async function getAllCookies(details) { details.storeId ?? await getCurrentCookieStoreId(); const { partitionKey, ...detailsWithoutPartitionKey } details; // 处理不支持partitionKey的浏览器版本 const cookiesWithPartitionKey partitionKey ? await Promise.resolve() .then(() chrome.cookies.getAll(details)) .catch(() []) : []; const cookies await chrome.cookies.getAll(detailsWithoutPartitionKey); return [...cookies, ...cookiesWithPartitionKey]; }该模块通过chrome.cookies.getAll()API获取指定URL的Cookie数据支持跨浏览器兼容性处理特别是针对Chrome 119以下版本不支持partitionKey参数的降级方案。格式转换模块(src/modules/cookie_format.mjs)export const jsonToNetscapeMapper (cookies) { return cookies.map( ({ domain, expirationDate, path, secure, name, value }) { const includeSubDomain !!domain?.startsWith(.); const expiry expirationDate?.toFixed() ?? 0; const arr [domain, includeSubDomain, path, secure, expiry, name, value]; return arr.map((v) typeof v boolean ? v.toString().toUpperCase() : v, ); }, ); };该模块实现了三种输出格式Netscape格式兼容wget、curl等传统工具JSON格式便于编程解析和结构化处理Header格式直接用于HTTP请求头文件保存模块(src/modules/save_to_file.mjs)export default async function saveToFile( text, name, { ext, mimeType }, saveAs false, ) { const blob new Blob([text], { type: mimeType }); const filename name ext; const url URL.createObjectURL(blob); const id await chrome.downloads.download({ url, filename, saveAs }); // 清理下载完成后的Blob URL const onChange (delta) { if (delta.id id delta.state?.current ! in_progress) { chrome.downloads.onChanged.removeListener(onChange); URL.revokeObjectURL(url); } }; chrome.downloads.onChanged.addListener(onChange); }该模块使用Blob API和chrome.downloadsAPI实现本地文件保存确保数据不离开用户设备。权限管理与安全架构扩展的权限配置在src/manifest.json中明确定义{ permissions: [activeTab, cookies, downloads, notifications], host_permissions: [all_urls], incognito: split }权限使用说明activeTab仅获取当前活动标签页的URL不访问其他标签页cookies只读权限仅用于导出Cookie数据downloads仅用于保存本地文件不访问其他下载内容host_permissions必需权限用于访问所有域名的Cookie隐私策略文件privacy-policy.md明确声明扩展不收集任何用户数据所有操作均在本地完成。安装配置指南多环境部署技术方案从源代码构建与安装克隆仓库并准备开发环境git clone https://gitcode.com/gh_mirrors/ge/Get-cookies.txt-LOCALLY cd Get-cookies.txt-LOCALLY npm install构建Chrome扩展npm run build:chrome构建脚本scripts/build.js会自动打包扩展文件到dist/chrome目录。构建Firefox扩展npm run build:firefoxFirefox构建需要合并src/manifest.json和src/manifest-firefox.json脚本会自动处理API差异。Chrome浏览器手动加载扩展访问Chrome扩展管理页面chrome://extensions/启用右上角的开发者模式开关点击加载已解压的扩展程序按钮选择src文件夹或构建后的dist/chrome目录Firefox浏览器手动加载扩展访问Firefox调试页面about:debugging#/runtime/this-firefox点击临时载入附加组件按钮选择src/manifest-firefox.json文件或构建后的dist/firefox目录浏览器API兼容性处理由于Chrome和Firefox的API实现差异扩展采用了条件编译策略const isFirefox chrome.runtime.getManifest().browser_specific_settings ! undefined; if (isFirefox) { // Firefox使用后台脚本处理下载 await chrome.runtime.sendMessage({ type: save, target: background, data: { text, name, format, saveAs }, }); } else { // Chrome直接在弹出窗口处理下载 await _saveToFile(text, name, format, saveAs); }高级应用场景复杂环境下的Cookie集成方案使用Python脚本批量处理Cookie文件Python的http.cookiejar模块提供了完整的Cookie处理功能import http.cookiejar import urllib.request import json class CookieManager: def __init__(self): self.cookie_jar http.cookiejar.MozillaCookieJar() def load_from_netscape(self, filepath): 从Netscape格式文件加载Cookie self.cookie_jar.load(filepath, ignore_discardTrue, ignore_expiresTrue) return self def load_from_json(self, filepath): 从JSON格式文件加载Cookie with open(filepath, r, encodingutf-8) as f: cookies json.load(f) for cookie in cookies: # 转换为MozillaCookieJar格式 c http.cookiejar.Cookie( version0, namecookie[name], valuecookie[value], portNone, port_specifiedFalse, domaincookie[domain], domain_specifiedbool(cookie[domain]), domain_initial_dotcookie[domain].startswith(.), pathcookie[path], path_specifiedbool(cookie[path]), securecookie[secure], expiresint(cookie[expirationDate]) if cookie.get(expirationDate) else None, discardFalse, commentNone, comment_urlNone, rest{}, rfc2109False ) self.cookie_jar.set_cookie(c) return self def make_request(self, url): 使用加载的Cookie发起HTTP请求 opener urllib.request.build_opener( urllib.request.HTTPCookieProcessor(self.cookie_jar) ) response opener.open(url) return response.read() # 使用示例 manager CookieManager() manager.load_from_netscape(cookies.txt) content manager.make_request(https://api.example.com/protected-resource)在Docker容器中配置Cookie环境对于需要持久化Cookie的Docker容器环境可以创建专门的Cookie管理服务FROM python:3.11-slim # 安装必要的工具 RUN apt-get update apt-get install -y \ curl \ wget \ rm -rf /var/lib/apt/lists/* # 创建Cookie管理目录 RUN mkdir -p /app/cookies # 安装Python依赖 COPY requirements.txt /app/ RUN pip install --no-cache-dir -r /app/requirements.txt # 复制Cookie管理脚本 COPY cookie_manager.py /app/ # 设置工作目录 WORKDIR /app # 创建数据卷用于Cookie持久化 VOLUME [/app/cookies] # 运行Cookie同步服务 CMD [python, cookie_manager.py]对应的Python同步脚本# cookie_manager.py import os import time import json from pathlib import Path from datetime import datetime class DockerCookieManager: def __init__(self, cookie_dir/app/cookies): self.cookie_dir Path(cookie_dir) self.cookie_dir.mkdir(exist_okTrue) def sync_cookies(self, source_file, target_formatnetscape): 同步Cookie文件到不同格式 source_path self.cookie_dir / source_file if not source_path.exists(): print(fCookie文件不存在: {source_path}) return # 根据源格式选择转换逻辑 if source_file.endswith(.json): self._convert_json_to_netscape(source_path) elif source_file.endswith(.txt): self._convert_netscape_to_json(source_path) def _convert_json_to_netscape(self, json_path): JSON转Netscape格式 with open(json_path, r) as f: cookies json.load(f) netscape_lines [ # Netscape HTTP Cookie File, # https://curl.haxx.se/rfc/cookie_spec.html, # Generated by Docker Cookie Manager, ] for cookie in cookies: domain cookie.get(domain, ) include_subdomain TRUE if domain.startswith(.) else FALSE path cookie.get(path, /) secure TRUE if cookie.get(secure) else FALSE expiry str(int(cookie.get(expirationDate, 0))) if cookie.get(expirationDate) else 0 name cookie.get(name, ) value cookie.get(value, ) netscape_lines.append(f{domain}\t{include_subdomain}\t{path}\t{secure}\t{expiry}\t{name}\t{value}) output_path json_path.with_suffix(.txt) with open(output_path, w) as f: f.write(\n.join(netscape_lines)) print(f已转换: {json_path.name} - {output_path.name}) if __name__ __main__: manager DockerCookieManager() # 监控目录变化并自动同步 while True: for cookie_file in manager.cookie_dir.glob(*.json): manager.sync_cookies(cookie_file.name) time.sleep(60) # 每分钟检查一次自动化测试环境集成在Selenium自动化测试中集成Cookie导出功能from selenium import webdriver from selenium.webdriver.chrome.options import Options import json import time class TestCookieManager: def __init__(self, driver): self.driver driver self.cookies_dir test_cookies def export_cookies_for_testing(self, test_name): 导出当前会话Cookie用于测试 cookies self.driver.get_cookies() # 保存为JSON格式 json_path f{self.cookies_dir}/{test_name}_{int(time.time())}.json with open(json_path, w) as f: json.dump(cookies, f, indent2) # 转换为Netscape格式用于curl/wget netscape_path json_path.replace(.json, .txt) self._convert_to_netscape(cookies, netscape_path) return json_path, netscape_path def _convert_to_netscape(self, cookies, output_path): 将Selenium Cookie转换为Netscape格式 lines [ # Netscape HTTP Cookie File, # Generated for Selenium testing, # Test session cookies, ] for cookie in cookies: domain cookie.get(domain, ) if domain and not domain.startswith(.): domain . domain include_subdomain TRUE if domain.startswith(.) else FALSE path cookie.get(path, /) secure TRUE if cookie.get(secure) else FALSE expiry str(int(cookie.get(expiry, 0))) if cookie.get(expiry) else 0 name cookie.get(name, ) value cookie.get(value, ) lines.append(f{domain}\t{include_subdomain}\t{path}\t{secure}\t{expiry}\t{name}\t{value}) with open(output_path, w) as f: f.write(\n.join(lines)) def load_cookies_to_driver(self, cookie_file): 从文件加载Cookie到Selenium驱动 with open(cookie_file, r) as f: cookies json.load(f) # 先访问域名以设置Cookie if cookies: domain cookies[0].get(domain, ).lstrip(.) self.driver.get(fhttps://{domain}) # 添加所有Cookie for cookie in cookies: self.driver.add_cookie(cookie) # 使用示例 options Options() options.add_argument(--headless) driver webdriver.Chrome(optionsoptions) try: driver.get(https://example.com/login) # 执行登录操作... cookie_manager TestCookieManager(driver) json_file, netscape_file cookie_manager.export_cookies_for_testing(login_test) print(fCookie已导出: {json_file}, {netscape_file}) # 在新会话中加载Cookie new_driver webdriver.Chrome(optionsoptions) cookie_manager.driver new_driver cookie_manager.load_cookies_to_driver(json_file) # 现在可以访问需要认证的页面 new_driver.get(https://example.com/dashboard) finally: driver.quit()安全技术分析权限管理与数据流控制扩展权限的细粒度控制Get cookies.txt LOCALLY采用最小权限原则设计每个权限都有明确的用途说明权限名称技术用途安全影响activeTab获取当前活动标签页URL仅临时访问不持久存储cookies读取浏览器Cookie数据只读权限无法修改或创建Cookiedownloads保存文件到本地仅用于导出操作不访问其他下载notifications显示更新通知仅用于用户信息提示host_permissions访问所有域名的Cookie必需权限用于Cookie读取数据流安全验证扩展的数据处理流程完全在用户设备本地完成数据获取阶段通过chrome.cookies.getAll()API读取Cookie数据不离开浏览器沙盒格式转换阶段在内存中进行格式转换不涉及网络传输文件保存阶段使用URL.createObjectURL()创建本地Blob URL通过chrome.downloads.download()保存到用户指定位置隐私保护机制实现根据privacy-policy.md的技术承诺零数据收集扩展代码中不包含任何网络请求或数据上报逻辑源代码透明完整开源代码便于安全审计API权限最小化仅请求必要的API权限每个权限都有明确用途本地处理保证所有数据处理操作都在浏览器扩展沙盒内完成技术问题排查常见问题与调试方法浏览器兼容性问题处理问题1Firefox中下载功能失效解决方案Firefox的chrome.downloadsAPI在弹出窗口中有限制需要通过后台脚本处理// 在popup.mjs中的处理逻辑 const saveToFile async (text, name, { ext, mimeType }, saveAs false) { const format { ext, mimeType }; const isFirefox chrome.runtime.getManifest().browser_specific_settings ! undefined; if (isFirefox) { // Firefox通过消息传递到后台脚本 await chrome.runtime.sendMessage({ type: save, target: background, data: { text, name, format, saveAs }, }); } else { // Chrome直接调用下载API await _saveToFile(text, name, format, saveAs); } };问题2Chrome 119以下版本partitionKey支持问题解决方案通过错误捕获和降级方案处理const cookiesWithPartitionKey partitionKey ? await Promise.resolve() .then(() chrome.cookies.getAll(details)) .catch(() []) // 旧版本Chrome返回空数组 : [];格式转换问题调试Netscape格式验证工具# 验证Netscape格式文件 function validate_netscape_cookies() { local file$1 echo 验证Netscape Cookie文件: $file echo # 检查文件头 head -5 $file | grep -q # Netscape HTTP Cookie File if [ $? -eq 0 ]; then echo ✓ 文件头正确 else echo ✗ 文件头不正确 fi # 统计有效行数 local total_lines$(wc -l $file) local comment_lines$(grep -c ^# $file) local data_lines$((total_lines - comment_lines)) echo 总行数: $total_lines echo 注释行: $comment_lines echo 数据行: $data_lines # 检查字段分隔符 local tab_count$(head -10 $file | tail -5 | grep -c $\t) if [ $tab_count -gt 0 ]; then echo ✓ 使用制表符分隔 else echo ✗ 可能使用空格分隔应为制表符 fi echo } # 使用示例 validate_netscape_cookies cookies.txtJSON格式验证脚本import json import sys def validate_json_cookies(filepath): 验证JSON格式Cookie文件的完整性 try: with open(filepath, r, encodingutf-8) as f: cookies json.load(f) print(f验证JSON Cookie文件: {filepath}) print( * 50) if not isinstance(cookies, list): print(✗ 根元素必须是数组) return False print(f✓ 包含 {len(cookies)} 个Cookie记录) required_fields [name, value, domain, path] valid_count 0 for i, cookie in enumerate(cookies): missing_fields [field for field in required_fields if field not in cookie] if missing_fields: print(f✗ 记录 {i}: 缺少字段 {missing_fields}) else: valid_count 1 print(f✓ 有效记录: {valid_count}/{len(cookies)}) print( * 50) return valid_count len(cookies) except json.JSONDecodeError as e: print(f✗ JSON解析错误: {e}) return False except Exception as e: print(f✗ 文件读取错误: {e}) return False if __name__ __main__: if len(sys.argv) ! 2: print(用法: python validate_json.py cookie_file.json) sys.exit(1) if validate_json_cookies(sys.argv[1]): print(验证通过) sys.exit(0) else: print(验证失败) sys.exit(1)性能优化与内存管理大Cookie集合处理优化// 分块处理大量Cookie避免内存溢出 async function processLargeCookieSet(url, chunkSize 100) { const allCookies []; let start 0; let hasMore true; while (hasMore) { try { const cookies await chrome.cookies.getAll({ url, partitionKey: { topLevelSite: new URL(url).origin } }); if (cookies.length 0) { hasMore false; break; } // 分块处理 for (let i start; i Math.min(start chunkSize, cookies.length); i) { allCookies.push(cookies[i]); } start chunkSize; hasMore start cookies.length; // 避免阻塞UI await new Promise(resolve setTimeout(resolve, 0)); } catch (error) { console.error(获取Cookie时出错:, error); break; } } return allCookies; }扩展界面功能详解上图展示了Get cookies.txt LOCALLY扩展的用户界面采用清晰的模块化设计顶部操作区域Export按钮一键导出当前网站Cookie为Netscape格式Export As按钮选择导出格式Netscape/JSON/HeaderCopy按钮复制Cookie数据到剪贴板Export All Cookies按钮导出当前标签页所有Cookie格式选择下拉菜单支持Netscape、JSON和HTTP Header三种输出格式Cookie数据表格实时显示当前网站的Cookie信息包括域名、路径、安全标志、过期时间等关键字段左侧说明区域详细说明扩展的安全特性包括本地处理保证、开源代码验证和隐私保护承诺技术实现总结与最佳实践Get cookies.txt LOCALLY通过严谨的技术架构实现了安全可靠的本地Cookie导出功能。其核心价值在于完全本地处理所有数据操作均在用户设备上完成无网络传输开源透明完整源代码便于安全审计和自定义修改格式兼容性支持行业标准的Netscape格式和现代JSON格式跨浏览器支持通过条件编译处理Chrome和Firefox的API差异安全使用建议定期清理Cookie文件建议每月清理一次导出的Cookie文件使用专用目录存储为Cookie文件创建加密目录避免与其他文件混合最小权限原则仅导出必要网站的Cookie避免全站Cookie导出版本更新检查定期从源代码仓库更新扩展版本开发集成建议自动化脚本集成结合cron任务或CI/CD流水线定期更新Cookie环境隔离为开发、测试、生产环境使用不同的Cookie文件版本控制将Cookie文件纳入版本控制记录变更历史监控告警设置文件访问监控检测异常Cookie使用通过遵循上述技术指南和安全实践开发者和技术爱好者可以安全、高效地利用Get cookies.txt LOCALLY进行Cookie管理和自动化集成在保护隐私的同时提升开发效率。【免费下载链接】Get-cookies.txt-LOCALLYGet cookies.txt, NEVER send information outside.项目地址: https://gitcode.com/gh_mirrors/ge/Get-cookies.txt-LOCALLY创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考