【发布时间】:2018-02-04 10:23:05
【问题描述】:
我正在使用以下脚本来执行命令并获取输出: 运行时 rt = Runtime.getRuntime();
static Runtime rt;
static Process proc;
public static void main(String[] Args) throws IOException, InterruptedException {
rt = Runtime.getRuntime();
String[] commands = {"ssh.exe","-o BatchMode=yes", "root@192.168.1.1", "cat /var/a.txt"};
// String[] commands = {"ssh.exe", "root@192.168.0.1"};
// String[] commands = { "ls", "-la" };
proc = rt.exec(commands);
new Thread("out") {
public void run() {
System.out.println("Thread: " + getName() + " running");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String s = null;
// read the output from the command
System.out.println("StdOut:\n");
try {
while ((s = stdInput.readLine()) != null) {
System.out.println("$ " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
new Thread("err") {
public void run() {
System.out.println("Thread: " + getName() + " running");
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
// read any errors from the attempted command
System.out.println("StdErr:\n");
try {
while ((s = stdError.readLine()) != null) {
System.out.println("! " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
Thread.sleep(10000);
System.out.println("end");
}
如果我执行“ls -la”或“ssh”,我会得到预期的输出。但是,尝试从远程设备(第 1 行)获取 a.txt 内容失败并且操作挂起。 从命令行执行“ssh root@192.168.0.1 cat a.txt”可以工作并检索内容。
为什么会这样?如何修复? 谢谢
【问题讨论】:
标签: java ssh bufferedreader