Java를 이용하여 Shell Command를 실행하는 Program
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * TODO : 클래스 설명 작성 * * @author : 윤주석 * @since 1.0 * @see */ public class ShellCommander {
public String execute(String command) { StringBuffer output = new StringBuffer(); Process process = null; BufferedReader br = null; Runtime runtime = Runtime.getRuntime(); String osName = System.getProperty("os.name");
// win if (osName.contains("Windows")) { command = "cmd /c " + command; }
try { process = runtime.exec(command);
// write process input br = new BufferedReader(new InputStreamReader(process.getInputStream())); String msg = null; while ((msg=br.readLine()) != null) { output.append(msg + System.getProperty("line.separator")); } br.close();
// write error input br = new BufferedReader(new InputStreamReader(process.getErrorStream())); while((msg=br.readLine())!=null) { output.append(msg + System.getProperty("line.separator")); } // br.close(); } catch (IOException e) { output.append("IOException : " + e.getMessage()); e.printStackTrace(); } finally { process.destroy(); try { if(br!=null) br.close(); } catch (IOException e) { e.printStackTrace(); } }
return output.toString(); } } |
[실행 Method]
public class RunShell {
public static void main(String[] args) { ShellCommander sc = new ShellCommander();
if (args.length ==0 ) { System.out.println("ERROR !! Input parameter!!"); System.exit(1); }
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) { sb.append(args[i]); sb.append(" "); }
String output = sc.execute(sb.toString().trim());
System.out.println(output); } } |
실행방법
> java -jar RunShell.jar ls -al |
<결과>
drwxr-xr-x. 6 root root 4096 2016-09-27 16:09 . dr-xr-x---. 19 root root 4096 2016-09-26 13:47 .. -rw-r--r--. 1 root root 10181 2016-09-27 16:15 ShellCmd.jar .... |