Sftp连接和读取文件

9 篇文章 0 订阅
2 篇文章 0 订阅

开发过程中,需求:连接到远程sftp服务器并读取其中的文件。

1.使用com.jcraft.jsch包中工具建立session连接远程sftp服务器


public static Channel connect(String username, String host, int port, String password) throws JSchException {
        Session session = null;
        Channel channel = null;
        long start = System.currentTimeMillis();
        JSch jSch = new JSch();
        session = jSch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        // 设置不用检查hostKey
        // 如果设置成“yes”,ssh就会自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件,
        // 并且一旦计算机的密匙发生了变化,就拒绝连接
        config.put("StrictHostKeyChecking", "no");
        // UseDNS选项打开状态下,当客户端试图登录OpenSSH服务器时,服务器端先根据客户端的IP地址进行DNS PTR反向查询,查询出客户端的host name,然后根据查询出的客户端host name进行DNS 正向A记录查询,验证与其原始IP地址是否一致
        // 这是防止客户端欺骗的一种手段,但一般我们的IP是动态的,不会有PTR记录的,打开这个选项不过是在白白浪费时间而已。
        // 默认值是 “yes” ,为了提高效率减少时间消耗,则把UseDNS设置为“no”
        // 用域名访问时才将此选项打开
        config.put("UseDNS", "no");
        session.setConfig(config);
        session.connect(connectTimeOut);
        session.setTimeout(readTimeOut);
        channel = session.openChannel("sftp");
        channel.connect();
        long end = System.currentTimeMillis();
        info_log.info("成功登陆sftp,登陆耗时:[" + (end - start) + "]毫秒");
        return channel;
}

2.根据返回的channel列举服务器上文件,并依次按行读取文件内容

ChannelSftp channel = null;
try {
    //连接远程sftp
    channel = (ChannelSftp) FtpUtil.connect(ftpUserName, ftpHost, ftpPort, ftpPasswd);

    Vector<ChannelSftp.LsEntry> ftpFiles = channel.ls(ftpRootDir);//列举指定目录中文件
    if (ftpFiles != null && ftpFiles.size() > 0) {
        for (LsEntry lsEntry : ftpFiles) {
            String filename = lsEntry.getFilename();
            BufferedReader bufferedReader = null;

            try {
                channel.cd(ftpRootDir);//进入指定目录操作
                InputStream inputStream = channel.get(filename);
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                String tempString = null;
                while ((tempString = bufferedReader.readLine()) != null) {
                    //....数据处理
                }

            } catch (Exception e) {

            } finally {
                try {
                    if (bufferedReader != null)
                        bufferedReader.close();//关闭流
                } catch (IOException e) {
                    log.error("Close BufferedReader error:", e);
                }
            }               
        }
    }
            
} catch (Exception e) {
} finally {
    //记得关闭连接
    if (channel != null) {
        channel.quit();
        channel.disconnect();

        try {
            if (channel.getSession() != null)
                channel.getSession().disconnect();
                    
            } catch (JSchException e) {
                    log.error("channel getSession error:", e);
        }
}

 

 

 

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值