| 1 |
|
| 2 |
|
| 3 |
import argparse |
| 4 |
import browser_cookie3 |
| 5 |
import json |
| 6 |
|
| 7 |
|
| 8 |
def parse_args(args=None): |
| 9 |
p = argparse.ArgumentParser( |
| 10 |
description='Extract browser cookies using browser_cookie3.', |
| 11 |
epilog='Exit status is 0 if cookie was found, 1 if not found, and 2 if errors occurred', |
| 12 |
) |
| 13 |
p.add_argument('-j', '--json', action='store_true', |
| 14 |
help="Output JSON with all cookie details, rather than just the cookie's value") |
| 15 |
p.add_argument('domain') |
| 16 |
p.add_argument('name') |
| 17 |
|
| 18 |
g = p.add_argument_group('Browser selection') |
| 19 |
x = g.add_mutually_exclusive_group() |
| 20 |
x.add_argument('-a', '--all', dest='browser', action='store_const', const=None, default=None, |
| 21 |
help="Try to load cookies from all supported browsers") |
| 22 |
for browser in browser_cookie3.all_browsers: |
| 23 |
x.add_argument('--' + browser.__name__, dest='browser', action='store_const', const=browser, |
| 24 |
help="Load cookies from {} browser".format(browser.__name__.title())) |
| 25 |
g.add_argument('-f', '--cookie-file', |
| 26 |
help="Use specific cookie file (default is to autodetect).") |
| 27 |
g.add_argument('-k', '--key-file', |
| 28 |
help="Use specific key file (default is to autodetect).") |
| 29 |
|
| 30 |
args = p.parse_args(args) |
| 31 |
|
| 32 |
if not args.browser and (args.cookie_file or args.key_file): |
| 33 |
p.error("Must specify a specific browser with --cookie-file or --key-file arguments") |
| 34 |
|
| 35 |
return p, args |
| 36 |
|
| 37 |
|
| 38 |
def main(args=None): |
| 39 |
p, args = parse_args(args) |
| 40 |
|
| 41 |
try: |
| 42 |
if args.browser: |
| 43 |
cj = args.browser(cookie_file=args.cookie_file, key_file=args.key_file) |
| 44 |
else: |
| 45 |
cj = browser_cookie3.load() |
| 46 |
except browser_cookie3.BrowserCookieError as e: |
| 47 |
p.error(e.args[0]) |
| 48 |
|
| 49 |
for cookie in cj: |
| 50 |
if cookie.domain in (args.domain, '.' + args.domain) and cookie.name == args.name: |
| 51 |
if not args.json: |
| 52 |
print(cookie.value) |
| 53 |
else: |
| 54 |
print(json.dumps({k: v for k, v in vars(cookie).items() |
| 55 |
if v is not None and (k, v) != ('_rest', {})})) |
| 56 |
break |
| 57 |
else: |
| 58 |
raise SystemExit(1) |
| 59 |
|
| 60 |
|
| 61 |
if __name__ == '__main__': |
| 62 |
main() |