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

由网友(幼儿园一姐)分享简介:我想用自动化PowerShell的数据库备份文件的FTP下载。文件名包括日期,所以我不能只是每天都运行相同的FTP脚本。有没有干净的方式来做到这一点PowerShell内置或使用.NET Framework?I'd like to automate the FTP download of a database bac...

我想用自动化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,它会运行而无需修改。

After some experimentation I came up with this way to automate a secure FTP download in PowerShell. This script runs off the public test FTP server administered by Chilkat Software. So you can copy and paste this code and it will run without modification.

$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下载:编码问题 简单的FTP演示应用 非常简单的FTP客户 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.

阅读全文

相关推荐

最新文章