惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
S
SegmentFault 最新的问题
V
Visual Studio Blog
J
Java Code Geeks
宝玉的分享
宝玉的分享
美团技术团队
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
有赞技术团队
有赞技术团队
量子位
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
博客园 - 叶小钗
月光博客
月光博客
P
Proofpoint News Feed
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog

博客园 - Ants

我用 AI 辅助开发了一系列小工具(2):图片压缩工具 我用 AI 辅助开发了一系列小工具(1):文件提取工具 Spring Cloud中,Eureka常见问题总结 部署Spring Boot应用 C# FTP 命令无法获取ServerU目录列表问题 redis参数优化 memcached在windows下多实例并存 开源一个windows下的定时任务框架,简单粗暴好用。 WebRequest 访问 https Python定时任务框架APScheduler 3.0.3 Cron示例 Eclipse安装python注意事项 C# 计算文件MD5 C# 为私有方法添加单元测试(反射) 在ASP.NET MVC中使用Unity进行依赖注入的三种方式 ASP.NET Web API 安全筛选器 Token Based Authentication in Web API 2 IIS中查看W3P.exe进程对应的应用程序池的方法 WCF自定义Header sqlserver 用 RowNumber 分组
.net 操作sftp服务器
Ants · 2015-04-21 · via 博客园 - Ants

因为项目的需要,整理了一段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 CET.Finance.SftpWinService.Common
  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:              this.ConnectSftp();
  56:          }
  57:   
  58:          #region Events
  59:   
  60:          /// <summary>
  61:          /// SFTP获取文件   
  62:          /// </summary>
  63:          /// <param name="remotePath"></param>
  64:          /// <param name="localPath"></param>
  65:          /// <returns></returns>
  66:   
  67:          public bool Get(string remotePath, string localPath)
  68:          {
  69:              try
  70:              {
  71:                  string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
  72:                  Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(fullRemotePath);
  73:                  Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
  74:                  m_sftp.get(src, dst);
  75:                  return true;
  76:              }
  77:              catch
  78:              {
  79:                  return false;
  80:              }
  81:          }
  82:   
  83:          /// <summary>
  84:          ///SFTP存放文件   
  85:          /// </summary>
  86:          /// <param name="localPath"></param>
  87:          /// <param name="remotePath"></param>
  88:          /// <returns></returns>
  89:          public void Put(string localPath, string remotePath)
  90:          {
  91:              Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
  92:              string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
  93:              Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(fullRemotePath);
  94:              m_sftp.put(src, dst);
  95:          }
  96:   
  97:   
  98:          /// <summary>
  99:          /// 删除SFTP文件 
 100:          /// </summary>
 101:          /// <param name="remoteFile"></param>
 102:          /// <returns></returns>
 103:   
 104:          public void Delete(string remoteFile)
 105:          {
 106:              string fullRemotePath = defRemotePath + remoteFile.TrimStart('/');
 107:              m_sftp.rm(fullRemotePath);
 108:          }
 109:          /// <summary>
 110:          /// 获取SFTP文件列表   
 111:          /// </summary>
 112:          /// <param name="remotePath"></param>
 113:          /// <param name="fileType">文件后缀名称(.txt)</param>
 114:          /// <returns></returns>
 115:          public List<string> GetFileList(string remotePath, string fileType)
 116:          {
 117:              List<string> objList = new List<string>();
 118:              string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
 119:              if (DirExist(fullRemotePath))
 120:              {
 121:                  Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(fullRemotePath);
 122:                  foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
 123:                  {
 124:                      string sss = qqq.getFilename();
 125:                      if (fileType.Contains(Path.GetExtension(sss)))
 126:                      { 
 127:                          objList.Add(sss);
 128:                      }                  
 129:                  }
 130:              }
 131:              return objList;
 132:          }
 133:   
 134:          /// <summary>
 135:          /// 目录是否存在
 136:          /// </summary>
 137:          /// <param name="dirName">目录名称必须从根开始</param>
 138:          /// <returns></returns>
 139:          public bool DirExist(string dirName)
 140:          {
 141:              try
 142:              {
 143:                  m_sftp.ls(defRemotePath + dirName.TrimStart('/'));
 144:                  return true;
 145:              }
 146:              catch (Tamir.SharpSsh.jsch.SftpException)
 147:              {
 148:                  return false;//执行ls命令时出错,则目录不存在。
 149:              }
 150:          }
 151:   
 152:          /// <summary>
 153:          /// 创建目录
 154:          /// </summary>
 155:          /// <param name="dirName">目录名称必须从根开始</param>
 156:          /// <returns></returns>
 157:          public void Mkdir(string dirName)
 158:          {
 159:              Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(defRemotePath);
 160:              foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry fileName in vvv)
 161:              {
 162:                  string name = fileName.getFilename();
 163:                  if (name == dirName)
 164:                  {
 165:                      throw new Exception("dir is exist");
 166:                  }
 167:              }
 168:              m_sftp.mkdir(defRemotePath + dirName.TrimStart('/'));
 169:          }
 170:   
 171:          /// <summary>
 172:          /// 连接SFTP   
 173:          /// </summary>
 174:          public void ConnectSftp()
 175:          {
 176:              JSch jsch = new JSch();   //利用java实现的通讯包  
 177:              m_session = jsch.getSession(this.UserName, this.HostName, this.Port);
 178:              m_session.setHost(this.HostName);
 179:              MyUserInfo ui = new MyUserInfo();
 180:              ui.setPassword(this.Password);
 181:              m_session.setUserInfo(ui);
 182:   
 183:              if (!m_session.isConnected())
 184:              {
 185:                  m_session.connect();
 186:                  m_channel = m_session.openChannel("sftp");
 187:                  m_channel.connect();
 188:                  m_sftp = (ChannelSftp)m_channel;
 189:              }
 190:          }
 191:   
 192:          /// <summary>
 193:          /// 断开SFTP    
 194:          /// </summary>
 195:          public void DisconnectSftp()
 196:          {
 197:              if (m_session.isConnected())
 198:              {
 199:                  m_channel.disconnect();
 200:                  m_session.disconnect();
 201:              }
 202:          }
 203:   
 204:          #endregion
 205:   
 206:          //登录验证信息            
 207:          private class MyUserInfo : UserInfo
 208:          {
 209:              String passwd;
 210:              public String getPassword() { return passwd; }
 211:              public void setPassword(String passwd) { this.passwd = passwd; }
 212:   
 213:              public String getPassphrase() { return null; }
 214:              public bool promptPassphrase(String message) { return true; }
 215:   
 216:              public bool promptPassword(String message) { return true; }
 217:              public bool promptYesNo(String message) { return true; }
 218:              public void showMessage(String message) { }
 219:          }
 220:   
 221:          public void Dispose()
 222:          {
 223:              this.DisconnectSftp();
 224:              this.m_channel = null;
 225:              this.m_session = null;
 226:              this.m_sftp = null;
 227:          }
 228:      }
 229:   
 230:  }

配置文件内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="SftpServer" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  
  <SftpServer>
    <add key="host_name" value="127.0.0.1"/>
    <add key="user_name" value="test"/>
    <add key="password" value="123"/>
  </SftpServer>   
  
</configuration>