使用 jsch session 和 channelexec 执行多个命令

我努力让它工作,但最终让脚本在远程 unix 服务器上执行命令(执行 sh 脚本)。我正在尝试执行第二个命令并在创建新频道或使用相同频道时不断收到错误消息。


       try {



            ((ChannelExec) channel).setCommand(command);

            PrintStream out= new PrintStream(channel.getOutputStream());

            InputStream in = channel.getInputStream();


            channel.connect();


            BufferedReader scriptReader= new BufferedReader(new InputStreamReader(in));

            scriptOutput = scriptReader.readLine();


            sb = new StringBuilder();


            while ((scriptOutput = scriptReader.readLine())!= null) {

                sb.append(scriptOutput + "\n");

这是频道执行的第一个片段,效果很好。现在,在使用上述输入流后立即调用下一个方法片段:


      try {


          StringBuilder sb = new StringBuilder();

          command = new_command;

          ((ChannelExec) channel).setCommand(command);


          InputStream in = channel.getInputStream();

          channel.connect();

          BufferedReader scriptReader= new BufferedReader(new InputStreamReader(in));

          scriptOutput = scriptReader.readLine();


            //StringBuilder sb = new StringBuilder();

          for(int c=0; c < consumerList.size(); c++){

           ....

现在返回以下错误:


com.jcraft.jsch.JSchException: channel is not opened.

现在,如果我使用相同的会话创建一个新频道,我会从返回的流中得到一个空响应。我确实在远程 shell 中测试了命令,它工作正常:


      int counter = 0;

      Channel channelII = session.openChannel("exec");


      try {


          StringBuilder sb = new StringBuilder();

          command = new_command;

          ((ChannelExec) channelII).setCommand(command);


          InputStream in = channelII.getInputStream();

          channelII.connect();

          BufferedReader scriptReader= new BufferedReader(

           new InputStreamReader(in));

          scriptOutput = scriptReader.readLine();

第二个命令如下,我希望能够为不同的消费者群体重复执行它:


/usr/kafka/bin/kafka-consumer-groups.sh --bootstrap-server 

    192.xxx.xx.xxx:9092 --describe -group consumergroup1



阿波罗的战车
浏览 2966回答 1
1回答

Qyouu

我弄清楚出了什么问题并想发布一个答案,因为我确实意识到这样的小事情确实会出现在我们那里的“愚蠢”程序员身上,他们提出荒谬的问题会招致反对票。第二个命令的输出在第一行返回警告/错误响应,并且不包含以下内容,我没有看到,阅读下一行是空的。我知道这很愚蠢,应该在发布之前弄清楚这一点,因为这就是本网站的重点:发布其他人不知道的问题。但既然我天生就应该知道这一点:无论如何确保包括以下行:&nbsp; ((ChannelExec)channelII).setErrStream(System.err);并且还使用循环读取流,而不仅仅是通过读取第一行进行测试。&nbsp; &nbsp; &nbsp;while ((scriptOutput = scriptReader.readLine())!= null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(scriptOutput + "\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }我希望这至少可以成为一些人的教训,如果不是解决方案的话。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java