Jsch - 一次会话多个通道

5
我能够通过Jsch使用ssh执行单个命令,但是当我尝试执行第二个命令时,它失败了。为了调试,我将问题简化到以下几行代码:
import java.io.IOException;
import java.io.InputStream;

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

public class Exec {

    public static void test(Session session) throws Exception {
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand("pwd");

        channel.setInputStream(null);

        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
    }

    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();         
            Session session = jsch.getSession("nck", "127.0.0.1", 22);          
            session.setPassword("asd");         
            session.setConfig("StrictHostKeyChecking", "no");           
            session.connect();

            test(session); // This one succeeds with exit-status: 0         
            test(session); // This one fails with exit-status: 255

            session.disconnect();
        } catch (Exception e) {
            //
        }
    }
}

这主要是官方的Exec示例,但是它给我输出了这个结果:

/home/nck
exit-status: 0
exit-status: 255

第一条命令成功执行,第二条没有。
有任何想法吗?

1
它对我有效。(使用基于0.1.45-rc5的自定义构建 - 可能是您遇到了最近修复的错误。) - Paŭlo Ebermann
6个回答

8

这是一个完整的Java类,基于@krishna的答案:

/**
 * Run several ssh commands in a single JSch session
 */
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;

class SshMultiCommands
{
   public static void main(String[] args) throws Exception
   {
      JSch jsch = new JSch();
      String user = "user";            //CHANGE ME
      String host = "192.168.222.157"; //CHANGE ME
      String passwd = "password";      //CHANGE ME
      int port = 22;    
      Session session = jsch.getSession(user, host, port);
      session.setPassword(passwd);

      session.setConfig("StrictHostKeyChecking", "no");

      session.connect();

      Channel channel = session.openChannel("shell");
      OutputStream ops = channel.getOutputStream();
      PrintStream ps = new PrintStream(ops, true);

      channel.connect();
      InputStream input = channel.getInputStream();

      //commands
      ps.println("ls -lag");
      ps.println("cd /etc");
      ps.println("ls");
      ps.println("exit");
      ps.close();

      printResult(input, channel);

      channel.disconnect();
      session.disconnect();
   }

   /**
    * @param input
    * @param channel
    */
   private static void printResult(InputStream input,
                                   Channel channel) throws Exception
   {
      int SIZE = 1024;
      byte[] tmp = new byte[SIZE];
      while (true)
      {
         while (input.available() > 0)
         {
            int i = input.read(tmp, 0, SIZE);
            if(i < 0)
               break;
             System.out.print(new String(tmp, 0, i));
         }
         if(channel.isClosed())
         {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
         }
         try
         {
            Thread.sleep(300);
         }
         catch (Exception ee)
         {
         }
      }
   }
}

我尝试了所有的解决方案,这是最好的解决方案。 - svarog

4

嘿,我在使用jsch和Ubuntu时遇到了完全相同的问题。你是如何解决这个问题的?每次执行都创建一个新会话会花费太多时间吗?目前,我捕获jsch异常并搜索“会话未关闭”,然后重新连接会话并再次执行命令。这种方法可以工作,但不是一个好的解决方案。

编辑:我走错了路,我现在通过使用

channel = session.openChannel("shell");

而不是“exec”来解决我的问题。


3

您可以使用Shell执行多个命令。以下是通过Shell执行命令的代码:

Channel channel=session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

channel.connect();
ps.println("mkdir folder"); 
ps.println("dir");
//give commands to be executed inside println.and can have any no of commands sent.
ps.close();

InputStream in=channel.getInputStream();
byte[] bt=new byte[1024];

while(true) {
    while(in.available()>0) {
        int i=in.read(bt, 0, 1024);
        if(i<0)
            break;
        String str=new String(bt, 0, i);

        //displays the output of the command executed.
        System.out.print(str);
    }
    if(channel.isClosed()) 
        break;

    Thread.sleep(1000);
    channel.disconnect();
    session.disconnect();   
}

2
如果您想使用exec,可以在命令之间加上分号(;)来运行多个命令。
例如:
pwd;ls- -l; 
cd foldername

((ChannelExec) channel).setCommand("pwd;ls -l; cd foldername");

1

我曾经使用完全相同的代码,但有时通过ssh执行脚本时会遇到问题。有时程序会丢失所有内容,有时只会丢失部分内容。 我通过更改嵌套循环中的if(channel.isclosed)解决了我的问题。 以下是新代码:

while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            System.out.print(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
             if(in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                System.out.print(new String(tmp, 0, i));
             } 
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
}

0

这不是jsch的bug,而是我的ssh服务器的bug(cygwin - 我打赌我配置错了什么...)

编辑:嗯,我在Ubuntu上使用jsch也遇到了同样的问题...奇怪

猜测作为解决方法,我将不得不为每个查询打开一个新会话。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接