【发布时间】:2020-04-03 00:25:46
【问题描述】:
我已经构建了一个用于从 FTP 服务器下载文件的脚本。该脚本与我测试过的所有服务器都运行良好。对于此服务器,我可以获得目录列表,但是当我尝试下载文件时它失败并返回“421 服务不可用,关闭控制连接”错误。下面是我用来下载文件的代码。
function Get-FtpFile
{
Param ([string]$fileUrl, $credentials, [string]$destination)
try
{
$FTPRequest = [System.Net.FtpWebRequest]::Create($fileUrl)
if ($credentials)
{
$FTPRequest.Credentials = $credentials
}
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UseBinary = $true
$FTPRequest.UsePassive = $true
# Send the ftp request
$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
$LocalFile = New-Object IO.FileStream ($destination,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
# Loop through the download
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
$LocalFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)
$ResponseStream.Close()
$ReadBuffer.clear()
$LocalFile.Close()
$FTPResponse.Close()
}
catch [Net.WebException]
{
return "Unable to download because: $($_.exception)"
}
}
我可以使用 Windows 文件资源管理器 FTP 从该服务器下载文件,因此我认为这不是服务器本身的问题。
我通过测试注意到的一件有趣的事情是,当服务器返回目录列表时,每个文件名都包含一个尾随的 NULL。我已经尝试下载包括和不包括这个尾随 NULL 的文件,这两种尝试都会产生相同的错误代码。
以前有人见过类似的错误吗?或者是否有人知道 Windows 文件资源管理器使用 FTP 的方式与我上面列出的 PowerShell 脚本的区别?
【问题讨论】:
-
Wireshark 转储会显示客户端行为是否不同。
-
或者如果您不熟悉 Wireshark,请发布
FtpWebRequestlog file,以及来自任何可以下载该文件的 FTP 客户端的日志文件。 -
谢谢大家的建议,很遗憾我自己无法访问服务器,我们的客户正在从安全位置访问它。 Martin 我将尝试在我的代码中实现 .NET 跟踪功能。直到下周二,我才能从该服务器获得测试结果。但是当我得到日志文件时,我会将它们发布在这里。再次感谢您的帮助。
-
您好,我能够将 .NET 跟踪功能添加到我的脚本中,结果发现我没有正确删除尾随 NULL。更正此问题后,我现在可以从服务器下载所需的所有文件。感谢您的帮助。
标签: powershell ftp windows-explorer