【发布时间】:2012-05-26 07:23:51
【问题描述】:
我正在尝试通过 C# 中的 FtpWebRequest 类实现 ftp/sftp,但到现在还没有成功。
我不想使用任何第三方免费或付费 dll。
凭证就像
- 主机名 = sftp.xyz.com
- 用户 ID = abc
- 密码 = 123
我能够通过 IP 地址实现 ftp,但无法通过凭据实现上述主机名的 sftp。
对于 sftp,我已将 FtpWebRequest 类的 EnableSsl 属性启用为 true,但出现无法连接到远程服务器的错误。
我可以使用相同的凭据和主机名连接 Filezilla,但不是通过代码。
我观察到 filezilla,它将主机名从 sftp.xyz.com 更改为 sftp://sftp.xyz.com 在文本框和命令行中,它将用户 ID 更改为 abc@sftp.xyz.com
我在代码中做了同样的事情,但 sftp 没有成功。
请在这方面需要紧急帮助。提前致谢。
以下是我目前的代码:
private static void ProcessSFTPFile()
{
try
{
string[] fileList = null;
StringBuilder result = new StringBuilder();
string uri = "ftp://sftp.xyz.com";
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(uri));
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.EnableSsl = true;
ftpRequest.Credentials = new NetworkCredential("abc@sftp.xyz.com", "123");
ftpRequest.UsePassive = true;
ftpRequest.Timeout = System.Threading.Timeout.Infinite;
//ftpRequest.AuthenticationLevel = Security.AuthenticationLevel.MutualAuthRequested;
//ftpRequest.Proxy = null;
ftpRequest.KeepAlive = true;
ftpRequest.UseBinary = true;
//Hook a callback to verify the remote certificate
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
//ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append("ftp://sftp.xyz.com" + line);
result.Append("\n");
line = reader.ReadLine();
}
if (result.Length != 0)
{
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
// extracting the array of all ftp file paths
fileList = result.ToString().Split('\n');
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.ReadLine();
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (certificate.Subject.Contains("CN=sftp.xyz.com"))
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
带 ssl 的 ftp 是 ftps,而不是 sftp。 sftp 是一个完全不同的基于 ssh 的协议。
-
而且,据我所知,.NET 中没有基于 SSH 的协议。
-
thnks 但是我应该怎么做我已经给出了以 sftp 开头的主机名,并且 filezilla 在连接时也在主机名之前添加了 sftp。请详细说明一些步骤或代码。
-
嗨 @JoachimIsaksson 我基本上有 2 个主机名,一个是 sftp.xyz.com,另一个是 ftp.xyz.com 我该怎么办。我怎样才能在 .net 中实现这一点
-
@pan4321 sftp 在没有第三方库的情况下在 .NET 中不可用,因此如果您真的不想使用任何第三方代码,则必须自己实现它。否则,SharpSSH 对我有用,但(大部分?)商业实现更稳定。