Linux下用Sftp下载案例 -java

来源:互联网 发布:可以看禁播的软件 编辑:程序博客网 时间:2024/06/18 09:23
package com.kkyc.sass.common.utils;


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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


public class FtpUtils {
private static Logger logger = LoggerFactory.getLogger(FtpUtils.class);
private String host;
private int port;
private String username;
private String password;

/**
* @param host ip
* @param port 端口
* @param username 账号
* @param password 密码
* @return
* */
public FtpUtils(String host, int port, String username, String password) {
set(host, port, username, password);
}

public void set(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}

Session sshSession = null ;

/**
* 链接linux
* */
public ChannelSftp connect() {
ChannelSftp sftp = null ;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
logger.info(String.format("%s connect success" , host));
Channel channel = sshSession.openChannel("sftp");
channel.connect() ;
sftp = (ChannelSftp) channel;
} catch (Exception e) {
logger.error("connect:" + host , e );
close( null );
return null ;
}
return sftp;
}

/**
* linux远程下载
* @param file 待下载文件 /home/kksass/upload/***.zip
* @param backupDir 保存的目录 /data/kksass/backup
*/
public void get(File file, String backupDir) {
ChannelSftp sftp = connect() ;
try {
if(null != sftp){
// File file = new File( directory ) ;
// String parent = getParent( file ,2);
sftp.cd( "upload" );
/* File desc = new File(downloadFile);
FileOutputStream outputStream = new FileOutputStream(desc);
sftp.get(file.getName() , outputStream); */
// logger.info(file.getPath()+"---------"+downloadFile);
sftp.get(file.getName(), backupDir);
logger.info(String.format("down %s suc" , file.getPath()));
//outputStream.close() ;
}
} catch (Exception e) {
logger.error("down error :" + file.getPath() , e );
}finally{
close(sftp);
}
}

protected void close(ChannelSftp sftp){
if(sftp!=null){
sftp.disconnect() ;
sftp.exit();
}
if(sshSession!=null){
sshSession.disconnect();
}
}

/**
*
* @param desc
* @param systemType 1.Windows 2.Linux
* @return
*/
protected String getParent(File desc, Integer systemType){
if(systemType == 1){
String parent = desc.getParent();
return parent.replace("\\", "/");
}
return desc.getParent() ;
}

// 待调用方法
public static void ftpBackup(File file,String backupDir) {

/**
* @param host ip
* @param port 端口
* @param username 账号
* @param password 密码
* */
FtpUtils sftpUtils = new FtpUtils("120.23.69.217" , 22 , "user" , "password") ;

sftpUtils.get(file , backupDir);
}
}

原创粉丝点击