C#使⽤Renci.SshNet连接SSH远程服务器
当我们需要在远程的服务器上上传下载⽂件等⼀系列操作时,通常会借助⼀些远程⼯具才能完成。Renci.SshNet是⼀个⽤于.NET的安全Shell(SSH-2)库,可以在不借助第三⽅⼯具的情况下连接远程服务器进⾏操作。
GitHub:
引⽤Renci.SshNet
  执⾏远程命令
1using (SshClient sshClient = new SshClient(host, int.Parse(port, CultureInfo.CurrentCulture), username, password))
2{
3//连接
4    sshClient.Connect();
5//执⾏命令
6var cmd = sshClient.RunCommand("ls");
7//ExitStatus == 0 执⾏成功
8//
9if (cmd.ExitStatus == 0)
10    {
11        Console.WriteLine(cmd.Result);//执⾏结果
12    }
13else
14    {
15        Console.WriteLine(cmd.Error);//错误信息
16    }
17//断开连接
18    sshClient.Disconnect();
19 }
  封装的相关的Helper
1public class SshNetHelper : IDisposable
2{
3#region Field or property
4
5private readonly SftpClient sftp;
6
7///<summary>
8/// SFTP connect status
9///</summary>
10public 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>
23public 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>
36public bool Connect()
37        {
38try
39            {
40if (!Connected)
41                {
42                    sftp.Connect();
43                }
44return true;
45            }
46catch (Exception ex)
47            {
48throw new Exception($"Disconnect SFTP fail,Error Message:{ex.Message}");
49            }
50        }
51
52#endregion
53
54#region Disconnect SFTP
55
56///<summary>connect下载
57/// Disconnect SFTP
58///</summary>
59public void Disconnect()
60        {
61try
62            {
63if (sftp != null && Connected)
64                {
65                    sftp.Disconnect();
66                }
67            }
68catch (Exception ex)
69            {
70throw 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>
83public void Put(string localPath, string remotePath)
84        {
85try
86            {
87using (var file = File.OpenRead(localPath))
88                {
89                    Connect();
90                    sftp.UploadFile(file, remotePath);
91                    Disconnect();
92                }
93            }
94catch (Exception ex)
95            {
96throw 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>
109public void BatchPut(string localPath, string remotePath)
110        {
111string uploadFullName = "";
112string remoteFullName = "";
113try
114            {
115                Connect();
116                DirectoryInfo fdir = new DirectoryInfo(localPath);
117                FileInfo[] file = fdir.GetFiles();
118
119if (file.Length != 0)
120                {
121foreach (FileInfo f in file) //show all files under the path
122                    {
123using (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            }
133catch (Exception ex)
134            {
135throw 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>
148public void Get(string remotePath, string localPath)
149        {
150try
151            {
152                Connect();
153var byt = sftp.ReadAllBytes(remotePath);
154                Disconnect();
155                File.WriteAllBytes(localPath, byt);
156            }
157catch (Exception ex)
158            {
159throw 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>
171public void Delete(string remoteFile)
172        {
173try
174            {
175                Connect();
176                sftp.Delete(remoteFile);
177                Disconnect();
178            }
179catch (Exception ex)
180            {
181throw 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>
195public ArrayList GetFileList(string remotePath, string fileSuffix)
196        {
197try
198            {
199                Connect();
200var files = sftp.ListDirectory(remotePath);
201                Disconnect();
202var objList = new ArrayList();
203foreach (var file in files)
204                {
205string name = file.Name;
206if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length)) 207                    {
208                        objList.Add(name);
209                    }
210                }
211return objList;
212            }
213catch (Exception ex)
214            {
215throw 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>
228public void Move(string oldRemotePath, string newRemotePath)
229        {
230try
231            {
232                Connect();
233                sftp.RenameFile(oldRemotePath, newRemotePath);
234                Disconnect();
235            }
236catch (Exception ex)
237            {
238throw new Exception($"Move SFTP File Faile,Error Message:{ex.Message}");
239            }
240        }
241
242#endregion
243
244protected virtual void Dispose(bool disposing)
245        {
246if (!disposing) return;
247// dispose managed resources
248            sftp.Dispose();
249// free native resources
250        }
251
252public void Dispose()
253        {
254            Dispose(true);
255            GC.SuppressFinalize(this);
256        }
257 }
View Code

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。