通过JSch shell通道向服务器发送命令

问题描述:

我无法弄清楚如何通过JSch shell频道发送命令。

I can't figure it out how I can send commands via JSch shell channel.

我这样做,但它不起作用:

I do this, but it doesn't work:

JSch shell = new JSch();
String command = "cd home/s/src";  
Session session = shell.getSession(username, host, port);  
MyUserInfo ui = new MyUserInfo();  
ui.setPassword(password);  
session.setUserInfo(ui);  
session.connect();  

channel = session.openChannel("shell");  
fromServer = new BufferedReader(new InputStreamReader(channel.getInputStream()));  
toServer = channel.getOutputStream();
channel.connect();  
toServer.write((command + "\r\n").getBytes());
toServer.flush();

然后我读取这样的输入:

and then I read input like this:

StringBuilder builder = new StringBuilder();  

int count = 0;  
String line = "";  

while(line != null) {  
    line = fromServer.readLine();
    builder.append(line).append("\n");

    if (line.endsWith(".") || line.endsWith(">")){
        break;
    }
}  
String result = builder.toString();  
ConsoleOut.println(result);


如果它挂在 readLine ()这意味着您的while永远不会结束(可能不太可能考虑您的代码),或者 readLine()正在等待它source,即 IOstream 阻止线程导致 available()!= true

If it hangs at readLine() that means either your "while" is never ending (might be unlikely considering your code), or, readLine() is waiting for its source, namely the IOstream blocks the thread cause available()!=true.

如果没有看到您的调试信息,我无法完全解决您的代码问题。但作为建议,你试过 PipedIntputStream ?我们的想法是将您的控制台输入传递给您的输出,以便您可以写它。要实现这一点,您需要初始化输入/输出。

I can't quite troubleshoot your code without seeing your debug info. But as an advice, have you tried PipedIntputStream? The idea is to pipe your console input to "your" output so that you can "write" it. To implement this, you need to initialize the in/out-put.

InputStream in = new PipedInputStream();
PipedOutputStream pin = new PipedOutputStream((PipedInputStream) in);
/**...*/
channel.setInputStream(in);
channel.connect();
/** ...*/
pin.write(myScript.getBytes());

同样适用于您的问题,如何阅读控制台输出。

The same goes to your question, how to read console output.

PipedInputStream pout = new PipedInputStream((PipedOutputStream) out);
/**
* ...
*/
BufferedReader consoleOutput = new BufferedReader(new InputStreamReader(pout));
consoleOutput.readLine();

再次,如果您不确定要阅读多少行,从而想要使用while ,确保你在内部做一些事情,以防止1)忙碌等待2)结束条件。示例:

And again, if you are not sure how many lines to read and thus want to use "while", make sure you do something inside while to prevent 1) busy-waiting 2) ending-condition. Example:

while(!end)
{
   consoleOutput.mark(32);
   if (consoleOutput.read()==0x03) end = true;//End of Text
   else
   { 
     consoleOutput.reset();
     consoleOutput.readLine();
     end = false;
   }
}