"""
http://www.programmersought.com/article/41052167991/
snippets get-baidu-cookies.py
cursor = conn.execute("PRAGMA table_info(cookies)"):
cursor.fetchal()
[(0, 'creation_utc', 'INTEGER', 1, None, 0),
(1, 'host_key', 'TEXT', 1, None, 0),
(2, 'name', 'TEXT', 1, None, 0),
(3, 'value', 'TEXT', 1, None, 0),
(4, 'path', 'TEXT', 1, None, 0),
(5, 'expires_utc', 'INTEGER', 1, None, 0),
(6, 'is_secure', 'INTEGER', 1, None, 0),
(7, 'is_httponly', 'INTEGER', 1, None, 0),
(8, 'last_access_utc', 'INTEGER', 1, None, 0),
(9, 'has_expires', 'INTEGER', 1, '1', 0),
(10, 'is_persistent', 'INTEGER', 1, '1', 0),
(11, 'priority', 'INTEGER', 1, '1', 0),
(12, 'encrypted_value', 'BLOB', 0, "''", 0),
(13, 'samesite', 'INTEGER', 1, '-1', 0),
(14, 'source_scheme', 'INTEGER', 1, '0', 0)]
_ = CIMultiDict({'domain': '.baidu.com', 'names': ['*'],
'copyto': True, 'cookies': False, 'debug': True})
for elm in _:
globals()[elm] = _.get(elm)
domain_name = domain
"""
from typing import Any, List, Optional, Union
import os
import sys
from pathlib import Path
import shutil
import sqlite3
import json
import urllib.parse
from win32crypt import CryptUnprotectData # pylint: disable=no-name-in-module
import pyperclip
# from absl import app, flags
# import multidict # for typing hint
# from multidict import CIMultiDict
import logzero
from logzero import logger
# pylint: disable=too-many-locals, too-many-branches, too-many-statements, broad-except # noqa=E501
def chrome_cookies(
domain_name: Union[str, bytes] = ".baidu.com",
names: Optional[List[str]] = None, # set to ['*]
copyto: bool = True,
# debug: Union[bool, int] = 0,
debug: Optional[Any] = 0,
) -> Optional[Union[dict, str]]:
""" fetch baidu cookies from chrome in windows
"""
if not sys.platform.startswith('win'):
raise SystemExit(
'Only this proggie works on Windows, '
'for linux/osx, please check out pycookiecheat.'
)
if names is None:
names = ['*']
if isinstance(domain_name, bytes):
domain_name = domain_name.decode()
domain_name = str(domain_name)
# convert possible url to domain
try:
host_key = urllib.parse.urlparse(domain_name).path
except Exception as exc:
logger.error(exc)
raise
# remove prefix www if present
if host_key.startswith("www"):
host_key = host_key[3:]
# make sure a dot is preappened
host_key = "." + host_key.strip(".")
if len(host_key.strip(".").split(".")) < 2:
logger.warning(
"looks like a top level domain -- something is probably wrong, but we proceed anyway." # noqa=E501
)
if debug:
logzero.loglevel(10)
else:
logzero.loglevel(20)
_ = os.getenv("LOCALAPPDATA")
_ = Path(_) / r"Google\Chrome\User Data\Default\Cookies"
cookie_file = f"{_}"
if not Path(cookie_file).exists():
logger.warning(" Only tested on Win10 for Chome")
sys.exit(f" cookie file {cookie_file} does not exist.")
# make a copy
dst = f'{os.getenv("USERPROFILE")}/temp-Cookies'
try:
_ = shutil.copy(cookie_file, dst)
except Exception as exc:
sys.exit(exc)
# sql = "select * from cookies where host_key like '.baidu.com';" # noqa=E501
# len: 15
sql = "select host_key, path, is_secure, expires_utc, name, value, encrypted_value from cookies where host_key like ?" # noqa=E501
# len 7
# [*conn.cursor().execute(sql, (host_key,))]
# sql = f"select * from cookies where host_key like '%{url}%';"
# host_key = '.baidu.com'
try:
# conn = sqlite3.connect(cookie_file)
conn = sqlite3.connect(f"{dst}")
except Exception as exc:
logger.error("Unable to open sqlite3 on %s: %s", cookie_file, exc)
sys.exit(1)
try:
cursor = conn.cursor()
# cursor_execute = cursor.execute(sql)
cursor_execute = cursor.execute(sql, (host_key,))
except Exception as exc:
logger.error("%s", exc)
raise
# finally: conn.close()
if debug:
cursor_execute = [*cursor_execute]
logger.debug(cursor_execute)
logger.debug([len(elm) for elm in cursor_execute])
cookies_dict = {}
for elm in cursor_execute:
logger.debug("elm: %s", elm)
# host_key, name, encrypted_value = elm[1], elm[2], elm[12]
name, encrypted_value = elm[4], elm[6]
logger.debug("%s %s %s", host_key, name, encrypted_value)
try:
cookie = CryptUnprotectData(encrypted_value)
logger.debug("%s %s %s %s", host_key, name, encrypted_value, cookie) # noqa=E501
cookies_dict.update({name: cookie[1].decode()})
except Exception as exc:
logger.debug("exc: %s", exc)
continue
conn.close()
logger.info("cookies (dict) for %s returned", host_key)
if copyto:
pyperclip.copy(json.dumps(cookies_dict))
return cookies_dict
if __name__ == "__main__":
print(chrome_cookies("www.52pojie.cn", debug=True))