.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 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: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
配置文件内容:
<?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>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.net 操作sftp服务器的更多相关文章
- Linux Centos 6.6搭建SFTP服务器
Linux Centos 6.6搭建SFTP服务器 在Centos 6.6环境使用系统自带的internal-sftp搭建SFTP服务器. 打开命令终端窗口,按以下步骤操作. 0.查看openssh的 ...
- Windows 7下 搭建 基于 ssh 的sftp 服务器
Windows xp 下 搭建 基于 ssh 的sftp 服务器,服务器端可以用 freesshd,F-secure server等,filezilla server不可用,之前傻乎乎的用file ...
- java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息
1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...
- linux搭建sftp服务器
转自:http://blog.csdn.net/superswordsman/article/details/49331539 最近工作需要用到sftp服务器,被网上各种方法尤其是权限设置问题搞得晕头 ...
- Linux课程---3、Linux远程登录和传输(操作Linux服务器软件)
Linux课程---3.Linux远程登录和传输(操作Linux服务器软件) 一.总结 一句话总结: xshell:Xshell是一个强大的安全终端模拟软件 Xshell是一个强大的安全终端模拟软件, ...
- 搭建SFTP服务器,允许一个或多个用户拥有一个或多个目录的rwx权限
1.引言 sftp可以为传输文件提供一种安全的网络的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH的其中一部分,是一种传输档案至 Blogger 伺服器的安全方式.其实 ...
- Linux ---搭建SFTP服务器
在Centos 6.6环境使用系统自带的internal-sftp搭建SFTP服务器. 打开命令终端窗口,按以下步骤操作. 0.查看openssh的版本 ssh -V 使用ssh -V 命令来查看op ...
- SFTP 服务器cd() 方法和 ls() 方法说明
方法说明: cd():这个方法用于进入某个目录下. 默认情况,当连接SFTP服务器成功后直接进入用户目录,比如我连接自己本机SFTP服务器后进入/Users/mac目录.cd() 方法进入每一个目录都 ...
- Java上传文件至SFTP服务器
Windows搭建SFTP服务器 https://www.cnblogs.com/wangjunguang/p/9453611.html 注意点: 1.以管理员权限运行FreeSSHd 2.如果无法启 ...
随机推荐
- linux常用命令之文件系统
df df - report file system disk space usage 查看文件系统的使用清空 用法 df [-hi] [path] 选项 -h human readable ,以人类 ...
- 如何理解javascript closure ?
接触过javascript的人应该听过闭包(closure),有一种观点认为是闭包赋予了javascript的强大能力,也赋予了它具备OOP的特征.既然javascript closure如此重要,那 ...
- 过去几个月出炉的30款最喜欢的 jQuery 插件
在这篇文章中,我们收集了一些在过去的几个月里最喜欢的 jQuery 插件.为了使您更容易搜索到自己喜欢的 jQuery 插件,我们已经对插件进行了分类: 页面布局插件,图片和视频插件,滑块和画廊,排版 ...
- Converse.js – 开源的 XMPP 聊天客户端
Converse.js 是一个运行在浏览器的免费和开源的聊天客户端.它可以集成到任何网页.类似于 Facebook 的聊天,它也支持多用户聊天室.Converse.js 可以连接到任何可访问的 XMP ...
- 分享25个新鲜出炉的 Photoshop 高级教程
网络上众多优秀的 Photoshop 实例教程是提高 Photoshop 技能的最佳学习途径.今天,我向大家分享25个新鲜出炉的 Photoshop 高级教程,提高你的设计技巧,制作时尚的图片效果.这 ...
- URL 路径长度限制(错误:指定的文件或文件夹名称太长)
本节讨论 URL 的构成.SharePoint 2010 构建 URL 的方式.URL 的编码和加长以及作为其他 URL 中的参数传递的方式. SharePoint URL 的构成 SharePoin ...
- JavaScript学习01 语言简介、基本使用和变量声明
JavaScript语言简介.基本使用和变量声明 JavaScript是网景(Netscape)公司开发的一种基于客户端浏览器.面向对象.事件驱动式的网页脚本语言. JavaScript的前身叫Liv ...
- Android UX & UI 最佳实践: 设计有效的导航
Best Practices for User Experience & UI Designing Effective Navigation 导航:帮助用户有效直观地使用你的应用. Plann ...
- Sqlite3中存储类型和数据类型结合文档解析。
sqlite3是个很小的数据库,运行在手机,机顶盒上....那它就不可能像musql,sqlserver那么规范,有很多的数据类型,之前我也以为它定义了很多数据类型,其实不是他就5个存储类,那么多数据 ...
- 【iOS】block的使用
Block 是iOS在4.0之后新增的程式语法,一般用于回调方法,功能上和delegate类似.本文将讲解block的几种常见的使用方法,当然,block中最值得注意的还是它的内存管理,我将在< ...