Last active
January 3, 2016 09:19
-
-
Save imbolc/8441403 to your computer and use it in GitHub Desktop.
read firefox cookies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sqlite3 | |
import ConfigParser | |
class FirefoxCookies(object): | |
''' | |
Usage: | |
cookies = FirefoxCookies() | |
print cookies.items() # [(name, value), ...] | |
print cookies.dict() # dict style for requests | |
print cookies.header() # header style for grab | |
With requests: | |
import requests | |
with requests.session() as s: | |
r = s.get('http://yandex.ru/', cookies=FirefoxCookies().dict()) | |
print 'imbolc' in r.text | |
''' | |
items = lambda self: self._cookies | |
dict = lambda self: dict(self._cookies) | |
header = lambda self: ', '.join('%s=%s' % c for c in self._cookies) | |
def __init__(self, host='.yandex.', firefox_dirname='~/.mozilla/firefox'): | |
self.host = host | |
self.dbpath = self._get_dbpath(firefox_dirname) | |
self._cookies = self._get_cookies() | |
def _get_cookies(self): | |
con = sqlite3.connect(self.dbpath) | |
cur = con.cursor() | |
cur.execute('SELECT host, name, value FROM moz_cookies order by host') | |
return [(n, v) for h, n, v in cur.fetchall() if self.host in h] | |
@staticmethod | |
def _get_dbpath(dirname): | |
dirname = os.path.expanduser(dirname) | |
config = ConfigParser.RawConfigParser(allow_no_value=True) | |
config.read(os.path.join(dirname, 'profiles.ini')) | |
profile_dirname = os.path.join(dirname, config.get('Profile0', 'Path')) | |
return os.path.join(profile_dirname, 'cookies.sqlite') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment