【问题标题】:Invoke SQL Command with Secure Creds使用安全凭据调用 SQL 命令
【发布时间】:2016-02-04 12:13:16
【问题描述】:

我对如何在 Powershell 命令中使用安全字符串来运行远程 SQL 查询有点卡住。

以下命令可以在 powershell 中运行,因为它是在我自己的帐户下运行的——它在提供用户名和密码的值时也会返回结果。

 "SELECT COUNT(E.intEmployeeID) AS Count FROM Employees E WITH(NOLOCK)" -       ServerInstance "SERVERA\INSTANCEA" -Database "DATABASEA" -u USER1 -p SomePassword

我想自动化/安排这个脚本,因为我不想在我的脚本中使用明文 txt 中的密码,所以我正在寻找使其成为安全/加密字符串的方法。因此,我使用以下内容创建了加密密码。问题是我不确定如何将此密码传回我的命令中。..

这将创建加密字符串并存储在文件中。这将是一个远程保护的文件。

$File = "C:\password.txt"
[Byte[]] $Key = (1..16)
$Password = "SomePassword" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $Key | Out-File $File

这将读取加密文件并存储在安全字符串中...但是我如何让我的 Invoke SQL 命令使用此密码。

$File = "C:\Cred.txt"
[Byte[]] $Key = (1..16)
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key

$Password 的值是 System.Security.SecureString,如果我在原始命令中使用此变量,命令将失败并显示“用户登录失败”

用于执行 SQL 查询的帐户是经过 SQL 身份验证的帐户,而不是域帐户..

欢迎任何建议 谢谢。

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0


    【解决方案1】:

    创建凭据对象:

    $cred = new-object -typeName System.Management.Automation.PSCredential -ArgumentList $user, $pass
    

    然后,将密码转换为纯文本:

    [string]$pass = $cred.GetNetworkCredential().Password
    invoke-sqlcmd -UserName $user -Password $pass -Query 'select @@servername'
    

    Ivoke-SqlCmd 只能使用纯文本密码。

    【讨论】:

    • 使用这种方法你会失去安全字符串的安全性
    • Microsoft 应该真正纠正这个问题并允许“Invoke-SQLCmd”接受 Secure-String 对象。这太荒谬了。
    【解决方案2】:

    可以使用安全字符串而不将纯文本存储在变量中。这是一个例子。

    $Server = Read-Host "Server"
    $Database = Read-Host "Database"
    $Username = Read-Host "User"
    $Password = Read-Host "password for user $Username on $Server" -AsSecureString
    
    Invoke-Sqlcmd -Database $Database -ServerInstance $Server -Verbose -Username $Username -Password (New-Object PSCredential "userDummy", $Password).GetNetworkCredential().Password -Query "SELECT table_catalog [database], table_schema [schema], table_name name, table_type type FROM INFORMATION_SCHEMA.TABLES GO"
    

    【讨论】:

    • 如果您正在使用 Invoke-Sqlcmd,可以这样做吗?
    猜你喜欢
    • 1970-01-01
    • 2017-01-31
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多