一、Renci.SshNet
首先添加下方库
创建类
using log4net;
using Renci.SshNet;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ftp
{
public class SFTPHelper
{
#region 字段或属性
private SftpClient sftp;
/// <summary>
/// SFTP连接状态
/// </summary>
public bool Connected { get { return sftp.IsConnected; } }
#endregion
#region 构造
/// <summary>
/// 构造
/// </summary>
/// <param name="ip">IP</param>
/// <param name="port">端口</param>
/// <param name="user">用户名</param>
/// <param name="pwd">密码</param>
public SFTPHelper(string ip, string port, string user, string pwd)
{
sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
sftp.BufferSize = uint.MaxValue;
//Connect();
}
~SFTPHelper()
{
Disconnect();
}
#endregion
#region 连接SFTP
/// <summary>
/// 连接SFTP
/// </summary>
/// <returns>true成功</returns>
public bool Connect()
{
try
{
if (!Connected)
{
sftp.Connect();
}
return true;
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"连接SFTP失败,原因:{ex}");
throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
return false;
}
}
#endregion
#region 断开SFTP
/// <summary>
/// 断开SFTP
/// </summary>
public void Disconnect()
{
try
{
if (sftp != null && Connected)
{
sftp.Disconnect();
}
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"断开SFTP失败,原因:{ex}");
throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
}
}
#endregion
#region SFTP上传文件
public bool IsExist(string path)
{
bool result = false;
try
{
if (!Connected)
Connect();
result = sftp.Exists(path);
Disconnect();
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
}
return result;
}
public void CreateDirectory(string remotePath)
{
try
{
if (!Connected)
Connect();
sftp.CreateDirectory(remotePath);
Disconnect();
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
}
}
/// <summary>
/// SFTP上传文件
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="remotePath">远程路径</param>
public bool Put(string localPath, string remotePath)
{
try
{
using (var file = File.OpenRead(localPath))
{
if (!Connected)
Connect();
if (!Connected)
return false;
//sftp.BufferSize = uint.MaxValue;
//sftp.ChangeDirectory(remotePath);
sftp.UploadFile(file, remotePath, true);
Disconnect();
}
return true;
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
return false;
}
}
#endregion
#region SFTP获取文件
/// <summary>
/// SFTP获取文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localPath">本地路径</param>
public void Get(string remotePath, string localPath)
{
try
{
if (!Connected)
Connect();
var byt = sftp.ReadAllBytes(remotePath);
Disconnect();
File.WriteAllBytes(localPath, byt);
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件获取失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
}
}
#endregion
#region 删除SFTP文件
/// <summary>
/// 删除SFTP文件
/// </summary>
/// <param name="remoteFile">远程路径</param>
public void Delete(string remoteFile)
{
try
{
if (!Connected)
Connect();
sftp.Delete(remoteFile);
Disconnect();
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件删除失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
}
}
#endregion
#region 获取SFTP文件列表
/// <summary>
/// 获取SFTP文件列表
/// </summary>
/// <param name="remotePath">远程目录</param>
/// <param name="fileSuffix">文件后缀</param>
/// <returns></returns>
public ArrayList GetFileList(string remotePath, string fileSuffix)
{
var objList = new ArrayList();
try
{
if (!Connected)
Connect();
var files = sftp.ListDirectory(remotePath);
Disconnect();
foreach (var file in files)
{
string name = file.Name;
objList.Add(name);
}
return objList;
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件列表获取失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
return objList;
}
}
#endregion
#region 移动SFTP文件
/// <summary>
/// 移动SFTP文件
/// </summary>
/// <param name="oldRemotePath">旧远程路径</param>
/// <param name="newRemotePath">新远程路径</param>
public void Move(string oldRemotePath, string newRemotePath)
{
try
{
if (!Connected)
Connect();
sftp.RenameFile(oldRemotePath, newRemotePath);
Disconnect();
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件移动失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
}
}
#endregion
#region 下载
public int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "/" + fileName;
string remoteFileName = filePath + "/" + fileName;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
if (!sftp.IsConnected)
sftp.Connect();
using (var file = File.OpenWrite(localFileName))
{
sftp.DownloadFile(remoteFileName, file);
}
sftp.Disconnect();
//Log.getInstace().WriteSysInfo("下载文件{localFileName}成功", "info");
//LogManager.GetLogger("Debug").Info($"下载文件成功,文件路径:{localFileName}");
Console.WriteLine($"下载文件成功,文件路径:{localFileName}");
return 0;
}
}
catch (Exception ex)
{
//LogManager.GetLogger("Debug").Info($"SFTP文件移动失败,原因:{ex}");
throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
return -2;
}
}
#endregion
}
}
二、Tamir.Ssh
首先引用
创建类
public class SFTPHelperTamirSharpSsh
{
#region 本类调用方法示例
//SFTPHelper sftp = new SFTPHelper("127.0.11.11", "root", "root"); //端口号默认22,不需要填写
// sftp.Connect();
//sftp.Get("\\dpss\\b9bae449-d1cb-491d-b58e-1d149fdb78b5.gif", "D:\\"); //下载(注意斜杠)
//sftp.Put("D:\\aa.txt", "\\dpss\\"); //上传(注意斜杠)
//sftp.Disconnect();
#endregion
private Session m_session;
private Channel m_channel;
private ChannelSftp m_sftp;
//host:sftp地址 user:用户名 pwd:密码
public SFTPHelperTamirSharpSsh(string host, string user, string pwd)
{
string[] arr = host.Split(':');
string ip = arr[0];
int port = 22;
if (arr.Length > 1) port = Int32.Parse(arr[1]);
JSch jsch = new JSch();
m_session = jsch.getSession(user, ip, port);
MyUserInfo ui = new MyUserInfo();
ui.setPassword(pwd);
m_session.setUserInfo(ui);
}
//SFTP连接状态
public bool Connected { get { return m_session.isConnected(); } }
//连接SFTP
public bool Connect()
{
try
{
if (!Connected)
{
m_session.connect();
m_channel = m_session.openChannel("sftp");
m_channel.connect();
m_sftp = (ChannelSftp)m_channel;
}
return true;
}
catch
{
return false;
}
}
//断开SFTP
public void Disconnect()
{
if (Connected)
{
m_channel.disconnect();
m_session.disconnect();
}
}
//SFTP存放文件
public bool Put(string localPath, string remotePath)
{
try
{
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
m_sftp.put(src, dst);
return true;
}
catch
{
return false;
}
}
//SFTP获取文件
public bool Get(string remotePath, string localPath)
{
try
{
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
m_sftp.get(src, dst);
return true;
}
catch
{
return false;
}
}
//删除SFTP文件
public bool Delete(string remoteFile)
{
try
{
m_sftp.rm(remoteFile);
return true;
}
catch
{
return false;
}
}
//获取SFTP文件列表
public ArrayList GetFileList(string remotePath, string fileType)
{
try
{
Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
ArrayList objList = new ArrayList();
foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
{
string sss = qqq.getFilename();
if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
{ objList.Add(sss); }
else { continue; }
}
return objList;
}
catch
{
return null;
}
}
//登录验证信息
public class MyUserInfo : UserInfo
{
String passwd;
public String getPassword() { return passwd; }
public void setPassword(String passwd) { this.passwd = passwd; }
public String getPassphrase() { return null; }
public bool promptPassphrase(String message) { return true; }
public bool promptPassword(String message) { return true; }
public bool promptYesNo(String message) { return true; }
public void showMessage(String message) { }
}
}
三、WinSCP
添加引用
下载软件放到程序根目录
创建类
public class WinSCPHelper
{
/// <summary>
/// WinSCP数据传输
/// </summary>
/// <param name="winscptype">选择操作方式:上传、下载</param>
/// <param name="srcPath">源目录</param>
/// <param name="objPath">目标目录</param>
/// <param name="hostName">IP地址</param>
/// <param name="userName">账户</param>
/// <param name="password">密码</param>
/// <returns></returns>
public bool WinSCP(WinSCPType winscptype, string srcPath, string objPath, string hostName, string userName, string password, int portNumber, string sshHostKeyFingerprint)
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = hostName,
UserName = userName,
Password = password,
SshHostKeyFingerprint = sshHostKeyFingerprint //"ssh-rsa 2048 xxxxxxxxxxx..."使用WinSCP.exe 程序,添加一个连接方式并登录。
//登录后在Session选项中 选择 Generate Session URL/Code .查询软件生成的代码即可获取密钥
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
//transferResult =
// session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);
switch (winscptype)
{
case WinSCPType.Download:
transferResult = session.GetFiles(srcPath, objPath, false, transferOptions);
break;
case WinSCPType.Upload:
transferResult = session.PutFiles(srcPath, objPath, false, transferOptions);
break;
default:
transferResult = session.GetFiles(srcPath, objPath, false, transferOptions);
break;
}
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
//Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
LogManager.GetLogger("Debug").Info($"Upload of {transfer.FileName} succeeded" );
}
}
return true;
}
catch (Exception e)
{
//Console.WriteLine("Error: {0}", e);
LogManager.GetLogger("Debug").Info($"\"Error: {e}");
return false;
}
}
public enum WinSCPType
{
Download = 0,
Upload = 1
}
}
PS:服务器搭建测试可使用freeSSHd