【发布时间】:2014-06-15 02:04:23
【问题描述】:
我有这样一个场景:
我需要连接到远程服务器(linux)并执行 du -h 命令来查找特定文件夹(例如 /home/oracle/TEST)的磁盘使用情况。所以,我需要找到 TEST 文件夹的磁盘使用情况。并在java中打印结果。我该怎么做?
public static void main(String[] args) {
String s = null;
try {
// run the Unix "ps -ef" command
Socket s1=new Socket("10.1.7.237",1521);
System.out.println(s1.isConnected());
System.out.println(s1.getRemoteSocketAddress());
System.out.println("connected");
System.out.println();
PrintWriter wr=new PrintWriter(new OutputStreamWriter(s1.getOutputStream()),true);
wr.println("Hi Server...");
wr.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(s1.getInputStream()));
System.out.println(br.readLine());
Process p = Runtime.getRuntime().exec("du -h");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.out.println(e.getMessage());
System.exit(-1);
}
}
我也试过了,但遇到了这个异常:
Cannot run program "du": CreateProcess error=2, The system cannot find the file specified
java.io.IOException: Cannot run program "du": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at testprog.main(testprog.java:27)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 5 more
【问题讨论】:
-
我检测到错误:如果我用任务列表替换 du -h 命令,程序运行正常。问题是 Rumtime.getRuntime.exec() 在当前运行时执行命令(因为我我在 windows 中做),但我想在 linux 服务器而不是 windows 中运行命令。
-
这不会给你你正在寻找的结果。你想在远程机器上执行你的命令。使用
tasklist会给你你的windows box的结果,而不是你的远程linux机器。
标签: java linux runtime.exec