SSHを使用したPowerShellの例

Windowsスケジュールタスクの「Log on as」認証情報を更新するためのPAMスクリプト

このスクリプトを実行するには、Keeperゲートウェイホストシステムと対象システム間でSSH鍵ベースの認証を設定し、有効化する必要があります。鍵ペア認証をまだ設定していない場合は、以下のURLをご確認ください。

概要

以下のPowerShellコード例では、PowerShell 7を使用して確立したSSHセッションにおいてKeeper ローテーションでパスワードをローテーションした後、Windowsスケジュールタスクの「Log on as」認証情報を更新します。

この例では、確立された「SSH」セッションを介してWindowsベースのターゲットシステムに接続し、PowerShell 7のネイティブコマンドレットを使用してスケジュールタスクを管理します。この場合、「Microsoft.PowerShell.Management」とそのサブコマンド (「Get-Service」や「Set-Service」など) を使用して、ターゲット「Windowsスケジュールタスク」の「Log on as」認証情報を管理します。

手順 1

以下のPowerShellスクリプトを開いてコピーし、任意のファイル名で「.ps1」として保存します。この例では、スクリプトのファイル名を「rotate_service_cred.ps1」としました。このスクリプトをPAMユーザーレコードの「PAMスクリプト」セクションに添付します。

さらに、現在のPAMユーザーレコードを選択して、「ローテーションクレデンシャル」レコードを1つ含めます。「コマンドプレフィックスで実行」のチェックボックスをオンにし、PowerShell 7の実行ファイルのパスを指定してください (必須)。

Invoke-Commandを使用したPowerShellスクリプト (SSHを利用)
[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline=$true)]
    [string]
    $Record
)

try {
    # このセクションでは、PAMユーザーレコードの情報を取り込みます。
    Write-Debug "Decoding and converting the PAM User Record Information from Base64"
    $RecordJsonAsB64 = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Record))
    
    if (-not $RecordJsonAsB64) {
        throw "Failed to decode the PAM User Record Information from Base64."
    }

    Write-Debug "Converting the decoded JSON to PowerShell object"
    $RecordParams = $RecordJsonAsB64 | ConvertFrom-Json

    if (-not $RecordParams) {
        throw "Failed to convert the decoded JSON to PowerShell object."
    }
    Write-Debug "PAM User Record Information successfully retrieved and converted."
}
catch {
    Write-Error "An error occurred while processing the PAM User Record Information: $_"
}
finally {
    Write-Debug "Completed processing the PAM User Record Information."
}
# セクションの終了


try {
    # このセクションでは、すべての関連レコードとそのパラメータ情報を取り込みます。
    Write-Debug "Decoding and converting all associated records from Base64"
    $recordsJSON = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($RecordParams.records))
    
    if (-not $recordsJSON) {
        throw "Failed to decode the associated records from Base64."
    }

    Write-Debug "Converting the decoded JSON to PowerShell object"
    $records = $recordsJSON | ConvertFrom-Json

    if (-not $records) {
        throw "Failed to convert the decoded JSON to PowerShell object."
    }
    Write-Debug "Associated records successfully retrieved and converted."
}
catch {
    Write-Error "An error occurred while processing the associated records: $_"
}
finally {
    Write-Debug "Completed processing the associated records."
}
# セクションの終了


try {
    # このセクションでは、ユーザーレコードからパラメータを定義します。「remotecomp」と「service」は、PAMユーザーレコードのカスタムフィールドから取得されます。
    Write-Debug "Defining parameters from the User Record"
    $ErrorActionPreference = 'Stop'
    $DebugPreference = 'Continue'
    
    $remoteComputer = ($records | Where-Object {$_.uid -eq $RecordParams.userRecordUid}).remotecomp
    if (-not $remoteComputer) {
        throw "Failed to retrieve 'remotecomp' from the User Record."
    }
    
    $serviceName = ($records | Where-Object {$_.uid -eq $RecordParams.userRecordUid}).service
    if (-not $serviceName) {
        throw "Failed to retrieve 'service' from the User Record."
    }

    $user = ($RecordParams.user)
    if (-not $user) {
        throw "Failed to retrieve 'user' from the User Record."
    }

    $newPassword = ($RecordParams.newPassword)
    if (-not $newPassword) {
        throw "Failed to retrieve 'newPassword' from the User Record."
    }

    Write-Debug "Parameters from the User Record successfully defined."
}
catch {
    Write-Error "An error occurred while defining parameters from the User Record: $_"
}
finally {
    Write-Debug "Completed defining parameters from the User Record."
}
# セクションの終了


    try {
        # このセクションでは、AD管理リソースレコードを使用して新しいPSSessionを作成します。d
        Write-Debug "Creating a new SSH Session with the AD Administrative Resource Record"
        $session = New-PSSession -HostName $remoteComputer -UserName $user -ErrorAction Stop
    
        if (-not $session) {
            throw "Failed to create a new SSH Session."
        }
        Write-Debug "SSH Session created successfully."
    }
    catch {
        Write-Error "An error occurred while creating the SSH Session: $_"
    }
    finally {
        Write-Debug "Completed the attempt to create a new SSH Session."
    }
    # セクションの終了

try {
    # このスクリプトブロックでは、指定されたスケジュールされたタスクのパスワードを更新します。
    Write-Debug "Updating the password for the scheduled task: $taskName"
    
    $result = Invoke-Command -Session $session -ScriptBlock {
        param ($taskName, $user, $newPassword)
        
        try {
            Write-Debug "Setting the new password for scheduled task: $taskName"
            Set-ScheduledTask -TaskName "$taskName" -User "$user" -Password "$newPassword" -ErrorAction Stop
            Write-Output "Password for scheduled task $taskName has been updated successfully."
        }
        catch {
            Write-Error "An error occurred while updating the password for scheduled task "$taskName": $_"
            throw $_
        }
    } -ArgumentList $taskName, $user, $newPassword -ErrorAction Stop
    
    Write-Debug "Result of the remote command: $result"
}
catch {
    Write-Error "An error occurred while updating the password for the scheduled task on the remote computer: $_"
}
finally {
    Write-Debug "Completed attempt to update the password for the scheduled task on the remote computer."
}
        # スクリプトブロックの終了

# SSHセッションを削除します。
Remove-PSSession -Session $session
# セクションの終了

以下は結果として得られるPAMスクリプト設定画面です。

PAMスクリプト設定

手順 2

PAMユーザーレコードに「remotecomp」と「taskname」という2つのカスタムテキストフィールドを追加します。「remotecomp」フィールドには、Windowsスケジュールタスクを実行しているターゲットシステムのDNS名を入力します。この例では、「dc1」がターゲットシステムの名前となります。管理しているWindowsスケジュールタスクがKeeperゲートウェイホストに対してローカルである場合は、「remotecomp」フィールドに「localhost」を使用します。「taskname」フィールドには、タスクの「Windows Scheduled Task」の名前を入力します (「Display Name」ではありません)。この例では、「Task Name」は「AutoSSH」となります。

以下は、結果として得られるボルト内のレコード設定となります。

レコード設定

スクリプトの実行

手順に従うと、Keeperのパスワードローテーションと同様に、[ローテーションする]ボタンを使用して、スクリプトを「オンデマンド」で実行してテストできます。また、「パスワードローテーション設定」でスクリプトのスケジュールを設定することもできます。

最終更新