【问题标题】:Hiding password for SQL user in Powershell在 Powershell 中隐藏 SQL 用户的密码
【发布时间】:2016-02-21 09:06:21
【问题描述】:

我正在使用以下脚本在命令行传递 SQL 凭据,但我需要用户输入 SQL 用户的密码而不是其中的 Windows 凭据,并确保密码不会以明文形式显示插入到提示中。这是我的脚本:

Param(
  [Parameter(Mandatory=$True)]
  [ValidateNotNullOrEmpty()]
  [string]$dbusername="",
  [Parameter(Mandatory=$True)]
  [ValidateNotNullOrEmpty()]
  [string]$password="",
  [Parameter(Mandatory=$True)]
  [ValidateNotNullOrEmpty()]
  [string]$Machine=""
  )

这很好用,但我想确保当用户在提示中插入密码时密码是隐藏的。

我是用这条线来做的

Read-Host -Prompt "Enter your password" -AsSecureString

但这不能插入到 Param 块中,我之后插入它没有效果。

当用户在提示符下插入密码时,如何屏蔽密码?

【问题讨论】:

  • 如果你有 PS V3,转换为安全字符串,即:[securestring]$password="" 应该足够了
  • 感谢您的意见。如果我确实按照您提到的那样更改强制转换,则会提示用户在“隐藏模式”下插入我想要的密码,但是我遇到了身份验证错误。也许我应该提到我正在使用一个插入连接字符串的函数。该函数在没有安全字符串的情况下工作得很好。您需要完整的脚本才能看到它吗?
  • [Parameter(Mandatory)][System.Management.Automation.Credential()][PSCredential]$Credential

标签: sql powershell passwords parameter-passing credentials


【解决方案1】:

对于 PS V3,转换为安全字符串,即:[securestring]$password="" 就足够了。 在将它与您的应用程序一起使用之前,您肯定必须将此安全字符串转换回纯文本。这可以通过以下方式完成:

$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$clearpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)

【讨论】:

  • 使用 $clearpassword ?你能回应它并验证它吗?
  • Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string]$dbusername="", [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [securestring]$password="", [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string]$Machine="" )之后我已经插入
  • $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password) $clearpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
  • 是的,但您是否在连接字符串中使用 $clearpasword 而不是 $password ?
  • 密码如我所愿隐藏,但我得到Exception calling "Open" with "0" argument(s): "Login failed for user 'A4_reader'."
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2013-09-18
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多