.net 在 PowerShell 中自动执行安全 FTP 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/265339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:30:43  来源:igfitidea点击:

What's the best way to automate secure FTP in PowerShell?

.netpowershellftp

提问by Eric Ness

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?

我想使用 PowerShell 自动执行数据库备份文件的 FTP 下载。文件名包括日期,所以我不能每天都运行相同的 FTP 脚本。是否有一种干净的方法可以在 PowerShell 中内置或使用 .Net 框架来执行此操作?

UPDATEI forgot to mention that this is a through a secure FTP session.

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

回答by Eric Ness

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 serveradministered by Chilkat Software. So you can copy and paste this code and it will run without modification.

经过一些实验,我想出了这种在 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()

I found a lot of helpful information at these links

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

If you want to use an SSL connection you need to add the line

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

$ftprequest.EnableSsl = $true

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 Repositorythat has a code snippet to do that. The first 28 lines are the most relevant for the purposes of downloading a file.

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

回答by PabloG

Taken from here

取自这里

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

Works for me

对我来说有效

回答by tomasr

As far as PowerShell goes, the /n Software NetCmdletspackage includes FTP cmdlets (including support for both secure FTP types) that you could use pretty easily for this.

就 PowerShell 而言,/n Software NetCmdlets包包括 FTP cmdlet(包括对两种安全 FTP 类型的支持),您可以很容易地使用它。

回答by user695859

The JAMS Job Scheduler offers some cmdlets that would make this task simple. It has a variety of FTP cmdlets for secure sessions as well as date cmdlets for converting natural dates into .Net date objects such as "Last day of month":

JAMS Job Scheduler 提供了一些 cmdlet 可以简化此任务。它有各种用于安全会话的 FTP cmdlet 以及用于将自然日期转换为 .Net 日期对象的日期 cmdlet,例如“一个月的最后一天”:

JAMS Job Scheduler Cmdlets

JAMS 作业调度程序 Cmdlet

回答by Nathan

Something like this could work:

这样的事情可以工作:

$bkdir = "E:\BackupsPWS" #backups location directory
Zip = 'C:\"Program Files"-Zipz.exe' #compression utility
$files_to_transfer = New-Object System.Collections.ArrayList #list of zipped files to be   transferred over FTP
$ftp_uri="myftpserver"
$user="myftpusername"
$pass="myftppassword"

#find .bak files not zipped yet, zip them, add them to the list to be transferrd
get-childitem -path $bkdir | Sort-Object length |
where { $_.extension -match ".(bak)" -and
-not (test-path ($_.fullname -replace "(bak)", "7z")) } |
foreach {
$zipfilename = ($_.fullname -replace "bak", "7z")
Invoke-Expression "Zip a $zipfilename $($_.FullName)"
$files_to_transfer.Add($zipfilename)
}

#find .bak files, if they've been zipped, delete the .bak file
get-childitem -path $bkdir |
where { $_.extension -match ".(bak)" -and
(test-path ($_.fullname -replace "(bak)", "7z")) } |
foreach { del $_.fullname }

#transfer each zipped file over FTP
foreach ($file in $files_to_transfer)
{
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) # FTP credentials
$ftp_urix = $ftp_uri + "/" + $file.Substring($bkdir.Length + 1) # ftp address where to transfer   the file
$uri=[system.URI] $ftp_urix
$webclient.UploadFile($uri, $file) #transfer the file
}

Check this: Powershell: compress backups and FTP transfer

检查这个:Powershell:压缩备份和 FTP 传输

回答by EBGreen

This isn't as simple as I wish it was. There are three options that I know of.

这并不像我希望的那么简单。我知道有三个选项。

1) .Net - You can use the .Net framework to do this in PS, but it involves raw socket manipulation that I wouldn't want to do in a script. If I were going this route, then I would wrap up all the ftp junk into a DLL in C# then use that DLL from powershell.

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

2) Manipulating a file - If you know the pattern of the name of the file that you need to get each day then you could just open your ftp script with PS and change the name of the file in the script. Then run the script.

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

3) Pipe text to FTP - The last option is to use powershell to pipe info into and out of your FTP session. See here.

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

回答by Peter Seale

I have successfully used the Indy Project .NET library to do FTP. And...ugh, looks like the hosted .NET build is no longer available.

我已经成功地使用 Indy Project .NET 库来做 FTP。而且……呃,看起来托管的 .NET 构建不再可用。

回答by Alex

$realdate = (Get-Date).ToString("yyyyMMdd")

$realdate = (Get-Date).ToString("yyyyMMdd")

$path = "D:\samplefolderstructure\filename" + $realdate + ".msi"

$path = "D:\samplefolderstructure\filename" + $realdate + ".msi"

ftps -f $path -s:D:\FTP.txt

ftps -f $path -s:D:\FTP.txt

ftp.txt is the way we keep all of our connection info to the ftp server. ftps is the client we use obviously, so might have to change a few things. But, this should help you ge the idea.

ftp.txt 是我们将所有连接信息保存到 ftp 服务器的方式。ftps 显然是我们使用的客户端,因此可能需要更改一些内容。但是,这应该可以帮助您理解这个想法。