C#使用PuTTY加密上传文件

需求:加密通过SFPT上传文件

1.安装PuTTY

2.生成文件,文件不用后缀名

 

3.上代码

class Program
    {
        private static string file = "C:\\Users\\3859\\Desktop\\RODHoldToRepairOrScrapList KSZRODHL2022-10-28\\T326\\ReceivingReport-20240510100.xlsx";

        static void Main(string[] args)
        {

            //PuttySFTP_ToFile(file);
            PPKSftp_ToFile(file);
            Console.ReadKey();
        }



        private static void PPKSftp_ToFile(string file)
        {

            var privateKeyPath = @"D:\dzw\FileKey\puttyKey"; // 指定ppk文件路径
            var username = "DZW2"; // SSH服务器的用户名
            var host = "124.221.227.131"; // SSH服务器的地址
            var port = 1022; // SSH端口,默认是22
            var remoteFilePath = "/path/"; // 远程文件路径
            //使用私钥文件创建一个PrivateKeyFile对象
            PrivateKeyFile privateKeyFile = new PrivateKeyFile(privateKeyPath);
            //使用私钥文件创建一个PrivateKeyFile对象
            PrivateKeyAuthenticationMethod privateKeyAuth = new PrivateKeyAuthenticationMethod(username,privateKeyFile);

            //创建一个链接信息对象
            ConnectionInfo connectionInfo = new ConnectionInfo(host,port,username, privateKeyAuth);

            //创建一个SftpClient脆响并连接到SFTP服务器
            using (var sftpClient = new SftpClient(connectionInfo))
            {
                sftpClient.Connect();

                //创建远程目录和本地目录
                if (!sftpClient.Exists(remoteFilePath))
                {
                    sftpClient.CreateDirectory(remoteFilePath);
                }
                //创建文件
                //if (!Directory.Exists(file))
                //{
                //    Directory.CreateDirectory(file);
                //}

                //赋值的文件到远程目录
                //IEnumerable<FileSystemInfo> infos = new DirectoryInfo(file).EnumerateFileSystemInfos();
                //foreach (var info in infos)
                //{
                //    using (var fs = File.OpenRead(info.FullName))
                //    {
                //        string reFilePath = Path.Combine(remoteFilePath,info.Name);
                //        sftpClient.BeginUploadFile(fs,remoteFilePath);
                //    }
                //}
                using (var fs = File.OpenRead(file))
                {
                    string reFilePath = Path.GetFileName(file);
                    sftpClient.UploadFile(fs, remoteFilePath + reFilePath);
                }

                sftpClient.Disconnect();

            }

        }

    }

 

4.效果:

 

 

参阅:https://blog.csdn.net/CSDN2016DDDD/article/details/132980800

 

posted @ 2024-05-14 16:50  蜗牛的礼物  阅读(17)  评论(0编辑  收藏  举报