我正在编写一个访问钥匙串(keychain)的 Bash 命令行工具,以模拟网络浏览器与网页进行通信。
从那里获取存储在钥匙串(keychain)中的密码非常简单:
PASSWORD=`security find-internet-password -gs accounts.google.com -w`
但是提取电子邮件地址有点棘手,因为您为此获得的最具体的命令会返回大量信息:
$security find-internet-password -gs accounts.google.com
/Users/me/Library/Keychains/login.keychain"
class: "inet"
attributes:
0x00000007 <blob>="accounts.google.com"
0x00000008 <blob>=<NULL>
"acct"<blob>="my-email-address@gmail.com"
"atyp"<blob>="form"
"cdat"<timedate>=0x32303135303333303134333533315A00 "20150330143531Z\000"
"crtr"<uint32>="rimZ"
"cusi"<sint32>=<NULL>
"desc"<blob>=<NULL>
"icmt"<blob>=<NULL>
"invi"<sint32>=<NULL>
"mdat"<timedate>=0x32303135303333303134333533315A00 "20150330143531Z\000"
"nega"<sint32>=<NULL>
"path"<blob>="/ServiceLogin"
"port"<uint32>=0x00000000
"prot"<blob>=<NULL>
"ptcl"<uint32>="htps"
"scrp"<sint32>=<NULL>
"sdmn"<blob>=<NULL>
"srvr"<blob>="accounts.google.com"
"type"<uint32>=<NULL>
password: "my-password"
如何从以 "acct"<blob>=
开头的行中提取帐户电子邮件地址并将其存储到一个名为 EMAIL
的变量中?
最佳答案
如果您使用多个 grep
, cut
, sed
, 和 awk
语句,您通常可以用单个 awk
替换它们.
PASSWORD=$(security find-internet-password -gs accounts.google.com -w)
EMAIL=$(awk -F\" '/acct"<blob>/ {print $4}'<<<$PASSWORD)
这在单行上可能更容易,但我无法获得 security
命令打印出像你这样的输出以测试它。另外,在 StackOverflow 上显示有点长:
EMAIL=$(security find-internet-password -gs accounts.google.com -w | awk -F\" '/acct"<blob>/ {print $4}')
/acct"<blob>/
是正则表达式。这个特别awk
命令行将过滤掉匹配此正则表达式的行。 -F\"
将输出除以给定的字段。在您的行中,字段变为:
- 行前的空格。
-
acct
-
<blob>
-
my-email-address@gmail.com
- 空字段
{print $4}
说要打印出第四个字段。
顺便说一句,通常使用$(....)
会更好而不是 Shell 脚本中的反引号。 $( ... )
更容易看到,您可以在主命令之前包含要执行的子命令:
foo=$(ls $(find . -name "*.txt"))
关于macos - 命令行访问 OS X 的钥匙串(keychain) - 如何获取与帐户关联的电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540323/