-
-
Save droberin/eb8d96e48d3f89d05477a1f133ebff7f to your computer and use it in GitHub Desktop.
Python methods to interact with Mac OS X Keychain
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
import re | |
import os | |
def getpassword(service, account): | |
def decode_hex(s): | |
s = eval('"' + re.sub(r"(..)", r"\x\1", s) + '"') | |
if "" in s: s = s[:s.index("")] | |
return s | |
cmd = ' '.join([ | |
"/usr/bin/security", | |
" find-generic-password", | |
"-g -s '%s' -a '%s'" % (service, account), | |
"2>&1 >/dev/null" | |
]) | |
p = os.popen(cmd) | |
s = p.read() | |
p.close() | |
m = re.match(r"password: (?:0x([0-9A-F]+)\s*)?\"(.*)\"$", s) | |
if m: | |
hexform, stringform = m.groups() | |
if hexform: | |
return decode_hex(hexform) | |
else: | |
return stringform | |
def setpassword(service, account, password): | |
cmd = 'security add-generic-password -U -a %s -s %s -p %s' % (account, service, password) | |
p = os.popen(cmd) | |
s = p.read() | |
p.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment