FTPS的正确使用

关于FTP、FTPS 与 SFTP 简介见另外一篇转载的文章,讲的比较详细,此文不在另外描述.

https://blog.csdn.net/ericwuhk/article/details/109120158

FTPS在微软官网寥寥数笔,看完也一头雾水,无奈找了一通,找了到了一份开源代码,研究了一通发觉可用,至此记录.

https://docs.microsoft.com/en-us/archive/blogs/adarshk/using-ftpwebrequest-to-do-ftp-over-ssl

一句未改得原始代码上传至CSDN,以便哪天找不到国外网站资源.

https://download.csdn.net/download/ericwuhk/12984869

第一步:打开源码,VS报弹框不用理,直接确定即可.在原始代码中直接rebuild编译FTPSClient,生成"AlexPilotti.FTPS.Client.dll"和“AlexPilotti.FTPS.Client.XML" 这两个文件导入至所需得项目路径下,直接引用就可.

第二步:编译FTPSClientCmdApp,生成ftps.exe,打开cmd命令窗口查看工具是否可正常使用

ftps -h 10.131.128.6 -U user -P password -ssl CredentialsRequired -g /Modules/ZW01TLAA.IMZ C:\Users\XXX\Desktop\mytest

第三步:在自己的项目中,导入"AlexPilotti.FTPS.Client.dll"和“AlexPilotti.FTPS.Client.XML"后,需要修改代码才能正确使用.核心代码修改如下:

using System;
using System.Data;
using System.IO;
using BaseLibrary.ExecutionResults;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using BaseLibrary.Config;
using AlexPilotti.FTPS.Client;

public class readfile
{
    public string strServerPath;
    public FTPSClient client;

    public void initFTPS()
        {
            CCfg ccfg = new CCfg();
            strServerPath = ccfg.GetValue("serverPath");//modules
            string user = ccfg.GetValue("user");//"ftpsuser"
            string password = ccfg.GetValue("password");//"password"
            string ip = ccfg.GetValue("ip");//"192.168.1.1"

            client = new FTPSClient();
            NetworkCredential credential = new NetworkCredential(user, password);
            ESSLSupportMode sslRequestSupportMode = ESSLSupportMode.DataChannelRequested;
            X509Certificate x509ClientCert = null;
            string sslClientCertPath = null;
            int sslMinKeyExchangeAlgStrength = 0;
            int sslMinCipherAlgStrength = 0;
            int sslMinHashAlgStrength = 0;
            int timeout = 120;
            bool useCtrlEndPointAddressForData = false;
            EDataConnectionMode dataConnectionMode = EDataConnectionMode.Passive;
            if (sslClientCertPath != null)
            {
                x509ClientCert = X509Certificate.CreateFromCertFile(sslClientCertPath);
            }
            client.Connect(ip, 21,
                credential,
                sslRequestSupportMode,
                new RemoteCertificateValidationCallback(ValidateTestServerCertificate),
                x509ClientCert,
                sslMinKeyExchangeAlgStrength,
                sslMinCipherAlgStrength,
                sslMinHashAlgStrength,
                timeout * 1000,
                useCtrlEndPointAddressForData,
                dataConnectionMode);                            
        }

        enum EInvalidSslCertificateHandling { Refuse, Accept, Prompt }
        private  bool ValidateTestServerCertificate(object sender, X509Certificate                     certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool certOk = false;
            EInvalidSslCertificateHandling sslInvalidServerCertHandling = EInvalidSslCertificateHandling.Prompt;

            if (sslPolicyErrors == SslPolicyErrors.None)
                certOk = true;
            else
            {
                Console.Error.WriteLine();

                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) > 0)
                    Info("WARNING: SSL/TLS remote certificate chain warning");

                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) > 0)
                    Info("WARNING: SSL/TLS remote certificate name mismatch");

                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) > 0)
                    Info("WARNING: SSL/TLS remote certificate not available");

                if (sslInvalidServerCertHandling == EInvalidSslCertificateHandling.Accept)
                    certOk = true;
            }

            if (!certOk)
            {                
                Info("SSL/TLS Server certificate details:");                
                Info(GetCertificateInfo(certificate));
            }

            if (!certOk && sslInvalidServerCertHandling == EInvalidSslCertificateHandling.Prompt)
            {
                //certOk = Utility.ConsoleConfirm("Accept invalid server certificate? (Y/N)");
                certOk = true;
            }

            return certOk;
        }

        public static string GetCertificateInfo(X509Certificate certificate)
        {
            StringBuilder certInfo = new StringBuilder();

            //Note: certificate.ToString() returns just the class name in Mono 2.0

            // Simulate the .Net frameworks 2.0 ToString()
            certInfo.AppendLine("[Subject]");
            certInfo.AppendLine(certificate.Subject);
            certInfo.AppendLine("");
            certInfo.AppendLine("[Issuer]");
            certInfo.AppendLine(certificate.Issuer);
            certInfo.AppendLine("");
            certInfo.AppendLine("[Serial Number]");
            certInfo.AppendLine(certificate.GetSerialNumberString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Not Before]");
            certInfo.AppendLine(certificate.GetEffectiveDateString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Not After]");
            certInfo.AppendLine(certificate.GetExpirationDateString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Thumbprint]");
            certInfo.AppendLine(certificate.GetCertHashString());

            return certInfo.ToString();
        }

        public void Download(string strServerFile,string strLocalFile)
        {
            if (!File.Exists(strLocalFile))
            {
                if (client == null)
                {
                    initFTPS();
                }
                Info($"{strServerFile} is copying.");
                client.GetFile($"/{strServerPath}/{strServerFile}", strLocalFile);
            }
            else
            {
                Info($"{strServerFile} is already existed!");
            }
        }
}

是不是相当简单呢?

 

使用FTPS协议进行安全的文件传输涉及多个关键步骤,包括服务器配置、客户端设置以及实际的数据传输过程。以下是详细的说明: ### 1. 服务器端配置 - **安装并配置SSL证书**:在服务器上安装有效的SSL/TLS证书,以确保能够建立加密连接。这通常涉及到从可信的证书颁发机构获取证书,并将其安装到FTP服务器软件中。 - **启用TLS/SSL支持**:配置FTP服务器以接受基于TLS/SSL的安全连接。不同的FTP服务器软件可能有不同的配置方法,但一般都需要修改配置文件或通过管理界面开启相关选项。 ### 2. 客户端准备 - **选择支持FTPS的客户端**:确保使用FTP客户端软件支持FTPS协议。一些常见的支持FTPS的客户端包括FileZilla、WinSCP等。 - **配置客户端**:在客户端中设置正确的服务器地址、端口(默认为990)、用户名和密码。同时,需要指定使用哪种类型的加密连接(如显式或隐式TLS/SSL)[^4]。 ### 3. 建立安全连接 - **发起连接请求**:启动客户端后,根据预先设定的参数向服务器发送连接请求。此时,客户端会与服务器协商使用何种加密算法来保护通信。 - **验证服务器身份**:客户端会检查服务器提供的SSL证书是否有效,并确认其是否由受信任的证书颁发机构签发,以此防止中间人攻击。 ### 4. 文件传输操作 - **上传和下载文件**:一旦建立了安全连接,就可以像普通FTP一样执行文件上传和下载操作。所有数据都将被加密,从而保证了传输过程中的安全性。 - **断开连接**:完成所有必要的文件传输任务之后,可以正常关闭与服务器之间的连接。 ### 示例代码 以下是一个简单的Python示例,演示如何使用`ftplib`库与FTPS服务器交互: ```python from ftplib import FTP_TLS # 创建一个FTPS对象实例 ftps = FTP_TLS() # 连接到FTPS服务器 ftps.connect('your.ftps.server', 990) # 登录到服务器 ftps.login(user='username', passwd='password') # 切换至被动模式 ftps.prot_p() # 获取当前目录下的文件列表 ftps.retrlines('LIST') # 下载文件 with open('local_file.txt', 'wb') as f: ftps.retrbinary('RETR remote_file.txt', f.write) # 关闭连接 ftps.quit() ``` ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值