我有这样的场景:
我需要连接到远程服务器(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
答案 0 :(得分:1)
我认为你实际上并没有在远程服务器上执行du -h命令。 Runtime.getRuntime()获取本地主机上的Runtime实例。 您应该使用可以远程登录到远程主机并在那里执行命令的库,例如http://commons.apache.org/proper/commons-net/
你可以在这里看到:http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html 这个RunTime在主机上获得主机envairorment和exec“du -h”而不是在远程服务器上
答案 1 :(得分:0)
在Java中执行命令时,您不在经典shell中。因此,您无权访问相同的环境变量,内置命令等。
试试/usr/bin/du
答案 2 :(得分:0)
您无法直接使用Runtime.getRuntime().exec("du -h");
在远程计算机上执行某些操作。该命令在已启动java程序的机器上执行。
How do I run SSH commands on remote system using Java?回答了您的问题。
答案 3 :(得分:0)
尝试:
Runtime.getRuntime().exec("ssh ${hostname-goes-here} du -h /path/to/folder");
当然,您需要在客户端的路径上提供ssh
,并且为了使上述命令有效,您需要将公钥添加到{ {1}}档案。