PowerShellにパスワード文字列を直接書かない手法

PowerShellで用意されているGet-Credential 関連を駆使して、PowerShellスクリプト内に直接パスワードを書かないで済む手法でスクリプトを作成した。

スクリプトを配置したディレクトリにscript.cred というファイルを作り、そこに暗号化されたパスワード文字列を配置する、という仕組み。

1$authfile=$PSScriptRoot+".\script.cred"
2$username="admin" #ユーザ名
3$passwdstr="" # この変数にパスワード文字列が入る。
4if((Test-Path $authfile) -eq $false){
5    $creds = Get-Credential -UserName $username -Message $($username+"ユーザのパスワードを入力してください")
6    $creds.Password | ConvertFrom-SecureString | Set-Content -Path $authfile | Out-Null
7    $passwdstr=[Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($creds.Password))
8}else{
9    $passwdstr=[Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($(Get-Content $authfile | ConvertTo-SecureString)))
10}
11 
12# この段階の $passwdstr には暗号化されていないパスワード文字列が入っている

なお、メモリ上の$passwdstr には暗号化されていない文字列が保存されているため、そこは注意が必要。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StatCounter - Free Web Tracker and Counter