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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 计算机桌面锁写快捷,锁定计算机快捷键_锁定计算机的快捷键

    计算机桌面锁写快捷,锁定计算机快捷键_锁定计算机的快捷键2017-01-0515:11:14当有事需暂时离开,又不想他人动用电脑时,可采取锁定桌面的办法。1、首先要在电脑中设置好一个用户帐户密码(开机密码)。在锁定桌面时,只需按Win十L键(即按住那个有微软视窗图标的键…2016-12-1814:43:081在电脑上键盘上找到Windows键和L键,这两个键就是快速锁定计算机的关键所在步骤阅读2两只手一只手按Windows键,另一只手按L键,…

    2022年7月21日
    14
  • oracle查看密码修改记录_oracle查询数据库用户密码到期时间

    oracle查看密码修改记录_oracle查询数据库用户密码到期时间SQL>showuserUSERis”SYS”SQL>createusert1identifiedbyt1;createusert1identifiedbyt1*ERRORatline1:ORA-01920:username’T1’conflictswithanotheruserorrolenameSQL>dropuse…

    2022年7月28日
    2
  • 企业微信api接口文档_接口文档示例

    企业微信api接口文档_接口文档示例提供一些我自己使用过的api数据接口,让学习前端的朋友可以提早熟练地调用一些Api接口。以下api数据接口主要为一些学过ajax或一些学过vue基础的同学。第一个:网易云音乐的api数据接口,基础访问地址(api的跟地址)为:https://autumnfish.cn/点击查看文档,就可以进入接口文档的详细使用步骤了。这个接口很适合喜欢音乐的朋友去打造属于自己的音乐主页第二个:黑马…

    2022年9月18日
    4
  • 费曼学习法

    费曼学习法费曼学习法我的理解:费曼学习法就是把学好的东西用简洁易懂的语言,传授给别人举例:你学完微积分,然后自己去培训班,自己做老师,传授给学生们,并且学生们都能听懂费曼学习法的四个步骤:1.确定目标

    2022年8月6日
    5
  • FlashFXP 5.4.0 注册

    FlashFXP 5.4.0 注册打开软件点击–帮助–关于–点击–右边中部的钥匙输入以下全部字母数字  FLASHFXPwQAOlhkgwQAAAAC6W5MNJwTnsl73nIraAU149tnCQS   0hmZU3GGBQG1FtoSp5x0mUgA7bFW0qr0fKk2KCA+v2CCrFbF+q   bmLvEjV+4JCAX+H/TBpG7pdEJ8IEW09ST8t60Poou/…

    2022年7月26日
    35
  • linux rwx 权限「建议收藏」

    linux rwx 权限「建议收藏」@linuxrwx权限欢迎使用Markdown编辑器你好!这是你第一次使用Markdown编辑器所展示的欢迎页。如果你想学习如何使用Markdown编辑器,可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。新的改变我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:全新的界面设计,将会带来全新的写作体验;在创作中心设置你喜爱的代码高亮样式,Markdown将代码片显示选择的高亮样

    2022年5月2日
    58

发表回复

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

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