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

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还是很稳定的,适合在项目中使用。作为各机器之间文件操作,远程命令执行的工具类。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值