在PowerShell中自动化安全FTP的最佳方法是什么?

Eri*_*ess 26 .net ftp powershell

我想使用PowerShell自动化FTP下载数据库备份文件.文件名包含日期,因此我不能每天运行相同的FTP脚本.是否有一种干净的方法来构建PowerShell或使用.Net框架?

更新我忘了提到这是一个通过安全的FTP会话.

Eri*_*ess 24

经过一些实验,我想出了这种方法来自动化PowerShell中的安全FTP下载.此脚本在Chilkat Software管理的公共测试FTP服务器上运行.因此,您可以复制并粘贴此代码,它将无需修改即可运行.

$sourceuri = "ftp://ftp.secureftp-test.com/hamlet.zip"
$targetpath = "C:\hamlet.zip"
$username = "test"
$password = "test"

# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for an authenticated connection
$ftprequest.Credentials =
    New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false

# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()

# get a download stream from the server response
$responsestream = $ftpresponse.GetResponseStream()

# create the target file on the local system and the download buffer
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024

# loop through the download stream and send the data to the target file
do{
    $readlength = $responsestream.Read($readbuffer,0,1024)
    $targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)

$targetfile.close()
Run Code Online (Sandbox Code Playgroud)

我在这些链接上找到了很多有用的信息

如果要使用SSL连接,则需要添加该行

$ftprequest.EnableSsl = $true
Run Code Online (Sandbox Code Playgroud)

在调用GetResponse()之前到脚本.有时您可能需要处理已过期的服务器安全证书(就像我不幸的那样).PowerShell代码存储库中有一个页面,其中包含一个代码片段.前28行与下载文件最相关.


Pab*_*loG 7

取自这里

$source = "ftp://ftp.microsoft.com/ResKit/win2000/dureg.zip"
$target = "c:\temp\dureg.zip"
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($source, $target)
Run Code Online (Sandbox Code Playgroud)

适合我


EBG*_*een 0

这并不像我希望的那么简单。据我所知,有三种选择。

  1. .NET - 您可以使用 .NET 框架在 PowerShell 中执行此操作,但它涉及我不想在脚本中执行的原始套接字操作。如果我走这条路,那么我会将所有 FTP 垃圾打包到 C# 中的 DLL 中,然后从 PowerShell 中使用该 DLL。

  2. 操作文件 - 如果您知道每天需要获取的文件名称的模式,那么您只需使用 PowerShell 打开 FTP 脚本并更改脚本中的文件名称即可。然后运行脚本。

  3. 通过管道传输文本到 FTP - 最后一个选项是使用 PowerShell 通过管道将信息传入和传出 FTP 会话。看这里