你的位置:首页 > ASP.net教程

[ASP.net教程].net 操作sftp服务器


因为项目的需要,整理了一段C#操作sftp的方法。

依赖的第三方类库名称为:SharpSSH 1.1.1.13.

代码如下:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Collections.Specialized;
  6: using System.Configuration;
  7: using Tamir.SharpSsh;
  8: using System.IO;
  9: using Tamir.SharpSsh.jsch;
 10:  
 11: namespace TestSftp
 12: {
 13:   /// <summary>
 14:   /// 访问Sftp服务器方法(连凭证数请在config文件中配置)
 15:   /// </summary>
 16:   public class SftpClient : IDisposable
 17:   {
 18:     #region Properties
 19:  
 20:     /// <summary>
 21:     /// 主机名或IP
 22:     /// </summary>
 23:     public string HostName { get; private set; }
 24:     /// <summary>
 25:     /// 用户名
 26:     /// </summary>
 27:     public string UserName { get; private set; }
 28:     /// <summary>
 29:     /// 密码
 30:     /// </summary>
 31:     public string Password { get; private set; }
 32:  
 33:     /// <summary>
 34:     /// 端口号(默认端口为22)
 35:     /// </summary>
 36:     public int Port { get; private set; }
 37:  
 38:     #endregion    
 39:  
 40:     private static readonly string defRemotePath = "/";//默认操作是都是从根目录开始。
 41:     private ChannelSftp m_sftp;
 42:     private Session m_session;
 43:     Channel m_channel;
 44:  
 45:     /// <summary>
 46:     /// 从配置文件中加载凭证信息
 47:     /// </summary>    
 48:     public SftpClient()
 49:     {
 50:       var config = ConfigurationManager.GetSection("SftpServer") as NameValueCollection;
 51:       this.HostName = config["host_name"];
 52:       this.UserName = config["user_name"];
 53:       this.Password = config["password"];
 54:       this.Port = Convert.ToInt32(config["port"] ?? "22");//默认端口为22    
 55:     }
 56:  
 57:     #region Events
 58:  
 59:     /// <summary>
 60:     /// SFTP获取文件  
 61:     /// </summary>
 62:     /// <param name="remotePath"></param>
 63:     /// <param name="localPath"></param>
 64:     /// <returns></returns>
 65:  
 66:     public bool Get(string remotePath, string localPath)
 67:     {
 68:       try
 69:       {
 70:         string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
 71:         Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(fullRemotePath);
 72:         Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
 73:         m_sftp.get(src, dst);
 74:         return true;
 75:       }
 76:       catch
 77:       {
 78:         return false;
 79:       }
 80:     }
 81:  
 82:     /// <summary>
 83:     ///SFTP存放文件  
 84:     /// </summary>
 85:     /// <param name="localPath"></param>
 86:     /// <param name="remotePath"></param>
 87:     /// <returns></returns>
 88:     public void Put(string localPath, string remotePath)
 89:     {
 90:       Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
 91:       string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
 92:       Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(fullRemotePath);
 93:       m_sftp.put(src, dst);
 94:     }
 95:  
 96:  
 97:     /// <summary>
 98:     /// 删除SFTP文件 
 99:     /// </summary>
 100:     /// <param name="remoteFile"></param>
 101:     /// <returns></returns>
 102:  
 103:     public void Delete(string remoteFile)
 104:     {
 105:       string fullRemotePath = defRemotePath + remoteFile.TrimStart('/');
 106:       m_sftp.rm(fullRemotePath);
 107:     }
 108:     /// <summary>
 109:     /// 获取SFTP文件列表  
 110:     /// </summary>
 111:     /// <param name="remotePath"></param>
 112:     /// <param name="fileType">文件后缀名称(.txt)</param>
 113:     /// <returns></returns>
 114:     public List<string> GetFileList(string remotePath, string fileType)
 115:     {
 116:       string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
 117:       Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(fullRemotePath);
 118:       List<string> objList = new List<string>();
 119:       foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
 120:       {
 121:         string sss = qqq.getFilename();
 122:         if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
 123:         { objList.Add(sss); }
 124:         else { continue; }
 125:       }
 126:       return objList;
 127:     }
 128:  
 129:     /// <summary>
 130:     /// 目录是否存在
 131:     /// </summary>
 132:     /// <param name="dirName">目录名称必须从根开始</param>
 133:     /// <returns></returns>
 134:     public bool DirExist(string dirName)
 135:     {
 136:       try
 137:       {
 138:         m_sftp.ls(defRemotePath + dirName.TrimStart('/'));
 139:         return true;
 140:       }
 141:       catch (Tamir.SharpSsh.jsch.SftpException)
 142:       {
 143:         return false;//执行ls命令时出错,则目录不存在。
 144:       }
 145:     }
 146:  
 147:     /// <summary>
 148:     /// 创建目录
 149:     /// </summary>
 150:     /// <param name="dirName">目录名称必须从根开始</param>
 151:     /// <returns></returns>
 152:     public void Mkdir(string dirName)
 153:     {
 154:       Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(defRemotePath);
 155:       foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry fileName in vvv)
 156:       {
 157:         string name = fileName.getFilename();
 158:         if (name == dirName)
 159:         {
 160:           throw new Exception("dir is exist");
 161:         }
 162:       }
 163:       m_sftp.mkdir(defRemotePath + dirName.TrimStart('/'));
 164:     }
 165:  
 166:     /// <summary>
 167:     /// SFTP连接状态  
 168:     /// </summary>
 169:     public bool Connected
 170:     {
 171:       get { return m_session.isConnected(); }
 172:     }
 173:  
 174:     /// <summary>
 175:     /// 连接SFTP  
 176:     /// </summary>
 177:     public void ConnectSftp()
 178:     {
 179:       JSch jsch = new JSch();  //利用java实现的通讯包 
 180:       m_session = jsch.getSession(this.UserName, this.HostName, this.Port);
 181:       m_session.setHost(this.HostName);
 182:       MyUserInfo ui = new MyUserInfo();
 183:       ui.setPassword(this.Password);
 184:       m_session.setUserInfo(ui);
 185:  
 186:       if (!Connected)
 187:       {
 188:         m_session.connect();
 189:         m_channel = m_session.openChannel("sftp");
 190:         m_channel.connect();
 191:         m_sftp = (ChannelSftp)m_channel;
 192:       }
 193:     }
 194:  
 195:     /// <summary>
 196:     /// 断开SFTP  
 197:     /// </summary>
 198:     public void DisconnectSftp()
 199:     {
 200:       if (Connected)
 201:       {
 202:         m_channel.disconnect();
 203:         m_session.disconnect();
 204:       }
 205:     }   
 206:  
 207:  
 208:  
 209:     #endregion    
 210:  
 211:     //登录验证信息      
 212:     private class MyUserInfo : UserInfo
 213:     {
 214:       String passwd;
 215:       public String getPassword() { return passwd; }
 216:       public void setPassword(String passwd) { this.passwd = passwd; }
 217:  
 218:       public String getPassphrase() { return null; }
 219:       public bool promptPassphrase(String message) { return true; }
 220:  
 221:       public bool promptPassword(String message) { return true; }
 222:       public bool promptYesNo(String message) { return true; }
 223:       public void showMessage(String message) { }
 224:     }
 225:  
 226:     public void Dispose()
 227:     {
 228:       this.DisconnectSftp();
 229:     }
 230:   }
 231:  
 232:  
 233: }