大家好,又见面了,我是你们的朋友
C# Tamir.SharpSsh连接SFTP
网上学习到C#连接SFTP方式,整理了一下,文章结尾处为具体的调用方式以及密钥文件的转换。
SFTPHelper.cs文件:
代码语言:javascript复制using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using Tamir.SharpSsh.jsch;
namespace Pfizer.EDIDataCollection.Framework
{
public class SFTPHelper
{
private Session m_session;
private Channel m_channel;
private ChannelSftp m_sftp;
//host:sftp地址 user:用户名 pwd:密码
public SFTPHelper(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();
const string passphrase = "";
const string privateKey = "";
if (!"".Equals(privateKey))
{
if (!"".Equals(passphrase))
{
//设置带口令的密钥
jsch.addIdentity(privateKey, passphrase);
}
else
{
//设置不带口令的密钥
jsch.addIdentity(privateKey);
}
}
//设置密钥和密码
m_session = jsch.getSession(user, ip, port);
MyUserInfo ui = new MyUserInfo();
ui.setPassword(pwd);
m_session.setUserInfo(ui);
}
/// <summary>
/// 新增构造函数(1个参数)
/// </summary>
/// <param name="sftpSectionName">sftp服务器配置节点名称</param>
public SFTPHelper(string sftpSectionName)
{
var config = System.Configuration.ConfigurationManager.GetSection(sftpSectionName) as NameValueCollection;
string host = config["host_name"];
string user = config["user_name"];
string password = config["password"];
string passphrase = config["passphrase"];
string privateKey = AppDomain.CurrentDomain.BaseDirectory config["privateKey"];
string[] arr = host.Split(':');
string ip = arr[0];
int port = 22;
if (arr.Length > 1) port = Int32.Parse(arr[1]);
JSch jsch = new JSch();
//const string passphrase = passphrase;
//const string privateKey = privateKeyPath;
if (!"".Equals(privateKey))
{
if (!"".Equals(passphrase))
{
//设置带口令的密钥
jsch.addIdentity(privateKey, passphrase);
}
else
{
//设置不带口令的密钥
jsch.addIdentity(privateKey);
}
}
//设置密钥和密码
m_session = jsch.getSession(user, ip, port);
MyUserInfo ui = new MyUserInfo();
ui.setPassword(password);
m_session.setUserInfo(ui);
}
public SFTPHelper()
{
var config = ConfigurationManager.GetSection("sftpServer") as NameValueCollection;
string host = config["host_name"];
string user = config["user_name"];
string pwd = config["password"];
string passphrase = config["passphrase"];
string privateKey = AppDomain.CurrentDomain.BaseDirectory config["privateKey"];
string[] arr = host.Split(':');
string ip = arr[0];
int port = Convert.ToInt32(config["port"] ?? "22");//默认端口为22
if (arr.Length > 1) port = Int32.Parse(arr[1]);
JSch jsch = new JSch();
if (!"".Equals(privateKey))
{
if (!"".Equals(passphrase))
{
//设置带口令的密钥
jsch.addIdentity(privateKey, passphrase);
}
else
{
//设置不带口令的密钥
jsch.addIdentity(privateKey);
}
}
//设置密钥和密码
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(Exception ex)
{
LogHelper.Error("ERROR", ex);
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;
// }
//}
//public bool Put(string localPath)
//{
// try
// {
// var config = ConfigurationManager.GetSection("sftpServer") as NameValueCollection;
// string remotePath = config["upload"];
// 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;
// }
//}
/// <summary>
/// 增加配置节
/// </summary>
/// <param name="localPath"></param>
/// <param name="configSection"></param>
/// <returns></returns>
public bool Put(string localPath, string remotePath, string configSection)
{
try
{
var config = ConfigurationManager.GetSection(configSection) as NameValueCollection;
//string remotePath = config[remotePath];
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(config[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;
}
}
public bool Get(string remotePath, string localPath, string filetype)
{
try
{
var config = ConfigurationManager.GetSection("sftpServer") as NameValueCollection;
remotePath = config["download"];
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath filetype);
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;
}
}
public bool Delete(string fileType, string filepath)
{
try
{
var config = ConfigurationManager.GetSection("sftpServer") as NameValueCollection;
string remotePath = config[filepath];
m_sftp.rm(remotePath fileType);
return true;
}
catch
{
return false;
}
}
public bool Delete(string fileType, string filepath, string configSection)
{
try
{
var config = ConfigurationManager.GetSection(configSection) as NameValueCollection;
string remotePath = config[filepath];
m_sftp.rm(remotePath fileType);
return true;
}
catch
{
return false;
}
}
//获取SFTP文件列表
public ArrayList GetFileList(string filepath, string fileType)
{
try
{
var config = ConfigurationManager.GetSection("sftpServer") as NameValueCollection;
string remotePath = config[filepath];
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) && sss.Contains(fileType))
{
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) {
}
}
}
}
具体调用方法:
代码语言:javascript复制SFTPHelper sftp = new SFTPHelper("("sftpServerVirtualMeeting"); "); // ("sftpServerVirtualMeeting"); 为config中配置的信息
//首先连接
sftp.Connect()
//连通后可调用其他方法例如
//上传文件 zipPath为上传文件路径 sftpServerVirtualMeeting为
sftp.Put(zipPath, "upload", "sftpServerVirtualMeeting");
//config中配置的上传到sftp地址
//最后关闭连接
sftp.Disconnect();
config 中配置:
<sftpServerVirtualMeeting>
<add key="host_name" value="xxxxx.xxx.com" />
<add key="user_name" value="账号" />
<add key="password" value="密码" />
<add key="passphrase" value="密码" />
<add key="privateKey" value="密钥文件名称" />
<add key="upload" value="上传到sftp地址" />
<add key="download" value="上传到sftp地址" />
<add key="port" value="22" />//端口号
</sftpServerVirtualMeeting>
密钥文件转换:
需要借用工具PuTTYgen 软件 将ppk文件转换成pem文件后可放入代码中使用(我接触的项目只涉及 到单一sftp密钥上传,如若涉及多个sftp密钥,还请自行百度动态转换ppk格式)
ppk转pem: https://blog.csdn.net/albertfly/article/details/76401176
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/179141.html原文链接:https://javaforall.cn