【问题标题】:PowerShell v1 Script Prompting for PasswordPowerShell v1 脚本提示输入密码
【发布时间】:2013-04-12 10:19:00
【问题描述】:

我正在尝试将远程服务器身份验证添加到 PS1 批处理文件脚本。

所以我可以这样做:

Copy-Item  $src $destination -Credential $Creds

我创建了一个密码文件,目前它与脚本位于同一目录中。它只包含密码字符串。

导致提示的行:

  Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File password.txt

当我删除 Read-Host 命令时,提示消失,脚本按预期执行。

问题 进行远程服务器身份验证的正确方法是什么?

这是脚本上下文中的新代码:

[...]

  if(-not(Test-Path $destination)){mkdir $destination | out-null}

  Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File password.txt
  $PW = Get-Content password.txt | ConvertTo-Securestring
  $Creds = New-Object -Typename System.Management.Automation.PSCredential -Argumentlist "SERVER02\Administrator",$PW

ForEach ($sourcefile In $(Get-ChildItem $source | Where-Object { $_.Name -match "Daily_Reviews\[\d{1,12}-\d{1,12}\].journal" }))
{ 

      [...]

      Copy-Item  $src $destination -Credential $Creds

      [...]

}

【问题讨论】:

  • 您是否尝试在没有提示的情况下读取密码?还是您使用的身份验证不起作用?

标签: windows powershell


【解决方案1】:

如果您不担心密码文件在机器之间的可移植性,您可以使用这种相当安全的方法:

# Capture once and store to file - DON'T PUT THIS PART IN YOUR SCRIPT
$passwd = Read-Host "Enter password" -AsSecureString
$encpwd = ConvertFrom-SecureString $passwd
$encpwd
$encpwd > $path\password.bin

# Later pull this in and restore to a secure string
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd

$cred = new-object System.Management.Automation.PSCredential 'john',$passwd
$cred

# NOTE: The "secret" required to rehyrdate correctly is stored in DPAPI - consequence:
#       You can only rehydrate on the same machine that did the ConvertFrom-SecureString

如果您需要调试它以查看 $passwd 是否正确,您可以在调试时执行:

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd)
$str =  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$str

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2012-04-28
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多