需要的jar包:

  去maven仓库自己搜索com.jcraft下载jar包

<dependency>  
  <groupId>com.jcraft</groupId>  
  <artifactId>jsch</artifactId>  
  <version>0.1.49</version>  
</dependency>  

 

 上传:

  ftp方式:

package com.sunsheen.jfids.studio.monitor.sender;

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

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sunsheen.jfids.studio.monitor.common.LogInfo;
/**
 * 上传到远程服务器
 * @author WangSong
 *
 */
public class SendLogByFtp {
    
    /**
     * 文件上传
     * @param username    服务器用户名
     * @param password    服务器密码
     * @param address    服务器ip
     * @param port        连接服务器的端口号(默认22)
     * @param file        上传的文件
     */
    public static void postFile(String username,String password,String address,int port,File file){
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            //创建连接
            JSch jsch = new JSch();
            sshSession = jsch.getSession(username, address, port);
            sshSession.setPassword(password);
            //获取session
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            //得到sftp
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            //进入存放日志文件的目录
            sftp.cd(LogInfo.SERVERS_RECIVE_FOLDER);
            //上传
            sftp.put(new FileInputStream(file), LogInfo.LOGS_ZIP_FILE_NAME);
            System.out.println("上传成功!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭sftp信道
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            //关闭channel管道
            if (channel != null) {
                if (channel.isConnected()) {
                    channel.disconnect();
                }
            }
            //关闭session
            if (sshSession != null) {
                if (sshSession.isConnected()) {
                    sshSession.disconnect();
                }
            }
        }        
    }
    
}
点击查看源码

相关文章: