jsch工具类,实现连接服务器执行命令

代码来源维护的项目里


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

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

public class SshUtil {
    
    private static final Logger logger = Logger.getLogger(SshUtil.class);

    private Session session = null;
    private ChannelExec channelExec = null;
    ByteArrayOutputStream err = null;
    StringBuffer outbuf = null;

    public ByteArrayOutputStream getErr() {
        return err;
    }

    public StringBuffer getOutbuf() {
        return outbuf;
    }

    public Session getSession() {
        return session;
    }

    public ChannelExec getChannelExec() {
        return channelExec;
    }

    /**
     * 使用用户名、密码连接
     *
     * @param host     主机ip
     * @param port     主机端口
     * @param username 主机用户名
     * @param password 主机密码
     * @throws JSchException
     */
    public void Connect(String host, int port, String username, String password) throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        int timeout = 30000;
        session.setTimeout(timeout);
        session.connect();

        logger.info("Connected to " + host + ".");
    }

    /**
     * 使用授信连接
     *
     * @param host       主机ip
     * @param username   主机用户名
     * @param privateKey 私钥路径
     * @throws JSchException
     */
    public void Connect(String host, String username, String privateKey) throws JSchException {
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey);
        session = jsch.getSession(username, host);

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        int timeout = 30000;
        session.setTimeout(timeout);
        session.connect();

        logger.info("Connected to " + host + ".");
    }

    /**
     * 执行
     *
     * @param cmd 命令
     * @return 状态
     * @throws JSchException
     * @throws IOException
     */
    public int excute(String cmd) throws JSchException, IOException {
        int exitStatus = 0;

        channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setInputStream(null);
        err = new ByteArrayOutputStream();
        channelExec.setErrStream(err);

        channelExec.setCommand(cmd);

        InputStream in = channelExec.getInputStream();
        channelExec.connect();

        outbuf = new StringBuffer();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                outbuf.append(new String(tmp, 0, i));
            }
            if (channelExec.isClosed()) {
                if (in.available() > 0) continue;
                exitStatus = channelExec.getExitStatus();
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }

        channelExec.disconnect();

        return exitStatus;
    }

    /**
     * 执行
     *
     * @param cmd 命令
     * @return 状态
     * @throws JSchException
     * @throws IOException
     */
    public String excuteReturnString(String cmd) throws JSchException, IOException {
        int exitStatus = 0;

        channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setInputStream(null);
        err = new ByteArrayOutputStream();
        channelExec.setErrStream(err);

        channelExec.setCommand(cmd);

        InputStream in = channelExec.getInputStream();
        channelExec.connect();

        outbuf = new StringBuffer();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                outbuf.append(new String(tmp, 0, i));
            }
            if (channelExec.isClosed()) {
                if (in.available() > 0) continue;
                exitStatus = channelExec.getExitStatus();
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }

        channelExec.disconnect();

        if (exitStatus == 0) {
            String outinfo = this.getOutbuf().toString();
            return outinfo;
        } else {
            String errinfo = this.getErr().toString();
            return errinfo;
        }
    }

    /**
     * 断开连接
     */
    public void DisConnect() {
        if (channelExec != null) {
            channelExec.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }

        logger.info("Disconnected from " + session.getHost() + ".");
    }

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值