Created
February 9, 2012 20:50
-
-
Save acdha/1782978 to your computer and use it in GitHub Desktop.
Simple Python function for storing passwords in the Keychain portably
This file contains 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
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