なっく日報

技術やら生活やらのメモ

コマンド一発でMacのkeychainに登録されているパスワードを取得する

自分向けにメモ

パスワードの登録

security add-generic-password -a ACCOUNT_NAME -w PASSWORD -s SERVICE_NAME

でKeychainにパスワードが登録できます。

各オプションの意味は以下の通り

    -a  Specify account name (required) # そのサービスで使っているアカウント
    -s  Specify service name (required) # サービス名
    -w  Specify password to be added # パスワード

パスワードの取得

security find-generic-password -a ACCOUNT_NAME -s SERVICE_NAME -w

でアカウントとサービス名を指定してKeychainのパスワードが取得できます。

各オプションの意味は以下の通り

    -a  Match "account" string # アカウント
    -s  Match "service" string # サービス名
    -w  Display only the password on stdout # パスワードだけ標準出力に表示

シェルスクリプト等で

#!/bin/bash
PASSWORD=$(security find-generic-password -a ACCOUNT_NAME -s SERVICE_NAME -w)

な感じで取得すれば、いろいろ捗りそうですね!

なお、Keychainをロックするまではノンパスで使えちゃうのでセキュリティ的には別途気をつけるようにしましょう (Keychainが自動的にロックされるかは不明)