java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行

来源:互联网 发布:mysql select 多个表 编辑:程序博客网 时间:2024/05/06 19:05

SFTPConstants.java,定义我们需要使用的一些参数名称:

public class SFTPConstants {    public static final String SFTP_REQ_HOST = "host";    public static final String SFTP_REQ_PORT = "port";    public static final String SFTP_REQ_USERNAME = "username";    public static final String SFTP_REQ_PASSWORD = "password";    public static final int SFTP_DEFAULT_PORT = 22;    public static final String SFTP_REQ_LOC = "location";}

SFTPChannel.java我们通过它来获得channel对象:

import java.util.Map;import java.util.Properties;import org.apache.log4j.Logger;import com.jcraft.jsch.Channel;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;public class SFTPChannel {    Session session = null;        Channel channel = null;    private static final Logger LOG = Logger.getLogger(SFTPChannel.class);    public Channel getChannel(String name, Map<String, String> sftpDetails, int timeout) throws JSchException {        String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);        String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);        String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);        String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);        int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;        if (port != null && !port.equals("")) {            ftpPort = Integer.valueOf(port);        }        JSch jsch = new JSch(); // 创建JSch对象        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象        LOG.info("Session created.");        if (ftpPassword != null) {            session.setPassword(ftpPassword); // 设置密码        }        Properties config = new Properties();        config.put("StrictHostKeyChecking", "no");        session.setConfig(config); // 为Session对象设置properties        session.setTimeout(timeout); // 设置timeout时间        session.connect(); // 通过Session建立链接        LOG.info("Session connected.");        LOG.info("Opening Channel.");        channel = session.openChannel(name); // 打开SFTP通道        LOG.info("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName                + ", returning: " + channel);        return channel;    }            public void connect() throws JSchException    {    channel.connect();    }    public void closeChannel() throws Exception {        if (channel != null) {            channel.disconnect();        }        if (session != null) {            session.disconnect();        }    }
新建一个类来监控文件操作的进度:

import com.jcraft.jsch.SftpProgressMonitor;public class FileProgressMonitor implements SftpProgressMonitor {    private long transfered;        public FileProgressMonitor()    {    }        @Override    public boolean count(long count) {        transfered = transfered + count;        System.out.println("Currently transferred total size: " + transfered + " bytes");        return true;    }    @Override    public void end() {    System.out.println("Transferring done.");    }    @Override    public void init(int op, String src, String dest, long max) {    System.out.println("Transferring begin.");    }}


下面,我们来看看文件操作:

Map<String, String> sftpDetails = new HashMap<String, String>();sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "192.168.1.17");sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "123456");sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");String src = "/home/test.txt"; //目标文件名String dst = "test/test.txt"; //本地文件名SFTPChannel channel = new SFTPChannel();ChannelSftp chSftp = null;try {chSftp = (ChannelSftp)channel.getChannel("sftp", sftpDetails, 60000);channel.connect();chSftp.get(src, dst, new FileProgressMonitor(), ChannelSftp.OVERWRITE);} catch (JSchException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {chSftp.quit();channel.closeChannel();}

执行远程命令:

String charset = "UTF-8";String cmd = "ls";Map<String, String> sftpDetails = new HashMap<String, String>();sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "192.168.1.17");sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "123456");sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");SFTPChannel channel = new SFTPChannel();ChannelExec execChannel = null;execChannel = (ChannelExec)channel.getChannel("exec", sftpDetails, 60000);execChannel.setCommand(cmd);execChannel.setInputStream(null);execChannel.setErrStream(System.err);execChannel.connect();InputStream in = execChannel.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));String buf = null;while ((buf = reader.readLine()) != null){//System.out.println(buf);}reader.close();try {channel.closeChannel();} catch (Exception e) {e.printStackTrace();}
经过测试,JSCH还是很稳定的,适合在项目中使用。作为各机器之间文件操作,远程命令执行的工具类。

原创粉丝点击