PowerShell之SFTP下载文件

2/13/2017来源:经验技巧人气:1988

SFTP是一种加密的安全的文件传输协议。通过PowerShell脚本进行SFTP传输相当方便,还可用于定时任务。我们将一些配置项写入到一个xml文件中,通过PowerShell读取xml内容。

下面是download.xml的代码:

<?xml version="1.0" ?> <sftpConfig> <PRotocol>Sftp</Protocol> <HostName>127.0.0.1</HostName> <UserName>admin</UserName> <PassWord>Password</Password> <SshHostKeyFingerprint>ssh-rsa 2048 32:af:45:6b:a0:e5:0d:f3:1e:b0:44:b7:de:ec:77:b3</SshHostKeyFingerprint> <RemotePath>/E/test/path/data/</RemotePath> <LocalPath>e:\test\path\data\</LocalPath> </sftpConfig>

下面是download.ps1脚本的代码:

param ( $xmlData=[xml](Get-Content "E:\test\path\scripts\download.xml"), $localPath = $xmlData.sftpConfig.LocalPath, $remotePath = $xmlData.sftpConfig.RemotePath, $dataFile = (Get-Date).toString("yyyy-MM-dd")+".txt", $flagFile = "flag_"+(Get-Date).toString("yyyyMMdd")+".txt" ) function wait10sec { $step=10 $add=0 $t=(get-date) $step-(($t.Hour*3600+$t.Minute*60+$t.Second)%$step)+$add } try { # Load WinSCP .NET assembly Add-Type -Path "E:\test\path\scripts\WinSCPnet.dll" # Setup session options $sessionOptions = New-Object WinSCP.SessionOptions $sessionOptions.Protocol = [WinSCP.Protocol]$xmlData.sftpConfig.Protocol $sessionOptions.HostName = $xmlData.sftpConfig.HostName $sessionOptions.UserName = $xmlData.sftpConfig.UserName $sessionOptions.Password = $xmlData.sftpConfig.Password $sessionOptions.SshHostKeyFingerprint = $xmlData.sftpConfig.SshHostKeyFingerprint $session = New-Object WinSCP.Session try { # Connect $session.Open($sessionOptions) # Detect the flag file while(! $session.FileExists($remoteRawPath+$flagFile)) { Get-Date Start-Sleep -s (wait10sec) } write-host "Start Downloading..." #if the data file or flag file exists,delete file first if((Test-Path ($localPath+$dataFile)) -or (Test-Path ($localPath+$flagFile))) { { write-host $dataFile" exists and will be removed!" Remove-Item ($localPath+$dataFile) } if(Test-Path ($localPath+$flagFile)) { write-host $finishFile" exists and will be removed!" Remove-Item ($localPath+$flagFile) } } $session.GetFiles($session.EscapeFileMask($remotePath + $dataFile), $localPath).Check() New-Item ($localPath+$flagFile) -ItemType file write-host "End Download" } finally { # Disconnect, clean up $session.Dispose() } exit 0 } catch [Exception] { Write-Host ("Error: {0}" -f $_.Exception.Message) exit 1 }

该脚本是通过WinSCP进行SFTP连接的,因此需要添加一个WinSCPnet.dll动态文件。