Java 使用Ssh网络协议 进行服务器上传和下载

本文介绍了一个使用SSH协议进行文件上传和下载的Java类实现。该类利用JSch库实现与远程服务器的连接,并提供了上传和下载文件的功能。文章详细展示了如何配置会话参数,如主机地址、端口、用户名和密码,以及如何使用ChannelSftp对象进行文件操作。

package rsbc.card.ftpUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.io.FilenameUtils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;

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


/**
 * 使用 ssh 实现文件上传下载<br>
 * @author admin
 *
 */
public class Ssh {
    public static final String host = "192.168.125.122";
    public static final int port = 22;
    public static final String username = "123";
    public static final String password = "123";
    //上传路径  文件级回执文件 上传
    public static final String pathnameput = "/app/mcb/sction/data/tablefile/";//上传服务器路径
    
    public static Session connect(String host, Integer port, String user, String password) throws JSchException{
        Session session = null;
        try {
            JSch jsch = new JSch();
            if(port != null){
                session = jsch.getSession(user, host, port.intValue());
            }else{
                session = jsch.getSession(user, host);
            }
            session.setPassword(password);
            //设置第一次登陆的时候提示,可选值:(ask | yes | no)
            session.setConfig("StrictHostKeyChecking", "no");
            //30秒连接超时
            session.connect(30000);
        } catch (JSchException e) {
            e.printStackTrace();
            System.out.println("获取连接发生错误");
            throw e;
        }
        return session;
    }
    
    public static void download(String directory,String srcFile, String saveFile, ChannelSftp sftp) throws  UnsupportedEncodingException {
        Vector conts = null;
        try{
            conts = sftp.ls(srcFile);
        } catch (SftpException e) {
            e.printStackTrace();
//            log.debug("ChannelSftp sftp罗列文件发生错误",e);
        }
        File file = new File(saveFile);
        if(!file.exists()) file.mkdir();
        //文件
        if(srcFile.indexOf(".") > -1){
            try {
                sftp.get(srcFile, saveFile);
            } catch (SftpException e) {
                e.printStackTrace();
//                log.debug("ChannelSftp sftp下载文件发生错误",e);
            }
        }else{
        //文件夹(路径)
            for (Iterator iterator = conts.iterator(); iterator.hasNext();) {
                LsEntry obj =  (LsEntry) iterator.next();
                String filename = new String(obj.getFilename().getBytes(),"UTF-8");
                if(!(filename.indexOf(".") > -1)){
                    directory = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
                    srcFile = directory;
                    saveFile = FilenameUtils.normalize(saveFile + System.getProperty("file.separator") + filename);
                }else{
                    //扫描到文件名为".."这样的直接跳过
                    String[] arrs = filename.split("\\.");
                    if((arrs.length > 0) && (arrs[0].length() > 0)){
                        srcFile = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
                    }else{
                        continue;
                    }
                }
                download(directory, srcFile, saveFile, sftp);
            }
        }
    }
    //下载方法
    //remoteDir 路径名称  remoteDirtxt路径名称加上文件名称 localFile 保存路径
      public static void downloadtxt(String remoteDir,String remoteDirtxt,String localFile){
            ChannelSftp sftp = null;
            Session session = null;
          try {
                session = Ssh.connect(host, port, username, password);
                Channel channel = session.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
//                System.out.println("上传附件+++++:" + wa.getAttachName());
                download(remoteDir,remoteDirtxt,localFile,sftp);
            }catch(Exception e) {
                e.printStackTrace();
            }finally {
                if(sftp != null)sftp.disconnect();
                if(session != null)session.disconnect();
            }
         
      }
      
      /**
         * 上传文件
         * 
         * @param localPath
         *            本地路径,若为空,表示当前路径
         * @param localFile
         *            本地文件名,若为空或是“*”,表示目前下全部文件
         * @param remotePath
         *            远程路径,若为空,表示当前路径,若服务器上无此目录,则会自动创建
         * @throws Exception
         */
        public static void putFile(String localPath, String localFile, String remotePath,Channel channel)
                throws Exception {
            Channel channelSftp =channel;
            channelSftp.connect();
            ChannelSftp c = (ChannelSftp) channelSftp;
            String remoteFile = null;
            if (remotePath != null && remotePath.trim().length() > 0) {
                try {
                    c.mkdir(remotePath);
                } catch (Exception e) {
                }
                remoteFile = remotePath + "/.";
            } else {
                remoteFile = ".";
            }
            String file = null;
            if (localFile == null || localFile.trim().length() == 0) {
                file = "*";
            } else {
                file = localFile;
            }
            if (localPath != null && localPath.trim().length() > 0) {
                if (localPath.endsWith("/")) {
                    file = localPath + file;
                } else {
                    file = localPath + "/" + file;
                }
            }
            c.put(file, remoteFile);
     
            channelSftp.disconnect();
        }
        
        //上传
        //String localPath,本地路径
        //String uploadFile,文件名
        //String remotePath  服务器路径
        public static String uploadtxt(String localPath,String uploadFile){
            ChannelSftp sftp = null;
            Session session = null;
            String path=pathnameput;
          try {
                session = Ssh.connect(host, port, username, password);
                Channel channel = session.openChannel("sftp");
                putFile(localPath,uploadFile,pathnameput,channel);
            }catch(Exception e) {
                e.printStackTrace();
            }finally {
                if(sftp != null)sftp.disconnect();
                if(session != null)session.disconnect();
            }
          return path;
         
      }
    
    

   
}
真实有效  老大帮我写的  而且也实现了

如果不行  可能jar不一样  

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

我的用是这个  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值