【问题标题】:Password from SecureString makes the script hangingSecureString 的密码使脚本挂起
【发布时间】:2019-05-09 16:10:28
【问题描述】:
$password = Get-Content 'c:\temp\tmp1\pw.dat' | ConvertTo-SecureString 
& "C:\Program Files\PuTTY\pscp.exe" -P 2222 -pw $password 'c:\temp\tmp1\test.txt' 'root@localhost:/home/root/temp'

上面的代码刚刚挂了;但是,下面的代码有效。

$password='mypw'
& "C:\Program Files\PuTTY\pscp.exe" -P 2222 -pw $password 'c:\temp\tmp1\test.txt' 'root@localhost:/home/root/temp'

有什么建议吗?我不认为我输入了错误的密码,因为我做了几次。此外,如果密码输入错误,我预计会出现错误消息。 顺便说一句,脚本的目的是将文件传输到 linux 机器上。

【问题讨论】:

  • 当您将SecureString 作为命令行参数传递给可执行文件时,您期望会发生什么?那将被替换为SecureString的明文内容? (提示:它没有)
  • @PetSerAl,我明白你的意思。我的目的是保护 linux root 的密码。也许 SecureString 不是正确使用的技术?我承认到目前为止,我在 SecureString 上找到的所有示例代码都是关于使用它来创建凭证对象。如果我走错了路,还有其他方法可以保护密码吗?
  • pw.dat 中的密码是纯文本吗?您也是唯一从同一用户运行此脚本的人吗?
  • @PetSerAl。你所有的问题都是正确的。 pw.dat 文件是从代码读取主机生成的 -AsSecureString | ConvertFrom-SecureString |出档。我的 Windows 登录将一直运行 scipt,无论是手动还是通过计划任务。
  • 好的,我有一个解决方案给你。给我一点时间来写它。

标签: powershell securestring


【解决方案1】:

如评论中所述,.dat 文件是使用

创建的
read-host -AsSecureString | ConvertFrom-SecureString | out-file

所以我知道有两种方法可以做到这一点。

$EncryptedString = read-host -AsSecureString | ConvertFrom-SecureString

$SecureString = $EncryptedString | ConvertTo-SecureString

$Pointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)

$PlainTextPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($Pointer)

$PlainTextPassword

这里的秘密是[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString),它将字符串转换为字节并返回指向它所在位置的指针

下一部分[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($Pointer) 转到指针并将字节转换为字符串。

另一种方法是将安全字符串转换为 PSCredential。

$EncryptedString = read-host -AsSecureString | ConvertFrom-SecureString

$SecureString = $EncryptedString | ConvertTo-SecureString

$PlainTextPassword = ([PsCredential]::new("DoesntMatter",$SecureString)).GetNetworkCredential().Password

$PlainTextPassword

这会将安全字符串转换为 PSCredential,您可以在其中获取 NetworkCredential 的纯文本密码。

【讨论】:

  • [System.Net.NetworkCredential]::new('', (Read-Host -AsSecureString)).Password
猜你喜欢
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 2011-04-05
相关资源
最近更新 更多