読者です 読者をやめる 読者になる 読者になる

LEON-VALUE

生活碎語、投資生活

Javaからlinuxコマンドを呼び出す

Linux環境のコマンドを呼出し、標準出力結果を取得する方法

ソースをコーヒーしたら、フォーマットが変になってしまた。


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class LinuxCmdTest{
public static void main(String arg[]) {
LinuxCmdTest cmdTest = new LinuxCmdTest();
String str_cmd;
String str_arg;

// Linuxのシェルを呼出す
// 普通の方法であれば、Pipeがある場合、正常に処理できないため、複雑なコマンドをシェルにして呼出す。
str_cmd = "sh";
str_arg = "/root/Test/get_netstat_result.sh";
cmdTest.processCmd(str_cmd, str_arg);

// 直接Linuxコマンドを呼出す
// new ProcessBuilder("/bin/sh", "-c", LINUXコマンド)
cmdTest.processCmdWithOption("netstat -alpn | grep -E ':(80)' | awk {'print $1'} | grep 'tcp' | uniq -c");

System.out.println(">>> call get_ps_result.sh");
str_arg = "/root/Test/get_ps_result.sh";
cmdTest.processCmd(str_cmd, str_arg);

// Runtime#exec の方法でLinuxコマンドを呼出す。
str_cmd = "/root/Test/get_netstat_result.sh";
runCmd(str_cmd);
}

// in the case of Runtime
public static void runCmd(String cmd) {
try {
Runtime r = Runtime.getRuntime();

Process process = r.exec(cmd);
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String line = br.readLine();
while (line != null) {
System.out.println(line) ;
line = br.readLine();
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
br.close();
is.close();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}

// in the case of ragurar processBuilder
public long processCmd(String cmd, String arg){
long rtn = 0;

ProcessBuilder pb = new ProcessBuilder(cmd, arg);
pb.redirectErrorStream(true);

try {
Process process = pb.start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String line = br.readLine();
if (line != null) {
System.out.println(line) ;
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
br.close();
is.close();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
return rtn;
}

// in the case of processBuilder with option
public long processCmdWithOption(String cmd){
long rtn = 0;

ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd);
pb.redirectErrorStream(true);

try {
Process process = pb.start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String line = br.readLine();
if (line != null) {
System.out.println(line) ;
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
br.close();
is.close();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
return rtn;
}
}