[Java] Java에서 Shell command 실행

2014. 3. 7. 10:47프로그래밍/Java

HttpSession session = request.getSession();

String[] exec = new String[3]; // 실행할 명령을 저장할 배열 


//Runtime 객체 생성

Runtime r = Runtime.getRuntime();



exec[0] = "/bin/sh";

exec[1] = "-c";

exec[2] = "실행할 명령 쉘";


InputStream inputStream = null;

     

BufferedReader bufferedReader = null;

String output = "";

try{


Process process = r.exec(exec); // Process 를 선언하지 않고, exec() 만 하면 실행되지 않음.


process.waitFor();

output += "명령" + exec[0] + exec[1] + exec[2] + "\n";


inputStream = process.getInputStream();

 

bufferedReader = new BufferedReader( new InputStreamReader( inputStream )); 


String msg = "";


while(true) { 

msg = bufferedReader.readLine() ; 

if( msg == null || msg.equals( "" ) ){

break ; 

}

System.out.println("msg);

output += msg;

}


} catch (IOException e) {

e.printStackTrace();

} finally {

try{if(inputStream!=null)inputStream.close();}catch(Exception e){}

try{if(bufferedReader!=null)bufferedReader.close();}catch(Exception e){

}