forked from liyanage/macosx-shell-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keychain_password.py
52 lines (40 loc) · 1.58 KB
/
keychain_password.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import subprocess, re
class KeychainPassword:
@classmethod
def find_internet_password(cls, username, host=None):
cmd = ['security', 'find-internet-password', '-g', '-a', username]
if host:
cmd.extend(['-s', host])
credentials = cls.run_security_command(cmd)
if not credentials:
return None
username, password = credentials
return password
@classmethod
def find_generic_password(cls, username, label=None):
credentials = cls.find_generic_username_and_password(username=username, label=label)
if not credentials:
return None
username, password = credentials
return password
@classmethod
def find_generic_username_and_password(cls, username=None, label=None):
cmd = ['security', 'find-generic-password', '-g']
if label:
cmd.extend(['-l', label])
if username:
cmd.extend(['-a', username])
return cls.run_security_command(cmd)
@classmethod
def run_security_command(cls, cmd):
try:
security_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except:
return None
result = re.findall('password: (?:0x([A-Z0-9]+)\s+)?"(.*?)"$.*"acct"<blob>="(.*?)"$', security_output, re.DOTALL|re.MULTILINE)
if not result:
return None
(hexpassword, password, username), = result
if hexpassword:
password = hexpassword.decode('hex').decode('utf-8')
return username, password