问题描述
我想用自动化PowerShell的数据库备份文件的FTP下载。文件名包括日期,所以我不能只是每天都运行相同的FTP脚本。有没有干净的方式来做到这一点PowerShell内置或使用.NET Framework?
I'd like to automate the FTP download of a database backup file using PowerShell. The file name includes the date so I can't just run the same FTP script every day. Is there a clean way to do this built into PowerShell or using the .Net framework?
更新我忘了提,这是一个通过一个安全的FTP会话。
UPDATE I forgot to mention that this is a through a secure FTP session.
推荐答案
一些实验,我想出了这个办法来自动化安全的FTP下载在PowerShell中后。此脚本通过奇尔卡特软件管理的公开测试的FTP服务器上运行了。所以,你可以复制并粘贴此code,它会运行而无需修改。
$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()
I found a lot of helpful information at these links
- FTP downloads: encoding problems
- Simple FTP demo application
- Very Simple FTP Client
如果您要使用SSL连接,你需要添加行
If you want to use an SSL connection you need to add the line
$ftprequest.EnableSsl = $true
要调用的GetResponse前脚本()。有时你可能需要处理与到期(像我遗憾的是)服务器安全证书。有一个网页在 PowerShell的code库具有code片段来做到这一点。前28行是最相关的用于下载文件的目的
to the script before you call GetResponse(). Sometimes you may need to deal with a server security certificate that is expired (like I unfortunately do). There is a page at the PowerShell Code Repository that has a code snippet to do that. The first 28 lines are the most relevant for the purposes of downloading a file.
这篇关于什么是自动化安全FTP在PowerShell中的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!