2016-01-17 31 views
0

我想使用Read-Host -AsSecureString来避免在我的脚本中输入密码。我想遍历服务器列表并在密码中包含每个服务器名称 - 因此所有密码都不相同。如果我使用变量将脚本中的密码放入脚本,该脚本将按照我的意愿工作,但如果我使用相同的变量作为Read-Host的值,则脚本无法工作。 Read-Host -AsSecureString可以不包含变量吗?可以读取主机接受一个变量作为输入?

查看下面的代码。当使用$passwordsecure变量(Read-Host值)密码是字面上什么即键入$computername,然而$password(其被注释)产生预期的机器名作为密码的一部分:

<# 
Info: 
- Launch the script and respond to the on-screen prompts: 
    - Enter the local user account housed on the remote servers whose password 
    needs to be changed (e.g. administrator or testUser) 
    - Enter path to txt file containing server list (e.g. E:Temp\servers.txt) 
    - Enter new password 
    - The script will connect to each server and change the password of the local 
    user account defined 
#> 

# Changes PS prompt to directory in which the script is being run from whether using Powershell console or the ISE. 
function Get-ScriptDirectory { 
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value 
    Split-Path $Invocation.MyCommand.Path 
} 

$ISEScriptPath = Split-Path -Parent $psISE.CurrentFile.Fullpath -EA SilentlyContinue 

if ($ISEScriptPath -eq $null) { 
    cd $(Get-ScriptDirectory -ea SilentlyContinue) 
} else { 
    cd $ISEScriptPath 
} 

############## Main Script ########### 

$fail = @() 
$pass = @() 
$passLog = @() 
$failLog = @() 
$date = "_$(get-date -uf %H%M_%d%h%Y)" 
$Results = Test-Path "$PWD\Results" 

if (-not $Results) { 
    md "$PWD\Results" 
} 

$user = Read-Host "Enter local account name whose password is to be changed on remote servers (e.g. testUser)" 

Write-Host "N.B. If the .txt file is located in '$PWD' just enter the filename (e.g. servers.txt)" 
"`n" 
$path = (Read-Host "Enter path to the .txt file containing servers for which the $(($user).toupper()) password will be changed (e.g. e:\temp\servers.txt)") 
$computerNames = Get-Content $path 
$passwordSecure = Read-Host -AsSecureString "Enter new password" 

$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordSecure)) 
#$password = "$($computername)!!" 

foreach ($computername in $computernames) { 
    $date2 = (Get-Date).ToString('dd-MM-yyyy hh:mm:ss tt') 
    $computername 
    $adminUser = [ADSI] "WinNT://$computerName/$user,User" 
    $adminUser.SetPassword($Password) 

    if ($?) { 
     "$computername was successfully updated" 
     $PassLog +="$computername updated successfully at $date2" 
     $Pass+="`n$computername updated successfully" 
     Start-Sleep -m 500 
    } else { 
     "$computername failed to update" 
     $failLog +="$computername failed to update at $date2" 
     $fail+="`n$computername failed to update" 
     Start-Sleep -m 500 
    } 
} 

"$(($fail).count) $(($user).toupper()) password failed to be reset on following servers and needs to be checked manually..`n"; 
Write-Host $fail -ForegroundColor "Red" 

"`n$(($Pass).count) servers had the $(($user).toupper()) account password updated successfully..`n" 
Write-Host $Pass -ForegroundColor "green" 
"`n" 

          "Processing servers provided in $PWD\$path...." | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                    "`n`n" | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
     "Failed to Reset $(($fail).count) $(($user).toupper()) passwords:`n"| Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                    "`n" | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                   $failLog | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                    "`n`n" | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
"Successfully Updated $(($Pass).count) $(($user).toupper()) passwords:`n" | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                    "`n" | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 
                   $passLog | Out-File ("$PWD\Results\" + $("$user"+"_PasswordReset" + $date + ".log")) -Append 

Write-Host "A results file has been created: $PWD\Results\$("$user"+"_PasswordReset" + $date + ".log`n")" -ForegroundColor Yellow 

回答

2

如果您在Read-Host提示处输入变量(例如$computername),您将得到一个文字字符串'$computername'。为了能够扩大字符串中变量,你需要这样的事:

$value = Read-Host 
$ExecutionContext.InvokeCommand.ExpandString($value) 

然而,这只会与普通字符串的工作,而不是与安全的弦。我不会首先推荐它,因为它需要用户知道哪些变量在脚本运行时可用。它也可能导致不希望的副作用,因为如果您输入$computer_some%orOther Powershell将尝试扩展(不存在)变量$computer_some,因为下划线是标识符中的有效字符。您必须将该字符串指定为${computer}_some%orOther。另外,如果您想在密码中输入文字$,该怎么办?你的用户需要知道这个角色必须逃脱。

如果您必须在密码中包含计算机名称(顺便提一下,这不是一个好主意,因为包括已知的事实会降低密码的整体强度),您应该在程序中以代码如下:

$pw = Read-Host -Prompt 'Password' 
$secpw = "$computername$pw" | ConvertTo-SecureString -AsPlainText -Force 

或者(如果必须读取密码作为安全字符串)是这样的:

$readpw = Read-Host -Prompt 'Password' -AsSecureString 
$cred = New-Object Management.Automation.PSCredential ('x', $readpw) 
$pw = $cred.GetNetworkCredential().Password 
$secpw = "$computername$pw" | ConvertTo-SecureString -AsPlainText -Force 
+2

@itchyDon - 除了安斯加尔指出存在的问题,在允许的变量输入允许表达式,比如''password $([datetime] :: now.addhour())“,'whi ch允许命令注入攻击,例如“fakepass $(del c:\ *。* -force)” –

3

否,Read-Host输入是字面处理和变量引用不会自动扩展。

您可以强制字符串扩张,但:

PS> $ExecutionContext.InvokeCommand.ExpandString('$PWD') 
C:\Users\Mathias 

你可以使用Read-Host没有-AsSecureString,在呼叫包裹,上面的函数,然后将其与ConvertTo-SecureString小命令转换为SecureString

PS> $computername = 'Computer123' 
PS> $passwordSecure = ConvertTo-SecureString $ExecutionContext.InvokeCommand.ExpandString($(Read-Host "Input password")) -AsPlainText -Force 
Input password: $($computername)!! 
PS> [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordSecure)) 
Computer123!! 
相关问题