Renci.SshNet進行SFTP連線下載刪除上傳檔案
阿新 • • 發佈:2020-09-16
如果對SFTP or FTPS 有過一點點了解的話,那麼你肯定知道Renci.SshNet。
其中SftpClient類的建構函式需要傳輸,遠端伺服器地址、埠、使用者名稱、密碼(有些還有私鑰)。下面只是用到賬戶密碼即可,暫時就不說祕鑰了。
當你建立了這個例項之後,就可以Connect();開啟伺服器連線了。
通過ListDirectory()方法你就可以拿到遠端目錄的檔案了。伺服器初始檔案目錄地址為"/",當你那你子目錄或者檔案即可進行操作。
通過Delete()方法你可以直接根據遠端目錄直接刪除檔案 or 資料夾//"/Test.txt"
通過DownloadFile()方法你可以直接更具遠端目錄以及建立的檔案下載檔案。
通過UploadFile()方法你可以把本地檔案的流上傳到遠端目錄。
如有問題,我們可以繼續探討。
public class SFTP { #region 欄位或屬性 private SftpClient sftp; /// <summary> /// SFTP連線狀態 /// </summary> public bool Connected { get { return sftp.IsConnected; } } #endregion #regionView Code構造 /// <summary> /// 構造 /// </summary> /// <param name="ip">IP</param> /// <param name="port">埠</param> /// <param name="user">使用者名稱</param> /// <param name="pwd">密碼</param> public SFTPOperation(stringip, string port, string user, string pwd) { sftp = new SftpClient(ip, Int32.Parse(port), user, pwd); } public SFTPOperation(string ip, int port, string user, string pwd) { var authMethods = new List<AuthenticationMethod>(); var keyboardAuthMethod = new KeyboardInteractiveAuthenticationMethod(user);//鍵盤模擬連線 keyboardAuthMethod.AuthenticationPrompt += delegate (Object senderObject, AuthenticationPromptEventArgs eventArgs) { foreach (var prompt in eventArgs.Prompts) { if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase)) { prompt.Response = pwd; } } }; authMethods.Add(new PasswordAuthenticationMethod(user, pwd)); authMethods.Add(keyboardAuthMethod); var connection = new ConnectionInfo(ip, port, user, authMethods.ToArray()); sftp = new SftpClient(connection); sftp.Connect(); } public SFTPOperation(string ip, int port, string user, string passphrase, string keypath) { var key = File.ReadAllText(keypath); PrivateKeyFile keyFile = null; using (var buf = new MemoryStream(Encoding.UTF8.GetBytes(key))) { if (string.IsNullOrWhiteSpace(passphrase)) { keyFile = new PrivateKeyFile(buf); } else { keyFile = new PrivateKeyFile(buf, passphrase); } } var keyFiles = new[] { keyFile }; var methods = new List<AuthenticationMethod> { new PrivateKeyAuthenticationMethod(user, keyFiles) }; var connection = new ConnectionInfo(ip, port, user, methods.ToArray()); sftp = new SftpClient(connection); sftp.Connect(); } #endregion #region 連線SFTP /// <summary> /// 連線SFTP /// </summary> /// <returns>true成功</returns> public bool Connect() { try { if (!Connected) { sftp.Connect(); } return true; } catch (Exception ex) { throw new Exception(string.Format("連線SFTP失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 斷開SFTP /// <summary> /// 斷開SFTP /// </summary> public void Disconnect() { try { if (sftp != null && Connected) { sftp.Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("斷開SFTP失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region SFTP上傳檔案 /// <summary> /// SFTP上傳檔案 /// </summary> /// <param name="localPath">本地路徑</param> /// <param name="remotePath">遠端路徑</param> public bool Put(string localPath, string remotePath, bool successCloseConnect = false) { try { using (var file = File.OpenRead(localPath)) { Connect(); sftp.UploadFile(file, remotePath); Console.WriteLine("上傳成功"); if (successCloseConnect) { Disconnect(); } } return true; } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案上傳失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region SFTP獲取檔案 /// <summary> /// SFTP獲取檔案 /// </summary> /// <param name="remotePath">遠端路徑</param> /// <param name="localPath">本地路徑</param> public void Get(string remotePath, string localPath) { try { //Connect(); //var test = sftp.Get(remotePath); var byt = sftp.ReadAllBytes(remotePath); //Disconnect(); //建立寫入流 using (var fs = new FileStream(localPath, FileMode.CreateNew)) { var stream = new MemoryStream(byt); byte[] bytes = new byte[1024]; int count = 0; int readCount = 0; //從相應流中讀取到的檔案大小 while ((count = stream.Read(bytes, 0, bytes.Length)) > 0) { //寫入檔案 fs.Write(bytes, 0, count); //清空 fs.Flush(); readCount += count; } stream.Close(); var Count = readCount; } } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案獲取失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } public void GetFile(string remotePath, string localPath) { try { //建立寫入流 //using (var fs = new FileStream(localPath, FileMode.CreateNew)) using (var fs = File.OpenWrite(localPath)) { sftp.DownloadFile(remotePath, fs); } } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案獲取失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 刪除SFTP檔案 /// <summary> /// 刪除SFTP檔案 /// </summary> /// <param name="remoteFile">遠端路徑</param> public void Delete(string remoteFile, bool closeClient = false) { try { Connect(); sftp.Delete(remoteFile); if (closeClient) { Disconnect(); } } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案刪除失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 獲取SFTP檔案列表 /// <summary> /// 獲取SFTP檔案列表 /// </summary> /// <param name="remotePath">遠端目錄</param> /// <param name="fileSuffix">檔案字尾</param> /// <returns></returns> public List<string> GetFileList(string remotePath, string fileSuffix) { try { //Connect(); var files = sftp.ListDirectory(remotePath); //Disconnect(); var list = new List<string>(); foreach (var file in files) { string name = file.Name; if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length)) { list.Add(name); } } return list; } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案列表獲取失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion #region 移動SFTP檔案 /// <summary> /// 移動SFTP檔案 /// </summary> /// <param name="oldRemotePath">舊遠端路徑</param> /// <param name="newRemotePath">新遠端路徑</param> public void Move(string oldRemotePath, string newRemotePath) { try { Connect(); sftp.RenameFile(oldRemotePath, newRemotePath); Disconnect(); } catch (Exception ex) { throw new Exception(string.Format("SFTP檔案移動失敗,原因:{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } } #endregion }