Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active August 29, 2015 14:14
Show Gist options
  • Save jdowner/41f6530ba1d9e86f6729 to your computer and use it in GitHub Desktop.
Save jdowner/41f6530ba1d9e86f6729 to your computer and use it in GitHub Desktop.
Password retrieval from password-store or a custom store.
import collections
import os
import subprocess
class Entry(collections.namedtuple('Entry', 'username, password, url')):
"""
An Entry object represents an entry in the password store.
"""
def __new__(cls, username, password, url=None):
"""Create a new Entry object
Arguments:
username: a username
password: a password
url: a URL associated with the account (optional)
"""
return super(Entry, cls).__new__(cls, username, password, url)
class PasswordStore(object):
def retrieve(self, account):
"""Returns the an entry for the specified account
"""
result = subprocess.check_output("pass {}".format(account), shell=True)
lines = [r.strip() for r in result.splitlines()]
lookup = {}
for line in lines:
try:
key, val = line.split(':', 1)
lookup[key.strip()] = val.strip()
except Exception:
pass
return Entry(
lookup['username'],
lookup['password'],
lookup.get('url', None),
)
class CustomStore(object):
def __init__(self):
self.storedir = os.path.expanduser('~/.password-store')
def retrieve(self, account):
result = subprocess.check_output(
"gpg --use-agent --no-tty -d {}/{}.gpg".format(self.storedir, account),
stderr=subprocess.PIPE,
shell=True,
)
lines = [r.strip() for r in result.splitlines()]
lookup = {}
for line in lines:
try:
key, val = line.split(':', 1)
lookup[key.strip()] = val.strip()
except Exception:
pass
return Entry(
lookup['username'],
lookup['password'],
lookup.get('url', None),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment