2014-10-05 88 views
2

我想使用WinSCP .NET程序集与安全证书,当密码保护在外部文件中。PowerShell使用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/" 

用硬编码密码,它的工作。如果我想使用securestring作为密码,我该怎么做?

我想:

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} 

但它不工作...

回答

1

根据WinSCP密码属性只是支持的字符串。所以试图通过一个安全的字符串将无法正常工作。如果你确实想要将密码存储在一个文件中,你可以尝试将它作为安全字符串存储,但这通常是一个really bad idea,因为它可以非常容易(也不确定是否可能)不安全。我推荐以下选项。

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

如果你对别的东西有你的心,你可以试试这个。只知道以前的原因我不要宽恕这一点。另外我必须看看它是否可以工作,因为它看起来像你不能输出securestring文件。

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

Ansgar's解释了我不知道是可能的。您可以将安全字符串存储在一个文件中并在其他地方使用。

+0

WinSCP .NET程序集已经支持'SecureString',请参见[我的答案](http://stackoverflow.com/a/26279430/850848)。 – 2015-06-02 20:21:09

2

由于@Matt指出,WinSCP .Net程序集不接受安全字符串或凭证对象。您需要将密码作为纯文本字符串传递。您可以将secure string存储在一个文件中,虽然:

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示例代码取自documentation

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

+0

WinSCP .NET程序集已经支持'SecureString',请参阅[我的答案](http://stackoverflow.com/a/26279430/850848)。 – 2015-06-02 20:21:03

+0

在添加'SecureString'支持之前,我没有写过答案。 ;)非常感谢你的工作,顺便说一句。 – 2015-06-02 20:26:06

+0

我知道这就是为什么我写“已经”:) – 2015-06-02 20:39:07

相关问题