C# 连接SFTP

C# 连接SFTPC#连接SFTP网上学习到C#连接SFTP方式,整理了一下,文章结尾处为具体的调用方式以及密钥文件的转换。SFTPHelper.c文件:usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Collections.Specialized;usingSystem.Configuration;usingSystem.Linq;usingSystem.Text;using

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

C# Tamir.SharpSsh连接SFTP

网上学习到C#连接SFTP方式,整理了一下,文章结尾处为具体的调用方式以及密钥文件的转换。

SFTPHelper.cs文件:

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) { 
    }
        }
    }
}

具体调用方法:

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.net/179141.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java通过cglib动态生成实体bean

    java通过cglib动态生成实体beanDynamicBeanEntity.class动态bean类:packagecom.dym.entity;importnet.sf.cglib.beans.BeanGenerator;importorg.apache.commons.collections.map.MultiValueMap;importjava.lang.reflect.*;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.It

    2022年6月13日
  • zookeeper入门教程_kubernetes github

    zookeeper入门教程_kubernetes githubzookeeperwatcher架构zookeeper 配置中心分布式ID分布式锁集群搭建数据一致性协议:zab协议Zookeeper Leader选举Observer角色及其配置watcher架构客户端首先将Watcher注册到服务器,同时将Watch对象保存到客户端的Watch管理器中。当Zookeeper服务器监听到的数据发生变化时,服务器会通知客户端,接着客户端的Watch管理器会触发相关的Watcher来回调响应处理逻辑,从而完成整体的数据发布/订阅流程。javaAPIJava

    2022年8月9日
  • Effective_STL 学习笔记(十一) 理解自定义分配器的正确用法

    Effective_STL 学习笔记(十一) 理解自定义分配器的正确用法

    2021年6月17日
  • 聊一聊Zabbix都监控哪些参数

    聊一聊Zabbix都监控哪些参数面试中的话,经常被问到技术方面的问题,也就是知识点的掌握程度,如果你准备充分的话,这个到不难,但一些开放性的东西,你可能答得就不是很好,便来到了我们的正题Zabbix监控哪些参数呢?这个范围是比较大、比较开放的,阔以以点带面的回答,也可概括性的回答,下面列举一些数据库:磁盘使用情况、内存使用情况、并发链接数量 数据库增删改查的频率、主从状态、缓冲池web:web服务是否正常、订单是否能正常下单注册是否正常、服务的响应时间、服务的并发量磁盘:使用率、block数,Inode数

    2022年6月14日
  • 股票软件开发

    股票软件开发求助编辑百科名片股票软件开发顾名思义就是股票软件开发公司为公司或个人开发制作自已个性化的股票分析软件,从此彻底告别依赖别人的技术平台支持,从股票软件名称,公司LOGO,启动界面,系统功能,特色指标、特色选股、软件注册后台,信息发布平台,机构数据,主力行情,大盘分析,个股分析,资金分析,热点分析等等一系列功能上实行自已品牌化管理运行。目录

    2022年4月10日
  • 2013.09.18《Win7旗舰版序列号》「建议收藏」

    2013.09.18《Win7旗舰版序列号》「建议收藏」TG664-TJ7YK-2VY3K-4YFY6-BCXF4MVG64-RQDVY-KB9RM-MX9WT-MW824TDTY2-6HJ49-46PCK-6HY88-KQXXXFKDJ2-RCXKD-TFW4H-2PTGK-MMMH8H67R8-4HCH4-WGVKX-GV888-8D79BJ4M92-42VH8-M9JWJ-BR7H6-KTFP676RJX-HDXWD-8BYQJ-GR

    2022年7月20日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号