3

当密码在外部文件中保护时,我正在尝试使用带有安全凭据的 WinSCP .NET 程序集。

# Load WinSCP .NET assembly
Add-Type -Path "D:\WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp

# Env
$sessionOptions.HostName = "blabla.com"
$sessionOptions.UserName = "UUUU"
#$sessionOptions.Password = "PPPP"
$sessionOptions.SshHostKeyFingerprint = "XXXXXXXXX"
$remotePath = "/home/UUUU/"

使用硬编码密码其工作。如果我想使用安全字符串作为密码,我应该怎么做?

我试过了:

read-host -assecurestring | convertfrom-securestring | out-file D:\securestring.txt

将安全密码保存在文件中。然后,在我的脚本中,我将其取回:

$sessionOptions.Password = get-Content D:\securestring.txt | convertto-securestring

$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $sessionOptions.UserName, $sessionOptions.Password}

但它不工作...

4

3 回答 3

4

自 WinSCP 5.7 起,程序集接受SecureString使用SessionOptions.SecurePassword.

请参阅https://winscp.net/eng/docs/library_sessionoptions

感谢您对这一改进的启发。

虽然程序集将密码加密保存在内存中,但最终仍需要对其进行解密。限制解密密码内部副本的改进正在等待中。

于 2014-10-09T13:17:01.193 回答
3

正如@Matt指出的那样,WinSCP .Net 程序集不接受安全字符串或凭据对象。您需要将密码作为明文字符串传递。但是,您可以将安全字符串存储在文件中:

Read-Host 'Enter password' -AsSecureString |
  ConvertFrom-SecureString |
  Out-File 'C:\password.txt'

并在从文件中读取密码后,使用PSCredential对象从安全字符串中检索解密密码:

$un   = 'username'
$pw   = Get-Content 'C:\password.txt' | ConvertTo-SecureString
$cred = New-Object Management.Automation.PSCredential $un, $pw

try {
  Add-Type -Path 'WinSCPnet.dll'

  $opt = New-Object WinSCP.SessionOptions
  $opt.Protocol = [WinSCP.Protocol]::Sftp
  $opt.HostName = 'example.org'
  $opt.UserName = $cred.UserName
  $opt.Password = $cred.GetNetworkCredential().Password
  $opt.SshHostKeyFingerprint = 'ssh-rsa 2048 ...'

  $sftp = New-Object WinSCP.Session

  $sftp.Open($opt)
  ...
} catch {
  ...
} finally {
  if ($sftp) { $sftp.Dispose() }
}

WinSCP 示例代码取自文档

但请注意,密码必须由运行 SFTP PowerShell 脚本的同一用户保存,因为加密密钥源自该用户的密码。

于 2014-10-05T15:58:36.387 回答
1

According to WinSCP the password property just supports a string. So trying to pass a secure string will not work. If you really want to store the password in a file, you could attempt to store it as the secure string but that is a really bad idea in general since it can be unsecured just as easily (Also not sure if it is possible). I recommend the following option.

# Only stored in memory which is safer.
$sessionOptions.Password = read-host

If you have your heart set on something else you could try this. Just know for previous reasons I do not condone this. Also i have to see if it even works because it looks like you cant output securestring to file.

read-host | out-file D:\securestring.txt
$sessionOptions.Password = get-Content D:\securestring.txt

Ansgar's explains what I didn't know was possible. You can stored the secure string in a file and use it elsewhere.

于 2014-10-05T12:39:50.430 回答