【发布时间】:2011-05-10 19:34:07
【问题描述】:
我不知道如何通过 JSch shell 通道发送命令。
我这样做了,但它不起作用:
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();
然后我读到这样的输入:
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);
【问题讨论】:
-
错误信息是什么?有堆栈跟踪吗?
-
没有错误信息,我只是没有收到任何信息。程序停在line = fromServer.readLine(),巫婆的意思是消息还没有发送……至少,我是这么认为的……
-
希望对您有帮助:jcraft.com/jsch/examples
-
:) 我正在按照这些示例工作... Thnx anw :)
-
jcraft.com/jsch/examples/Shell.java 的示例真的很好用。它只是设置 System.in 和 System.out,它们在管道流和控制台之间找到它们的方式。但是当我通过 ssh 连接到远程主机时,BufferedReader.readLine() 永远不会返回。解决方法是读取大块字节而不是字符串,然后手动从它们构造字符串。