【问题标题】:Can I change the server administrator password using PowerShell SecureString?我可以使用 PowerShell SecureString 更改服务器管理员密码吗?
【发布时间】:2013-01-22 08:50:22
【问题描述】:

我正在寻找编写一个脚本,该脚本将使用 PowerShell 更改远程服务器上的管理员密码。以下命令将执行此操作

$Admin=[adsi]("WinNT://" + MyServer + "/Administrator, user")
$Admin.SetPassword("NewPassword")

但我希望能够在脚本中隐藏"NewPassword" 以使其更安全。

那么有没有办法将"NewPassword" 保存到安全的 .txt 文件中,然后就可以像这样使用它了?

$Admin.SetPassword("$secureFile")

脚本将作为计划任务运行。

【问题讨论】:

    标签: powershell passwords powershell-2.0 securestring


    【解决方案1】:

    是的,您可以使用ConvertTo-SecureStringConvertFrom-SecureString cmdlet 对密码进行加密,然后再将其保存到磁盘上的文件中。

    但是,请记住,您需要一个加密密钥才能使用 cmdlet 加密/解密密码。来自the documentation

    如果使用KeySecureKey 指定加密密钥 参数,高级加密标准 (AES) 加密 使用算法。指定键的长度必须为 128、192、 或 256 位,因为这些是 AES 支持的密钥长度 加密算法。

    如果您未指定密钥,则将使用 Windows 数据保护 API (DPAPI) 进行加密。这意味着密钥将绑定到调用 cmdlet 的用户帐户。现在,如果您将脚本作为计划作业运行,则此解决方案可以正常工作。

    这里有几个脚本将使用生成的密钥将加密密码保存并读取到磁盘上的 XML 文件中:

    function Get-SecurePassword {
    <#
    .Synopsis
        Gets a password stored securely in an XML file.
    .Parameter Path
        The path to the XML file to import the password from.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Position=1)]
        [string]$Path = "Password.xml"
    )
        if (Test-Path $Path) {
            $cache = Import-Clixml $Path
            $key = [System.Convert]::FromBase64String($cache.Secret)
            $password = $cache.EncryptedPassword | ConvertTo-SecureString -Key $key
            $password
        }
    }
    
    function Set-SecurePassword {
    <#
    .Synopsis
        Stores a password securely in an XML file.
    .Parameter Path
        The path to the XML file to export the password to.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Position=1)]
        [string]$Password,
        [Parameter(Position=2)]
        [string]$Path = "Password.xml"
    )
        $key = New-StrongPasswordBytes -Length 32
        $textualKey = [System.Convert]::ToBase64String($key)
        $securePassword = $Password | ConvertFrom-SecureString -Key $key
        $cache = New-Object PSObject -Property @{ "EncryptedPassword" = $securePassword; "Secret" = $textualKey }
        $cache.PSObject.TypeNames.Insert(0, "SecurePassword")
        $cache | Export-Clixml $Path
    }
    
    function New-StrongPasswordBytes ($length) {
        Add-Type -Assembly System.Web
        $password = [System.Web.Security.Membership]::GeneratePassword($length, $length / 2)
        [System.Text.Encoding]::UTF8.GetBytes($password)
    }
    

    【讨论】:

    • 我认为重要的是要注意这里要保护的密码是模糊的,但任何可以访问 .xml 文件的人仍然可以访问。对 OP 来说足够好的解决方案,但不是特别安全。
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2015-04-19
    • 2021-03-10
    相关资源
    最近更新 更多