SftpClientWithKey.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. using System;
  2. using System.IO;
  3. using Renci.SshNet;
  4. using Renci.SshNet.Sftp;
  5. using System.Collections.Generic;
  6. namespace SFTPUtils
  7. {
  8. public class SftpClientWithKey
  9. {
  10. private SftpClient _sftpClient;
  11. private readonly string _host;
  12. private readonly int _port;
  13. private readonly string _username;
  14. private readonly string _privateKeyPath;
  15. /// <summary>
  16. /// 初始化 SFTP 客户端
  17. /// </summary>
  18. /// <param name="host">SFTP 服务器地址</param>
  19. /// <param name="port">端口(默认22)</param>
  20. /// <param name="username">用户名</param>
  21. /// <param name="privateKeyPath">OpenSSH 格式私钥文件路径</param>
  22. public SftpClientWithKey(string host, int port, string username, string privateKeyPath)
  23. {
  24. _host = host;
  25. _port = port;
  26. _username = username;
  27. _privateKeyPath = privateKeyPath;
  28. }
  29. /// <summary>
  30. /// 连接到 SFTP 服务器
  31. /// </summary>
  32. public void Connect()
  33. {
  34. try
  35. {
  36. if (_sftpClient != null && _sftpClient.IsConnected)
  37. {
  38. return;
  39. }
  40. var keyFiles = new[] { new PrivateKeyFile(_privateKeyPath) };
  41. var connectionInfo = new ConnectionInfo(_host, _port, _username,
  42. new PrivateKeyAuthenticationMethod(_username, keyFiles));
  43. _sftpClient = new SftpClient(connectionInfo);
  44. _sftpClient.Connect();
  45. }
  46. catch (Exception ex)
  47. {
  48. throw new Exception($"SFTP 连接失败: {ex.Message}", ex);
  49. }
  50. }
  51. /// <summary>
  52. /// 断开连接
  53. /// </summary>
  54. public void Disconnect()
  55. {
  56. if (_sftpClient != null && _sftpClient.IsConnected)
  57. {
  58. _sftpClient.Disconnect();
  59. }
  60. }
  61. /// <summary>
  62. /// 上传文件到 SFTP 服务器
  63. /// </summary>
  64. /// <param name="localFilePath">本地文件路径</param>
  65. /// <param name="remoteDirectory">远程目录</param>
  66. /// <param name="remoteFileName">远程文件名(可选,如果为空则使用本地文件名)</param>
  67. /// <returns>上传成功返回 true</returns>
  68. public bool UploadFile(string localFilePath, string remoteDirectory, string remoteFileName = null)
  69. {
  70. if (!File.Exists(localFilePath))
  71. {
  72. throw new FileNotFoundException("本地文件不存在", localFilePath);
  73. }
  74. Connect();
  75. try
  76. {
  77. // 确保远程目录存在
  78. CreateRemoteDirectory(remoteDirectory);
  79. // 确定远程文件名
  80. string finalRemoteFileName = string.IsNullOrEmpty(remoteFileName)
  81. ? Path.GetFileName(localFilePath)
  82. : remoteFileName;
  83. string remoteFilePath = $"{remoteDirectory.TrimEnd('/')}/{finalRemoteFileName}";
  84. using (var fileStream = new FileStream(localFilePath, FileMode.Open))
  85. {
  86. _sftpClient.UploadFile(fileStream, remoteFilePath);
  87. }
  88. return true;
  89. }
  90. catch (Exception ex)
  91. {
  92. throw new Exception($"文件上传失败: {ex.Message}", ex);
  93. }
  94. }
  95. /// <summary>
  96. /// 创建远程目录(如果不存在)
  97. /// </summary>
  98. /// <param name="remoteDirectory">远程目录路径</param>
  99. private void CreateRemoteDirectory(string remoteDirectory)
  100. {
  101. try
  102. {
  103. var directories = remoteDirectory.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  104. string currentPath = string.Empty;
  105. foreach (var directory in directories)
  106. {
  107. currentPath += "/" + directory;
  108. if (!_sftpClient.Exists(currentPath))
  109. {
  110. _sftpClient.CreateDirectory(currentPath);
  111. }
  112. }
  113. }
  114. catch (Exception ex)
  115. {
  116. throw new Exception($"创建远程目录失败: {ex.Message}", ex);
  117. }
  118. }
  119. /// <summary>
  120. /// 检查文件是否存在
  121. /// </summary>
  122. /// <param name="remoteFilePath">远程文件路径</param>
  123. /// <returns>存在返回 true</returns>
  124. public bool FileExists(string remoteFilePath)
  125. {
  126. Connect();
  127. return _sftpClient.Exists(remoteFilePath);
  128. }
  129. /// <summary>
  130. /// 列出远程目录中的文件
  131. /// </summary>
  132. /// <param name="remoteDirectory">远程目录</param>
  133. /// <returns>文件列表</returns>
  134. public IEnumerable<ISftpFile> ListFiles(string remoteDirectory)
  135. {
  136. Connect();
  137. return _sftpClient.ListDirectory(remoteDirectory);
  138. }
  139. /// <summary>
  140. /// 删除远程文件
  141. /// </summary>
  142. /// <param name="remoteFilePath">远程文件路径</param>
  143. /// <returns>删除成功返回 true</returns>
  144. public bool DeleteFile(string remoteFilePath)
  145. {
  146. Connect();
  147. if (_sftpClient.Exists(remoteFilePath))
  148. {
  149. _sftpClient.DeleteFile(remoteFilePath);
  150. return true;
  151. }
  152. return false;
  153. }
  154. /// <summary>
  155. /// 释放资源
  156. /// </summary>
  157. public void Dispose()
  158. {
  159. Disconnect();
  160. _sftpClient?.Dispose();
  161. }
  162. }
  163. }