Sftp实现连接的方法

package logSFTP;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SftpTool
{
 
 private Session session = null;
 
 private ChannelSftp channel = null;
 
 private String sftpUserName;
 
 private String sftpServerIp;
 
 private String sftpPassword;
 
 private int sftpPort;
 
 /**
  * 开始连接
  */
 public String connected (String serverIp, String userName, String password ,int port)
 {
  String msg = "";
  
  this.sftpServerIp = serverIp;
  this.sftpUserName = userName;
  this.sftpPassword = password;
  this.sftpPort = port;
  
  JSch jsch = new JSch();
  
  try
  {
   
   session = jsch.getSession(this.sftpUserName, this.sftpServerIp, this.sftpPort);
   
   session.setPassword(this.sftpPassword);
   
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   
   session.setTimeout(30000);
   
   session.connect();
   
   //打开SFTP通道
   channel = (ChannelSftp)session.openChannel("sftp");
   channel.connect();
   
   msg = "Success";
  }
  catch (JSchException e)
  {
   msg = "登录失败,可能是用户名或密码错误!";
   session = null;
  }
  
  return msg;
 }
 
 /**
  * 列出文件
  */
 //public
 
 /**
 * 下载文件
 * @param directory 下载目录
 * @param downloadFile 下载的文件
 * @param saveFile 存在本地的路径
 * @param sftp
 */
 public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp)
 {
  try
  {
   sftp.cd(directory);
   File file=new File(saveFile);
   sftp.get(downloadFile, new FileOutputStream(file));
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }

 /**
  * 关闭连接
 */
 public String close ()
 {
  if (channel != null)
        {
            channel.disconnect();
        }
        if (session != null)
        {
            session.disconnect();
        }
  return "连接断开";
 }
 
}

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值