C# 使用Renci.SshNet连接SSH远程服务器

当我们需要在远程的服务器上上传下载文件等一系列操作时,通常会借助一些远程工具才能完成。Renci.SshNet是一个用于.NET的安全Shell(SSH-2)库,可以在不借助第三方工具的情况下连接远程服务器进行操作。

GitHub:https://github.com/sshnet/SSH.NET

引用Renci.SshNet

  执行远程命令

 1 using (SshClient sshClient = new SshClient(host, int.Parse(port, CultureInfo.CurrentCulture), username, password))
 2 {
 3     //连接
 4     sshClient.Connect();
 5     //执行命令
 6     var cmd = sshClient.RunCommand("ls");
 7     //ExitStatus == 0 执行成功
 8     //
 9     if (cmd.ExitStatus == 0)
10     {
11         Console.WriteLine(cmd.Result);//执行结果
12     }
13     else
14     {
15         Console.WriteLine(cmd.Error);//错误信息
16     }
17     //断开连接
18     sshClient.Disconnect();
19 }

  封装的相关的Helper

  1 public class SshNetHelper : IDisposable
  2 {
  3     #region Field or property
  4 
  5         private readonly SftpClient sftp;
  6 
  7         /// <summary>
  8         /// SFTP connect status
  9         /// </summary>
 10         public bool Connected => sftp.IsConnected;
 11 
 12         #endregion
 13 
 14     #region Constructor
 15 
 16         /// <summary>
 17         /// Constructor
 18         /// </summary>
 19         /// <param name="ip">IP</param>
 20         /// <param name="port">Port</param>
 21         /// <param name="user">Username</param>
 22         /// <param name="pwd">password</param>
 23         public SshNetHelper(string ip, string port, string user, string pwd)
 24         {
 25             sftp = new SftpClient(ip, int.Parse(port, CultureInfo.CurrentCulture), user, pwd);
 26         }
 27 
 28         #endregion
 29 
 30     #region Connect SFTP
 31 
 32         /// <summary>
 33         /// Connect SFTP
 34         /// </summary>
 35         /// <returns>true</returns>
 36         public bool Connect()
 37         {
 38             try
 39             {
 40                 if (!Connected)
 41                 {
 42                     sftp.Connect();
 43                 }
 44                 return true;
 45             }
 46             catch (Exception ex)
 47             {
 48                 throw new Exception($"Disconnect SFTP fail,Error Message:{ex.Message}");
 49             }
 50         }
 51 
 52         #endregion
 53 
 54     #region Disconnect SFTP
 55 
 56         /// <summary>
 57         /// Disconnect SFTP
 58         /// </summary>
 59         public void Disconnect()
 60         {
 61             try
 62             {
 63                 if (sftp != null && Connected)
 64                 {
 65                     sftp.Disconnect();
 66                 }
 67             }
 68             catch (Exception ex)
 69             {
 70                 throw new Exception($"Disconnect SFTP fail,Error Message:{ex.Message}");
 71             }
 72         }
 73 
 74         #endregion
 75 
 76     #region SFTP Upload File
 77 
 78         /// <summary>
 79         /// SFTP Upload File
 80         /// </summary>
 81         /// <param name="localPath">Local file path</param>
 82         /// <param name="remotePath">Remote file path</param>
 83         public void Put(string localPath, string remotePath)
 84         {
 85             try
 86             {
 87                 using (var file = File.OpenRead(localPath))
 88                 {
 89                     Connect();
 90                     sftp.UploadFile(file, remotePath);
 91                     Disconnect();
 92                 }
 93             }
 94             catch (Exception ex)
 95             {
 96                 throw new Exception($"SFTP Upload File fail,Error Message:{ex.Message}");
 97             }
 98         }
 99 
100         #endregion
101 
102     #region SFTP Batch Upload File
103 
104         /// <summary>
105         /// SFTP Batch Upload File
106         /// </summary>
107         /// <param name="localPath">Local file path(without file name)</param>
108         /// <param name="remotePath">Remote file path(without file name)</param>
109         public void BatchPut(string localPath, string remotePath)
110         {
111             string uploadFullName = "";
112             string remoteFullName = "";
113             try
114             {
115                 Connect();
116                 DirectoryInfo fdir = new DirectoryInfo(localPath);
117                 FileInfo[] file = fdir.GetFiles();
118 
119                 if (file.Length != 0)
120                 {
121                     foreach (FileInfo f in file) //show all files under the path
122                     {
123                         using (var upLoadFile = File.OpenRead(f.FullName))
124                         {
125                             uploadFullName = f.FullName;
126                             remoteFullName = remotePath + "/" + f.Name;
127 
128                             sftp.UploadFile(upLoadFile, remotePath + "/" + f.Name);
129                         }
130                     }
131                 }
132             }
133             catch (Exception ex)
134             {
135                 throw new Exception($"SFTP Batch Upload File Fail,Error Message:{ex.Message}");
136             }
137         }
138 
139         #endregion SFTP Batch Upload File
140 
141     #region SFTP Get File
142 
143         /// <summary>
144         /// SFTP Get File
145         /// </summary>
146         /// <param name="remotePath">Remote file path</param>
147         /// <param name="localPath">Local file path</param>
148         public void Get(string remotePath, string localPath)
149         {
150             try
151             {
152                 Connect();
153                 var byt = sftp.ReadAllBytes(remotePath);
154                 Disconnect();
155                 File.WriteAllBytes(localPath, byt);
156             }
157             catch (Exception ex)
158             {
159                 throw new Exception($"SFTP Get File Fail,Error Message:{ ex.Message }");
160             }
161         }
162 
163         #endregion
164 
165     #region Delete SFTP File
166 
167         /// <summary>
168         /// Delete SFTP File
169         /// </summary>
170         /// <param name="remoteFile">Remote File path</param>
171         public void Delete(string remoteFile)
172         {
173             try
174             {
175                 Connect();
176                 sftp.Delete(remoteFile);
177                 Disconnect();
178             }
179             catch (Exception ex)
180             {
181                 throw new Exception($"Remote File Path Fail,Error Message:{ ex.Message }");
182             }
183         }
184 
185         #endregion
186 
187     #region Get SFTP File List
188 
189         /// <summary>
190         /// Get SFTP File List
191         /// </summary>
192         /// <param name="remotePath">Local path</param>
193         /// <param name="fileSuffix">file suffix</param>
194         /// <returns></returns>
195         public ArrayList GetFileList(string remotePath, string fileSuffix)
196         {
197             try
198             {
199                 Connect();
200                 var files = sftp.ListDirectory(remotePath);
201                 Disconnect();
202                 var objList = new ArrayList();
203                 foreach (var file in files)
204                 {
205                     string name = file.Name;
206                     if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
207                     {
208                         objList.Add(name);
209                     }
210                 }
211                 return objList;
212             }
213             catch (Exception ex)
214             {
215                 throw new Exception($"Get SFTP File List Fail,Error Message:{ex.Message}");
216             }
217         }
218 
219         #endregion
220 
221     #region Move SFTP File
222 
223         /// <summary>
224         /// Move SFTP File
225         /// </summary>
226         /// <param name="oldRemotePath">Old Remote Path</param>
227         /// <param name="newRemotePath">New Remote Path</param>
228         public void Move(string oldRemotePath, string newRemotePath)
229         {
230             try
231             {
232                 Connect();
233                 sftp.RenameFile(oldRemotePath, newRemotePath);
234                 Disconnect();
235             }
236             catch (Exception ex)
237             {
238                 throw new Exception($"Move SFTP File Faile,Error Message:{ex.Message}");
239             }
240         }
241 
242         #endregion
243 
244     protected virtual void Dispose(bool disposing)
245         {
246             if (!disposing) return;
247             // dispose managed resources
248             sftp.Dispose();
249             // free native resources
250         }
251 
252     public void Dispose()
253         {
254             Dispose(true);
255             GC.SuppressFinalize(this);
256         }
257 }
View Code
posted @ 2019-12-31 19:16  Uniqueness  阅读(8249)  评论(0编辑  收藏  举报