> For the complete documentation index, see [llms.txt](https://docs.keeper.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keeper.io/keeperpam/jp/commander-cli/commander-installation-setup/python-developer-setup/commander-cli-as-sdk.md).

# SDKとしてのコマンダーCLI

## インストール <a href="#installation" id="installation"></a>

以下は、Pythonの仮想環境で依存関係を分離しつつ、ソースコードからコマンダーを開発・テストする手順です。コマンダーCLIはライブラリとして利用することも、必要に応じてCLIのソースコードをカスタマイズすることも可能です。

### コマンダーリポジトリをクローンする <a href="#clone-the-commander-repository" id="clone-the-commander-repository"></a>

[Keeper-Security/Commander](https://github.com/Keeper-Security/Commander)のGitHubリポジトリをローカルマシンにクローンします。

```
git clone https://github.com/Keeper-Security/Commander
cd Commander
```

「master」ブランチは本番リリースと同期されます。「release」ブランチは今後のリリースに対応しています。任意で「release」ブランチに切り替えるには、以下を実行します。

```
git checkout release
```

### **Pythonをインストールする** <a href="#install-python" id="install-python"></a>

[python.org](https://www.python.org/)から最新のPython3をインストールします。

### 仮想環境を作成して有効にする <a href="#create-and-activate-virtual-environment" id="create-and-activate-virtual-environment"></a>

{% tabs %}
{% tab title="macOS / Linux" %}

```
python3 -m venv venv
source venv/bin/activate
```

{% endtab %}

{% tab title="Windows" %}

```
python -m venv venv
.\venv\Scripts\activate
```

{% endtab %}
{% endtabs %}

### 依存関係をインストールし、開発モードでセットアップする <a href="#install-dependencies-and-set-up-in-dev-mode" id="install-dependencies-and-set-up-in-dev-mode"></a>

```
pip install -r requirements.txt
pip install -e .
```

#### オプションのメール依存関係 <a href="#optional-email-dependencies" id="optional-email-dependencies"></a>

OAuth、SendGrid、AWS SES などのメールプロバイダーに対応するには、以下のオプション依存関係をインストールします。

```
pip install -e '.[email]'
```

### **セットアップ完了** <a href="#setup-complete" id="setup-complete"></a>

コマンダーCLIを起動できるようになりました。

```
keeper shell
```

認証プロセスの詳細については[ログイン](/keeperpam/jp/commander-cli/commander-installation-setup/logging-in.md)のページをご参照ください。[利用できるコマンド](/keeperpam/jp/commander-cli/command-reference.md)のページもあわせてご確認ください。

***

## Pythonコード <a href="#python-code" id="python-code"></a>

### 認証 <a href="#authentication" id="authentication"></a>

SDKを使ってKeeperコマンダーにサインインするには、主に2つの方法があります。

**手動認証:** ユーザー名を入力すると、コマンダーからログインプロンプトが表示されます。ユーザーが認証を完了すると、プログラムの処理が続行されます。

```python
from keepercommander.params import KeeperParams
from keepercommander import api

params = KeeperParams()
params.user = input('User email: ')
api.login(params) # Initiates login prompts
api.sync_down(params)
```

**自動認証:** [ログイン状態維持の構成を作成](/keeperpam/jp/commander-cli/commander-installation-setup/configuration/configuration.md#creating-a-persistent-login-config)した際に生成された `config.json` ファイルを使用します。設定ファイルが有効であれば、プログラムはコマンダーにプロンプトなしでサインインします。設定ファイルが無効または期限切れの場合は、ログインプロンプトに戻ります。

```python
from keepercommander.__main__ import get_params_from_config

params = get_params_from_config("{{path_to_config_file}}")
```

***

### ボルト操作 <a href="#vault-usage" id="vault-usage"></a>

Pythonスクリプト内でbash形式の[CLIコマンド](/keeperpam/jp/commander-cli/command-reference.md)を直接実行するには、`keepercommander` ライブラリの `cli` パッケージをインポートし、`do_command` 関数を使用します。

```python
from keepercommander.__main__ import get_params_from_config
from keepercommander import cli

# Login
params = get_params_from_config("{{path_to_config_file}}")

# Execute command
cli.do_command(params, "{{cli_command}}")
```

`do_command` 関数は、単独のCLIコマンドを実行するときに便利です。`api.login()` や `api.sync_down()` を使わずに実行することもできますが、戻り値は取得できません。Python内でオブジェクトを直接取得する用途には向きません。

戻り値を返すPython関数は、[keepercommanderモジュール](https://github.com/Keeper-Security/Commander/tree/master/keepercommander)配下にあり、利用前に `api.login()` と `api.sync_down()` の実行が必要です。[api.pyパッケージ](https://github.com/Keeper-Security/Commander/blob/master/keepercommander/api.py)にも便利な関数が多く、以下の例ではその一部を紹介します。

```python
from keepercommander.__main__ import get_params_from_config
from keepercommander import api

# Login
params = get_params_from_config("{{path_to_config_file}}")
api.login(params)
api.sync_down(params)

# Search shared folder
shared_folder_name = 'Example Shared Folder'
folder_search = api.search_shared_folders(params, shared_folder_name)

# Get full record dictionaries if folder exists
keeper_folder = None
if folder_search:
    keeper_folder = folder_search[0]
    for record in keeper_folder.records:
        record_obj = api.get_record(params, record["record_uid"])
        print(record_obj.to_dictionary())
else:
    print('No folder found')
```

***

### エンタープライズ利用 <a href="#enterprise-usage" id="enterprise-usage"></a>

エンタープライズデータへのアクセスには、あらかじめ `api.query_enterprise()` で `params.enterprise` を設定する必要があります。未設定の場合はデータは取得されません。以下のプログラムは、`audit-report` コマンドのJSON出力をPython内で直接取得する例です。

```python
from keepercommander.__main__ import get_params_from_config
from keepercommander import api
from keepercommander.commands.aram import AuditReportCommand

from json import loads

# Login
params = get_params_from_config("{{path_to_config_file}}")
api.login(params)
api.sync_down(params)

api.query_enterprise(params) # Populate enterprise

# Get JSON report directly in Python
kwargs = {
    'report_type':'raw', 
    'format':'json',
    'limit':-1,
    'aggregate':['occurences']
}
command_class = AuditReportCommand()
command_run = command_class.execute(params, **kwargs)
report = loads(command_run)
```

***

### バルクコマンドスクリプト <a href="#bulk-command-script" id="bulk-command-script"></a>

コマンダースクリプトの一般的な活用事例のひとつは、フォルダ内のすべてのレコードに対してコマンドを一括実行することです。

以下のスクリプトは、共有フォルダ・個人用フォルダ・ネストされたフォルダから対象を指定し、フォルダ内の各レコードにコマンド (デフォルトは `get`) を一括実行します。直接の子レコードだけを対象にするか、子孫レコードまで再帰的に対象にするかを選べます。

スクリプト末尾のコマンドを置き換えて実行すると、選択したフォルダ内のすべてのレコードに対してコマンドを実行できます。

{% code overflow="wrap" %}

```python
from keepercommander.params import KeeperParams
from keepercommander import api, cli
from keepercommander.subfolder import get_contained_record_uids

# Login
params = KeeperParams()
params.user = input('User email: ')
api.login(params)
api.sync_down(params)

# Basic CLI to collect folders
folder_list = []
folders_complete = False
while not folders_complete:
    folder_prompt = input('Enter a shared folder name / UID (enter / if all shared folders added): ')
    if folder_prompt == '/':
        # Deduplicate
        folder_list = list(set(folder_list))
        print(folder_list)
        confirm = input('Are all these folder names valid? (y/n) ')
        if confirm.lower() == 'y':
            folders_complete = True
        elif confirm.lower() == 'n':
            print('Restarting...')
            folder_list = []
        else:
            print('Wrong input')
    else:
        folder_list.append(folder_prompt)
recursive_complete = False
# Basic CLI to enable/disable recursive execution
while not recursive_complete:
    recursive_input = input('Only execute commands for direct children records (y/n)? ')
    if recursive_input.lower() == 'n':
        children_only = False
        recursive_complete = True
    elif recursive_input.lower() == 'y':
        children_only = True
        recursive_complete = True

# Iterate through collected folder names
keeper_folders = {params.folder_cache[x].name:x for x in params.folder_cache}
selected_folder_uids = []
for folder in folder_list:
    # entry is a UID
    if folder in params.folder_cache:
        selected_folder_uids.append(folder)
    # entry is a name
    elif folder in keeper_folders:
        selected_folder_uids.append(keeper_folders[folder])
    # entry not found
    else:
        print(f'No folder found for {folder}')
    
# Enumerate folder content
record_uids = []
for uid in selected_folder_uids:
    content = get_contained_record_uids(params, uid, children_only)
    for folder in content:
        record_uids += [x for x in content[folder]]
# Deduplicate
record_uids = list(set(record_uids))

# Run bulk command
for uid in record_uids:
    cli.do_command(params,f'get {uid}') # <-- Replace with your command
```

{% endcode %}

***

コマンダーCLIの内部クラスや関数を活用すれば、CLIの全機能を利用できます。レコードの検索、チームの作成、フォルダの共有などの例を含むスタンドアロンPythonスクリプトは[こちら](https://github.com/Keeper-Security/Commander/tree/master/examples)で確認できます。<br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.keeper.io/keeperpam/jp/commander-cli/commander-installation-setup/python-developer-setup/commander-cli-as-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
