首页后端开发其他后端知识JSch远程执行shell命令的方法有什么,这两种你知吗?

JSch远程执行shell命令的方法有什么,这两种你知吗?

时间2024-03-28 22:24:03发布访客分类其他后端知识浏览1003
导读:这篇文章我们来了解JSch远程执行shell命令的方法,JSch虽然是很老的框架,更新到2016年,现在也不更新了,但是学习Java过程中,了解一下JSch框架的使用还是有一定的学习价值的。对于JSch 使用 shell 执行命令,有两种方...

这篇文章我们来了解JSch远程执行shell命令的方法,JSch虽然是很老的框架,更新到2016年,现在也不更新了,但是学习Java过程中,了解一下JSch框架的使用还是有一定的学习价值的。对于JSch 使用 shell 执行命令,有两种方法,接下来我们详细的了解看看。

JSch 是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。

JSch 使用 shell 执行命令,有两种方法

  • ChannelExec: 一次执行一条命令,一般我们用这个就够了。

  • ChannelShell: 可执行多条命令,平时开发用的不多,根据需要来吧;

ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
    //只能执行一条指令(也可执行符合指令)
ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
    //可执行多条指令 不过需要输入输出流

1. ChannelExec

  • 每个命令之间用 ; 隔开。说明:各命令的执行给果,不会影响其它命令的执行。换句话说,各个命令都会执行,但不保证每个命令都执行成功。

  • 每个命令之间用 & & 隔开。说明:若前面的命令执行成功,才会去执行后面的命令。这样可以保证所有的命令执行完毕后,执行过程都是成功的。

  • 每个命令之间用 || 隔开。说明:|| 是或的意思,只有前面的命令执行失败后才去执行下一条命令,直到执行成功一条命令为止。

2. ChannelShell

对于ChannelShell,以输入流的形式,可执行多条指令,这就像在本地计算机上使用交互式shell(它通常用于:交互式使用)。如要要想停止,有两种方式:

  • 发送一个exit命令,告诉程序本次交互结束;

  • 使用字节流中的available方法,来获取数据的总大小,然后循环去读。

使用示例

1. 引入 pom 依赖

dependency>
    
   groupId>
    com.jcraft/groupId>
    
   artifactId>
    jsch/artifactId>
    
   version>
    0.1.53/version>
    
/dependency>
    

2. jsch 使用示例

在此封装了一个 Shell 工具类,用来执行 shell 命令,具体使用细节在代码注释中有说明,可以直接拷贝并使用,代码如下:

package org.example.shell;
    /**
 * Created by qianghaohao on 2021/3/28
 */import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
/**
 * @description:
 * @author: qianghaohao
 * @time: 2021/3/28
 */public class Shell {
    
    private String host;
    
    private String username;
    
    private String password;
    
    private int port = 22;
    
    private int timeout = 60 * 60 * 1000;


    public Shell(String host, String username, String password, int port, int timeout) {
    
        this.host = host;
    
        this.username = username;
    
        this.password = password;
    
        this.port = port;
    
        this.timeout = timeout;

    }


    public Shell(String host, String username, String password) {
    
        this.host = host;
    
        this.username = username;
    
        this.password = password;

    }


    public String execCommand(String cmd) {
    
        JSch jSch = new JSch();
    
        Session session = null;
    
        ChannelExec channelExec = null;
    
        BufferedReader inputStreamReader = null;
    
        BufferedReader errInputStreamReader = null;
    
        StringBuilder runLog = new StringBuilder("");
    
        StringBuilder errLog = new StringBuilder("");

        try {
    
            // 1. 获取 ssh session
            session = jSch.getSession(username, host, port);
    
            session.setPassword(password);
    
            session.setTimeout(timeout);
    
            session.setConfig("StrictHostKeyChecking", "no");
    
            session.connect();
      // 获取到 ssh session

            // 2. 通过 exec 方式执行 shell 命令
            channelExec = (ChannelExec) session.openChannel("exec");
    
            channelExec.setCommand(cmd);
    
            channelExec.connect();
      // 执行命令

            // 3. 获取标准输入流
            inputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
    
            // 4. 获取标准错误输入流
            errInputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getErrStream()));
    

            // 5. 记录命令执行 log
            String line = null;

            while ((line = inputStreamReader.readLine()) != null) {
    
                runLog.append(line).append("\n");

            }
    

            // 6. 记录命令执行错误 log
            String errLine = null;

            while ((errLine = errInputStreamReader.readLine()) != null) {
    
                errLog.append(errLine).append("\n");

            }
    

            // 7. 输出 shell 命令执行日志
            System.out.println("exitStatus=" + channelExec.getExitStatus() + ", openChannel.isClosed="
                    + channelExec.isClosed());
    
            System.out.println("命令执行完成,执行日志如下:");
    
            System.out.println(runLog.toString());
    
            System.out.println("命令执行完成,执行错误日志如下:");
    
            System.out.println(errLog.toString());

        }
 catch (Exception e) {
    
            e.printStackTrace();

        }
 finally {

            try {

                if (inputStreamReader != null) {
    
                    inputStreamReader.close();

                }

                if (errInputStreamReader != null) {
    
                    errInputStreamReader.close();

                }


                if (channelExec != null) {
    
                    channelExec.disconnect();

                }

                if (session != null) {
    
                    session.disconnect();

                }

            }
 catch (IOException e) {
    
                e.printStackTrace();

            }

        }
    

        return runLog.toString();

    }
}
    

上述工具类使用:

package org.example;
    import org.example.shell.Shell;
/**
 * Hello world!
 *
 */public class App {

    public static void main( String[] args ) {
    
        String cmd = "ls -1";
    
        Shell shell = new Shell("192.168.10.10", "ubuntu", "11111");
    
        String execLog = shell.execCommand(cmd);
    
        System.out.println(execLog);

    }
}
    

以上就是JSch远程执行shell命令的方法介绍,上述两种方式及示例具有一定的参考价值,有需要的朋友可以了解看看,希望对大家认识和学习JSch框架有帮助,想要了解更多可以继续浏览网络其他相关的文章。

文本转载自PHP中文网

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: JSch远程执行shell命令的方法有什么,这两种你知吗?
本文地址: https://pptw.com/jishu/655237.html
Java中split方法有什么用,如何使用? jdbc怎么连接数据库?一文带你了解操作

游客 回复需填写必要信息