java 使用jsch.jar包通过sftp访问Linux服务器

来源:互联网 发布:linux什么是管道 编辑:程序博客网 时间:2024/04/29 02:11

import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import org.apache.log4j.Logger;

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

/**
 * 使用jsch.jar包访问Linux服务器
 *
 * @author LX
 * @version 1.0 2015/5/7
 *
 */
public class SFTP {
    private Session session = null;
    private Channel channel = null;
    private ChannelSftp sftp = null;
    private Logger LOGGER = Logger.getLogger(SFTP.class);
    private String filePath = null;

    /**
     * 构造方法,初始化类时就加载参数
     *
     * @param serverip
     *            Linux服务器的ip
     * @param serverport
     *            Linux服务器的端口
     * @param serveruser
     *            Linux服务器的用户名
     * @param serverpw
     *            Linux服务器的密码
     * @param filepath
     *            Linux服务器上的路径
     */
    public SFTP(String serverip, int serverport, String serveruser,
            String serverpw, String filepath) {
        JSch jsch = new JSch();
        try {
            if (serverport <= 0) {// 连接服务器,采用默认端口
                session = jsch.getSession(serveruser, serverip);
            } else {// 采用指定的端口连接服务器
                session = jsch.getSession(serveruser, serverip, serverport);
            }
        } catch (JSchException e) {
            LOGGER.error(e);
        }

        // 如果服务器连接不上,则抛出异常
        if (session == null) {
            LOGGER.info("服务器连接不上,session创建失败");
        }

        // 设置登陆主机的密码
        session.setPassword(serverpw);// 设置密码
        // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        try {
            // 设置登陆超时时间
            session.connect(30000);
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            // 创建sftp通信通道
            sftp = (ChannelSftp) channel;
            // 进入服务器指定的文件夹
            filePath = filepath;
            sftp.cd(filePath);
        } catch (JSchException e) {
            LOGGER.error(e);
        } catch (SftpException e) {
            LOGGER.error(e);
        }

    }

    /**
     * 判断文件是否已经下载的方法
     *
     */
    public boolean filterPic(String fileName) {
        try {
            sftp.ls(fileName);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 下载文件到服务器上的方法
     *
     * @param requestByte
     *            需要保存的数据
     * @param fileName
     *            文件名
     * @throws SftpException
     * @throws IOException
     */
    public void savePic(byte[] requestByte, String fileName)
            throws SftpException, IOException {

        if (requestByte != null) {
            OutputStream outstream = sftp.put(filePath + "/" + fileName);
            outstream.write(requestByte);
            outstream.flush();
            outstream.close();
            LOGGER.info("下载完成:" + fileName);
        } else {
            LOGGER.info("下载失败:" + fileName + "。输入数据为空!");

        }
    }

    /**
     * 创建文件,并进入文件
     *
     * @param filepath
     *            文件路径
     */
    public synchronized void cdFile(String filepath) {
        try {
            sftp.cd(filepath);
        } catch (SftpException e) {
            LOGGER.error("文件不存在!" + filepath);
            try {
                sftp.mkdir(filepath);
                sftp.cd(filepath);
                LOGGER.info("创建文件成功!" + filepath);
            } catch (SftpException e1) {
                LOGGER.info("创建文件失败!" + filepath);
                LOGGER.error(e);
            }
        }
    }

    /**
     * 获取文件路径下的所有文件名
     *
     * @return
     */
    public Vector getFileList() {
        try {
            return sftp.ls(filePath);
        } catch (SftpException e) {
            LOGGER.error(e);
        }
        return null;
    }

    /**
     * 关闭SFTP连接
     */
    public void close() {
        if (session != null) {
            session.disconnect();
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (sftp != null) {
            sftp.disconnect();
        }
    }

    private static String help = "      Available commands:\n"
        + "      * means unimplemented command.\n"
        + "cd path                       Change remote directory to 'path'\n"
        + "lcd path                      Change local directory to 'path'\n"
        + "chgrp grp path                Change group of file 'path' to 'grp'\n"
        + "chmod mode path               Change permissions of file 'path' to 'mode'\n"
        + "chown own path                Change owner of file 'path' to 'own'\n"
        + "df [path]                     Display statistics for current directory or\n"
        + "                              filesystem containing 'path'\n"
        + "help                          Display this help text\n"
        + "get remote-path [local-path]  Download file\n"
        + "get-resume remote-path [local-path]  Resume to download file.\n"
        + "get-append remote-path [local-path]  Append remote file to local file\n"
        + "hardlink oldpath newpath      Hardlink remote file\n"
        + "*lls [ls-options [path]]      Display local directory listing\n"
        + "ln oldpath newpath            Symlink remote file\n"
        + "*lmkdir path                  Create local directory\n"
        + "lpwd                          Print local working directory\n"
        + "ls [path]                     Display remote directory listing\n"
        + "*lumask umask                 Set local umask to 'umask'\n"
        + "mkdir path                    Create remote directory\n"
        + "put local-path [remote-path]  Upload file\n"
        + "put-resume local-path [remote-path]  Resume to upload file\n"
        + "put-append local-path [remote-path]  Append local file to remote file.\n"
        + "pwd                           Display remote working directory\n"
        + "stat path                     Display info about path\n"
        + "exit                          Quit sftp\n"
        + "quit                          Quit sftp\n"
        + "rename oldpath newpath        Rename remote file\n"
        + "rmdir path                    Remove remote directory\n"
        + "rm path                       Delete remote file\n"
        + "symlink oldpath newpath       Symlink remote file\n"
        + "readlink path                 Check the target of a symbolic link\n"
        + "realpath path                 Canonicalize the path\n"
        + "rekey                         Key re-exchanging\n"
        + "compression level             Packet compression will be enabled\n"
        + "version                       Show SFTP version\n"
        + "?                             Synonym for help";

}

0 0
原创粉丝点击