java连接SFTP工具类

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SFTPUtil {
    private static JSch jsch;
    private static Session session;

    Logger logger = Logger.getLogger(SFTPUtil.class);
    /**
     * 连接到指定的IP
     * 
     * @throws JSchException
     */
    public static void connect(String user, String passwd, String host, int port) throws JSchException {
        jsch = new JSch();// 创建JSch对象
        session = jsch.getSession(user, host, port);// 根据用户名、主机ip、端口号获取一个Session对象
        session.setPassword(passwd);// 设置密码
        session.setConfig("kex","diffie-hellman-group1-sha1");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);// 为Session对象设置properties
        session.setTimeout(1500);// 设置超时
        session.connect();// 通过Session建立连接
        System.out.println("channel is connected");    

    }

    /**
     * 关闭连接
     */
    public static void close() {
        session.disconnect();
    }

    /**
     * 执行相关的命令
     * 
     * @throws JSchException
     */
    public static void execCmd(String command) throws JSchException {
        BufferedReader reader = null;
        Channel channel = null;
        try {
            if (command != null) {
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);
                // ((ChannelExec) channel).setErrStream(System.err);
                channel.connect();

                InputStream in = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                String buf = null;
                while ((buf = reader.readLine()) != null) {
                    System.out.println(buf);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            channel.disconnect();
        }
    }

    /**
     * 上传文件
     *
     * @param directory
     *            上传的目录
     * @param uploadFile
     *            要上传的文件
     * @param sftp
     * @throws JSchException
     * @throws SftpException
     * @throws FileNotFoundException
     */
    public void upload(String directory, String uploadFile) throws JSchException, FileNotFoundException, SftpException {
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.cd(directory);
        File file = new File(uploadFile);
        channelSftp.put(new FileInputStream(file), file.getName());
        System.out.println("Upload Success!");
    }

    public static void uploadSftp(String serverName,String userName, String pwd,String directory, String sftpFileName, byte[] byteArr)throws Exception 
   {
       connect(userName, pwd, serverName, 22); 
       
       upload(directory, sftpFileName, byteArr);
       
       close();
   }
    
    public static void upload(String directory, String sftpFileName, byte[] byteArr) throws Exception{    
      // upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));  
       ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
       try { 
          channelSftp.cd(directory);
      } catch (SftpException e) {  
         e.printStackTrace();
          channelSftp.mkdir(directory);    
          channelSftp.cd(directory);    
      }    
      channelSftp.put(new ByteArrayInputStream(byteArr), sftpFileName);    
   }    

    
    /**
     * 下载文件
     * 
     * @param src
     * @param fos
     * @throws JSchException
     * @throws SftpException
     */
    public static void download(String src, FileOutputStream fos) throws JSchException, SftpException {
        // src linux服务器文件地址,
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(src, fos);
        channelSftp.quit();
    }

    /**
     * 删除文件
     *
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     * @throws SftpException
     * @throws JSchException
     */
    public void delete(String directory, String deleteFile) throws SftpException, JSchException {
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.cd(directory);
        channelSftp.rm(deleteFile);
    }

    /**
     * 列出目录下的文件
     *
     * @param directory
     *            要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     * @throws JSchException
     */
    @SuppressWarnings("rawtypes")
    public static Vector listFiles(String directory) throws JSchException, SftpException 
    {
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        return channelSftp.ls(directory);
    }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

多年前从网上摘抄的,也不知道出处了,用的到的拿去用吧!

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程界小明哥

请博主喝瓶水,博主持续输出!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值