Skip to content

Instantly share code, notes, and snippets.

@acdha
Created February 9, 2012 20:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdha/1782978 to your computer and use it in GitHub Desktop.
Save acdha/1782978 to your computer and use it in GitHub Desktop.
Simple Python function for storing passwords in the Keychain portably
from subprocess import call, Popen, PIPE
from getpass import getpass
import sys
def keychain_wrapper(func):
@wraps(func)
def wrapper(service_name, username):
p = Popen(['security', 'find-internet-password', '-g', '-s', service_name, '-a', username],
shell=False, stdout=PIPE, stderr=PIPE)
rc = p.wait()
if rc == 0:
# Security prints the password to stderr for some crazy reason:
for i in p.communicate()[1].split("\n"):
if i.startswith("password:"):
return i.split(":")[1].strip().strip('"')
pw = getpass("Password for user %s at %s: " % (username, service_name))
rc = call(['security', 'add-internet-password', '-s', service_name, '-a', username, '-w', pw])
if rc != 0:
print("Unable to save password to Keychain!", file=sys.stderr)
return pw
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment