JSCH工具使用

333 阅读2分钟

引入maven包

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Channel的用法

  1. ChannelExec示例
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class JschTest2 {

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

    public static void main(String[] args) {

        String username = "root";
        String password = "123456";
        String host = "192.168.190.133";
        int port = 22;

        // 创建JSch对象
        JSch jSch = new JSch();
        Session jSchSession = null;
        Channel jschChannel = null;

        // 存放执行命令结果
        StringBuffer result = new StringBuffer();
        int exitStatus = 0;
        String command = "ls -l";

        try {
            // 根据主机账号、ip、端口获取一个Session对象
            jSchSession = jSch.getSession(username, host, port);

            // 存放主机密码
            jSchSession.setPassword(password);

            // 去掉首次连接确认
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            jSchSession.setConfig(config);

            // 超时连接时间为3秒
            jSchSession.setTimeout(3000);

            // 进行连接
            jSchSession.connect();

            jschChannel = jSchSession.openChannel("exec");
            ((ChannelExec) jschChannel).setCommand(command);

            jschChannel.setInputStream(null);
            // 错误信息输出流,用于输出错误的信息,当exitstatus<0的时候
            ((ChannelExec) jschChannel).setErrStream(System.err);

            // 执行命令,等待执行结果
            jschChannel.connect();

            // 获取命令执行结果
            InputStream in = jschChannel.getInputStream();
            /**
             * 通过channel获取信息的方式,采用官方Demo代码
             */
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    result.append(new String(tmp, 0, i));
                }
                // 从channel获取全部信息之后,channel会自动关闭
                if (jschChannel.isClosed()) {
                    if (in.available() > 0) {
                        continue;
                    }
                    exitStatus = jschChannel.getExitStatus();
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

        } catch (Exception e) {
            logger.warn(e.getMessage());
        } finally {
            // 关闭sftpChannel
            if (jschChannel != null && jschChannel.isConnected()) {
                jschChannel.disconnect();
            }

            // 关闭jschSesson流
            if (jSchSession != null && jSchSession.isConnected()) {
                jSchSession.disconnect();
            }

        }
        logger.info("获取执行命令的结果结果:" + result);
        logger.info("退出码为:" + exitStatus);

    }
}

运行结果:

image.png

  1. ChannelShell示例
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.util.Properties;

public class JschTest {
    public static void main(String[] arg) {

        String username = "root";
        String password = "123456";
        String host = "192.168.190.133";
        int port = 22;

        // 创建JSch对象
        JSch jSch = new JSch();
        Session jSchSession = null;
        Channel jschChannel = null;

        try {
            // 根据主机账号、ip、端口获取一个Session对象
            jSchSession = jSch.getSession(username, host, port);

            // 存放主机密码
            jSchSession.setPassword(password);

            // 去掉首次连接确认
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            jSchSession.setConfig(config);

            // 超时连接时间为3秒
            jSchSession.setTimeout(3000);

            // 进行连接
            jSchSession.connect();

            jschChannel = jSchSession.openChannel("shell");

            jschChannel.setInputStream(System.in);
            jschChannel.setOutputStream(System.out);

            jschChannel.connect();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}

运行结果:

image.png

源码参考见下面仓库中测试用例

引用

  1. jsch入门
  2. 源码地址