Skip to content

Instantly share code, notes, and snippets.

@fberger
Created May 23, 2012 09:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fberger/2774235 to your computer and use it in GitHub Desktop.
Save fberger/2774235 to your computer and use it in GitHub Desktop.
ChromeCookieJar
from cookielib import CookieJar, Cookie
import sqlite3
import os
import shutil
import tempfile
__all__ = ['ChromeCookieJar']
def to_epoch_seconds(chrome_timestamp):
return chrome_timestamp - 11644473600 * 1000 * 1000
class ChromeCookieJar(CookieJar):
'''
Reads cookies from a Google Chrome profile into memory
Sample usage:
import chromejar
jar = chromejar.ChromeCookieJar(profile='Profile 1')
import urllib2
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar),
urllib2.HTTPSHandler(debuglevel=3))
r = opener.open('https://github.com/')
'yourusername' in r.read()
'''
def __init__(self, policy=None, profile='Default'):
CookieJar.__init__(self, policy)
path = os.path.join(os.environ['HOME'],
'.config/google-chrome/%s/Cookies' % profile)
if not os.path.exists(path):
raise ValueException('No Chrome cookies at path: %s' % path)
tmpfile = tempfile.mktemp()
shutil.copyfile(path, tmpfile)
connection = sqlite3.connect(tmpfile)
cursor = connection.cursor()
results = cursor.execute('select * from cookies')
for creation_utc, host_key, name, value, path, expires_utc, secure, httponly, last_access_utc, has_expires, persistent in results:
c = Cookie(None,
name,
value,
None,
False,
host_key,
host_key and True or False,
host_key.startswith('.'),
path,
path and True or False,
secure,
has_expires and to_epoch_seconds(expires_utc) or None,
False,
None,
None,
{})
self.set_cookie(c)
cursor.close()
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment