FTP连接服务器Server Reply: SSH-2.0-OpenSSH_6.6.1异常

问题:在使用ftp上传文件时,出现了以下错误

org.apache.commons.net.MalformedServerReplyException: Could not parse response code.
Server Reply: SSH-2.0-OpenSSH_6.6.1

原因是FTPClient不支持通过协议SSH2进行SFTP连接,只能更换方法实现,可以使用com.jcraft.jsch.JSch提供的SSH解决问题。

需要的maven依赖:


    com.jcraft
    jsch
    0.1.54    

 Jsch的ChannelSftp更像是一个linuxl命令的包装,我们可以通过它的封装获取发送指定的命令:

连接:

public class SftpUtil {

    private static final Logger logger = LoggerFactory.getLogger(SftpUtil.class);

    private static ChannelSftp  channelSftp = null;

    private static Session sshSession = null;

    /**
     * 连接服务器
     */
    public static boolean getConnect(String host, String port, String userName, String password){

        try {
            JSch jsch = new JSch();
            // 获取sshSession
            sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
            // 添加s密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // 开启sshSession链接
            sshSession.connect();
            // 获取sftp通道
            channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
            // 开启
            channelSftp.connect();
            logger.info("使用sftp连接ftp成功");
        } catch (Exception e) {
           logger.error("连接ftp失败", e);
           return false;
        }
       return true;
    }
}

关闭,关闭时需要同时关闭 通道和session

 /**
     * 关闭
     */
public static void close(){
        logger.info("关闭sftp信息");
        try {
            if(channelSftp != null){
                channelSftp.disconnect();
            }
            if(sshSession != null) {
                sshSession.disconnect();
            }
        } catch (Exception e) {
            logger.error("关闭sftp连接失败", e);
        }
}

远程创建文件夹:

/**
     * 测似乎工作目录是否存在
     * @param remotePath ftp的工作目录
     */
    public boolean changeWorkingDirectory(String remotePath ) {
        logger.info("ftp上传地址:{}", remotePath);
        if(channelSftp == null || sshSession == null){
            logger.error("请先初始化ftp连接信息");
            return false;
        }
        boolean flag = false;
        boolean needCreateDir = false;
        try{
            channelSftp.cd(remotePath);
        } catch (SftpException e){
            needCreateDir = true;
            logger.error("sftp的cd命令失败,需要创建目录");
        }
        if(needCreateDir) {
            int start = 0;
            if (workingPath.startsWith("/")) {
                start = 1;
            }
            boolean isEnd = true;
            //使用递归的方式新建
            while(isEnd) {
                int index = remotePath.indexOf(sep, start);
                if(index >= 0){
                    String subStartWorkingPath = remotePath.substring(0, index);
                    try {
                        channelSftp.mkdir(subStartWorkingPath);
                        channelSftp.cd(subStartWorkingPath);
                    }catch (Exception e){
                        logger.error("sftp新建目录失败:{}", subStartWorkingPath);
                        isEnd = false;
                    }
                } else {
                    logger.info("级联新建目录[{}]结束", remotePath);
                    flag = true;
                    isEnd = false;
                }
                start = index + 1;
            }
        } else {
            flag = true;
        }
        return flag;
    }

上传文件:

/**
     * 上传
     * @param file 上传文件路径
     * @param ftp_path	服务器保存路径
     * @param newFilename 文件名
     */
    public boolean uploadFile(String file, String newFilename, String ftp_path) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(file));
            channelSftp.cd(ftp_path);
            channelSftp.put(fis, newFilename);
        } catch (Exception e) {
            logger.error("上传ftp文件失败", e);
            return false;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("文件流关闭失败", e);
                }
            }
        }
        return true;
    }

下载文件:

 /**
     * 下载文件
     * @param ftpPath	服务器文件路径
     * @param localPath	下载保存路径
     * @param oldFileName	服务器上文件名
     * @param newFileName	保存后新文件名
     */
public  static boolean download(String ftpPath, String localPath, String oldFileName, String newFileName) {
        FileOutputStream fos = null;
        try {
            channelSftp.cd(ftpPath);
            File file = new File(localPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String saveFile = localPath + newFileName;
            File file1 = new File(saveFile);
            fos = new FileOutputStream(file1);
            channelSftp.get(oldFileName, fos);
        } catch (Exception e) {
            logger.error("下载文件异常", e);
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    logger.error("文件流关闭失败", e);
                }
            }
        }
        return true;
    }

你可能感兴趣的:(apache,服务器,ssh)