using Microsoft.Extensions.Logging; using Renci.SshNet; namespace Admin.NET.Core { /// /// SSH / Sftp Helper /// public class SSHHelper : IDisposable { private SftpClient sftp; public SSHHelper(string host, int port, string user, string password) { sftp = new SftpClient(host, port, user, password); } public bool Exists(string ftpFileName) { Connect(); return sftp.Exists(ftpFileName); } private void Connect() { if (!sftp.IsConnected) { sftp.Connect(); } } /// /// 删除 /// /// public void DeleteFile(string ftpFileName) { Connect(); sftp.DeleteFile(ftpFileName); } /// /// 下载到指定目录 /// /// /// public void DownloadFile(string ftpFileName, string localFileName) { Connect(); using (Stream fileStream = File.OpenWrite(localFileName)) { sftp.DownloadFile(ftpFileName, fileStream); } } /// /// 读取字节 /// /// /// public byte[] ReadAllBytes(string ftpFileName) { Connect(); return sftp.ReadAllBytes(ftpFileName); } /// /// 读取流 /// /// /// public Stream OpenRead(string path) { return sftp.Open(path, FileMode.Open, FileAccess.Read); } /// /// 继续下载 /// /// /// public void DownloadFileWithResume(string ftpFileName, string localFileName) { DownloadFile(ftpFileName, localFileName); } /// /// 重命名 /// /// /// public void RenameFile(string oldPath, string newPath) { sftp.RenameFile(oldPath, newPath); } /// /// 指定目录下文件 /// /// /// /// public List GetFileList(string folder, IEnumerable filters) { var files = new List(); Connect(); var sftpFiles = sftp.ListDirectory(folder); foreach (var file in sftpFiles) { if (file.IsRegularFile && filters.Any(f => file.Name.EndsWith(f))) { files.Add(file.Name); } } return files; } /// /// 上传指定目录文件 /// /// /// public void UploadFile(string localFileName, string ftpFileName) { Connect(); var dir = Path.GetDirectoryName(ftpFileName); CreateDir(sftp, dir); using (var fileStream = new FileStream(localFileName, FileMode.Open)) { sftp.UploadFile(fileStream, ftpFileName); } } /// /// 上传字节 /// /// /// public void UploadFile(byte[] bs, string ftpFileName) { Connect(); var dir = Path.GetDirectoryName(ftpFileName); CreateDir(sftp, dir); sftp.WriteAllBytes(ftpFileName, bs); } /// /// 上传流 /// /// /// public void UploadFile(Stream fileStream, string ftpFileName) { Connect(); var dir = Path.GetDirectoryName(ftpFileName); CreateDir(sftp, dir); sftp.UploadFile(fileStream, ftpFileName); fileStream.Dispose(); } /// /// 创建目录 /// /// /// /// private void CreateDir(SftpClient sftp, string dir) { if (dir is null) { throw new ArgumentNullException(nameof(dir)); } if (!sftp.Exists(dir)) { var index = dir.LastIndexOfAny(new char[] { '/', '\\' }); if (index > 0) { var p = dir.Substring(0, index); if (!sftp.Exists(p)) { CreateDir(sftp, p); } sftp.CreateDirectory(dir); } } } public void Dispose() { if (sftp != null) { if (sftp.IsConnected) sftp.Disconnect(); sftp.Dispose(); } } } }