macOS でキーチェーンに保存されたパスワードをターミナルで利用する方法

macOS

macOS でキーチェーンに保存されたパスワードをターミナルで利用する方法についてです。

早速結論ですが、 security のサブコマンド find-generic-password を使用することでキーチェーンのに保存されたパスワードを取得できます。

security find-generic-password -s [サービス] -a [アカウント] -w

各オプションの意味:

  • -s: サービス名でマッチ
  • -a: アカウントでマッチ
  • -w: 一連の情報ではなくパスワードのみを出力する

「キーチェーン」アプリで確認できるキー一覧では -sName カラムにあたります。 -a はキー一覧で右クリックメニュー Get Info で詳細を表示したときの Account にあたります。

他のコマンドに渡して利用したいときは $() やパイプを使えば OK です。

other_command $(security find-generic-password -s [サービス] -a [アカウント] -w)

なお、 security find-generic-password のヘルプメッセージは次のようになっています:

❯ security find-generic-password --help
find-generic-password: illegal option -- -
Usage: find-generic-password [-a account] [-s service] [options...] [-g] [keychain...]
    -a  Match "account" string
    -c  Match "creator" (four-character code)
    -C  Match "type" (four-character code)
    -D  Match "kind" string
    -G  Match "value" string (generic attribute)
    -j  Match "comment" string
    -l  Match "label" string
    -s  Match "service" string
    -g  Display the password for the item found
    -w  Display only the password on stdout
If no keychains are specified to search, the default search list is used.
        Find a generic password item.

アバター
後藤隼人 ( ごとうはやと )

ソフトウェア開発やマーケティング支援などをしています。詳しくはこちら