c# NET6.0 SFTP 使用私钥连接并实现文件的上传与下载

NET6.0 SFTP 使用私钥连接并实现文件的上传与下载

使用Openssh 私钥连接SFTP服务器

如果使用的是.ppk(PuTTY Private Key)的私钥格式,可以使用puttygen转成openssh,
或者直接使用winscp来实现,
使用PuTTygen转成openssh

使用的是SSH.NET库https://www.nuget.org/packages/SSH.NET

dotnet add package SSH.NET --version 2020.0.2

下载文件

using Renci.SshNet;

 /// <summary>
 /// 下载所有文件到本地
 /// </summary>
 public  void DownloadFiles(string remotePath ,string localPath)
 {
     try
     {
         // 使用私钥文件创建一个PrivateKeyFile对象
         PrivateKeyFile privateKeyFile = new PrivateKeyFile(PrivateKeyFilePath);
         // 使用私钥文件创建一个PrivateKeyFile对象
         PrivateKeyAuthenticationMethod privateKeyAuth = new PrivateKeyAuthenticationMethod(Username, privateKeyFile);
         // 创建一个连接信息对象
         ConnectionInfo connectionInfo = new ConnectionInfo(Host, 22, Username, privateKeyAuth);
         // 创建一个SftpClient对象并连接到SFTP服务器
         using (var sftpClient = new SftpClient(connectionInfo))
         {
             sftpClient.Connect();
             // 创建远程目录和本地目录
             if (!sftpClient.Exists(remotePath))
             {
                 sftpClient.CreateDirectory(remotePath);
             }
             if (!Directory.Exists(localPath))
             {
                 Directory.CreateDirectory(localPath);
             }
             //复制文件到本地
             var fileList = sftpClient.ListDirectory(remotePath);
             foreach (var file in fileList)
             {
                 if (!file.IsDirectory)
                 {
                     string localFilePath = Path.Combine(localPath, file.Name);
                     using (var fs = new FileStream(localFilePath, FileMode.Create))
                     {
                         string remoteFilePath = file.FullName;
                         sftpClient.DownloadFile(remoteFilePath, fs);                     }
                 }
             }
             sftpClient.Disconnect();
         }
     }
     catch (Exception e)
          {         
         throw;
     }

 }

上传文件

using Renci.SshNet;

 /// <summary>
 /// 上传所有文件到sftp服务器
 /// </summary>
 public void UploadFiles( string localPath, string remotePath)
 {
     try
     {
 

         // 使用私钥文件创建一个PrivateKeyFile对象
         PrivateKeyFile privateKeyFile = new PrivateKeyFile(PrivateKeyFilePath);

         // 使用私钥文件创建一个PrivateKeyFile对象
         PrivateKeyAuthenticationMethod privateKeyAuth = new PrivateKeyAuthenticationMethod(Username, privateKeyFile);

         // 创建一个连接信息对象
         ConnectionInfo connectionInfo = new ConnectionInfo(Host, 22, Username, privateKeyAuth);

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

             // 创建远程目录和本地目录
             if (!sftpClient.Exists(remotePath))
             {
                 sftpClient.CreateDirectory(remotePath);
             }
             if (!Directory.Exists(localPath))
             {
                 Directory.CreateDirectory(localPath);
             }

             /复制的文件到远程目录
             IEnumerable<FileSystemInfo> infos = new DirectoryInfo(localPath).EnumerateFileSystemInfos();
             foreach (var info in infos)
             {
                 using (var fs = File.OpenRead(info.FullName))
                 {
                     string remotfilepath = Path.Combine(remotePath, info.Name);

                     sftpClient.UploadFile(fs, remotfilepath);
                 }
             }
             sftpClient.Disconnect();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }

 }

相关属性

 public string Host = "192.168.0.1";
 public string Username = "yourName";
 public string PrivateKeyFilePath = "opensshkey"; // 如果是ppk必须转为openssh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个基本的ESP32程序,可连接SFTP服务器并下载文件: ``` #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_wifi.h" #include "esp_event_loop.h" #include "esp_log.h" #include <libssh/libssh.h> #include <libssh/sftp.h> /* SFTP服务器的IP地址 */ #define SFTP_SERVER_IP "192.168.1.100" /* SFTP服务器的端口号 */ #define SFTP_SERVER_PORT 22 /* SFTP服务器的用户名和密码 */ #define SFTP_USERNAME "username" #define SFTP_PASSWORD "password" /* 要下载文件的路径和名称 */ #define REMOTE_FILE_PATH "/path/to/remote/file" #define LOCAL_FILE_PATH "/path/to/local/file" /* SFTP客户端连接句柄 */ ssh_session my_ssh_session; sftp_session my_sftp_session; /* 连接SFTP服务器 */ void sftp_connect(void *pvParameters) { /* 初始化SSH会话 */ int rc; my_ssh_session = ssh_new(); if (my_ssh_session == NULL) { printf("Error creating SSH session.\n"); vTaskDelete(NULL); } /* 设置SSH会话选项 */ ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, SFTP_SERVER_IP); ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &SFTP_SERVER_PORT); ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, SFTP_USERNAME); ssh_options_set(my_ssh_session, SSH_OPTIONS_PASSWORD, SFTP_PASSWORD); /* 连接SFTP服务器 */ rc = ssh_connect(my_ssh_session); if (rc != SSH_OK) { printf("Error connecting to SFTP server.\n"); ssh_free(my_ssh_session); vTaskDelete(NULL); } /* 认证 */ rc = ssh_userauth_password(my_ssh_session, NULL, SFTP_PASSWORD); if (rc != SSH_AUTH_SUCCESS) { printf("Error authenticating with SFTP server.\n"); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); vTaskDelete(NULL); } /* 初始化SFTP会话 */ my_sftp_session = sftp_new(my_ssh_session); if (my_sftp_session == NULL) { printf("Error creating SFTP session.\n"); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); vTaskDelete(NULL); } /* 连接SFTP服务器 */ rc = sftp_init(my_sftp_session); if (rc != SSH_OK) { printf("Error connecting to SFTP server.\n"); sftp_free(my_sftp_session); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); vTaskDelete(NULL); } printf("Connected to SFTP server.\n"); /* 下载文件 */ sftp_file file; file = sftp_open(my_sftp_session, REMOTE_FILE_PATH, O_RDONLY, 0); if (file == NULL) { printf("Error opening remote file.\n"); sftp_free(my_sftp_session); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); vTaskDelete(NULL); } FILE *local_file; local_file = fopen(LOCAL_FILE_PATH, "wb"); if (local_file == NULL) { printf("Error opening local file.\n"); sftp_close(file); sftp_free(my_sftp_session); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); vTaskDelete(NULL); } char buffer[1024]; size_t nbytes; while ((nbytes = sftp_read(file, buffer, sizeof(buffer))) > 0) { fwrite(buffer, 1, nbytes, local_file); } sftp_close(file); sftp_free(my_sftp_session); ssh_disconnect(my_ssh_session); ssh_free(my_ssh_session); printf("File downloaded successfully.\n"); vTaskDelete(NULL); } void app_main() { /* 配置Wi-Fi连接 */ wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); esp_wifi_init(&cfg); esp_wifi_set_mode(WIFI_MODE_STA); wifi_config_t wifi_config = { .sta = { .ssid = "your_wifi_ssid", .password = "your_wifi_password" } }; esp_wifi_set_config(WIFI_IF_STA, &wifi_config); esp_wifi_start(); /* 连接SFTP服务器并下载文件 */ xTaskCreate(&sftp_connect, "sftp_connect", 4096, NULL, 5, NULL); } ``` 在此示例代码中,我们在连接SFTP服务器后下载了一个文件。首先,我们初始化一个SSH会话,然后设置SSH选项以指定SFTP服务器的IP地址,端口号,用户名和密码。然后,我们连接SFTP服务器并进行身份验证。接下来,我们打开要下载的远程文件,并创建一个本地文件。然后,我们循环读取远程文件的内容,并将其写入本地文件中。最后,我们关闭文件并关闭SFTP和SSH会话。 编译和烧录这个ESP32应用程序,然后运行它。它将连接SFTP服务器并下载文件。如果一切正常,它将打印出“File downloaded successfully.”消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听我俩天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值