자바 linux 의 셸 스 크 립 트 호출

3801 단어 자바각본
원문
package cn.com.songjy.test.shell;
 
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
//http://kongcodecenter.iteye.com/blog/1231177
//  http://siye1982.iteye.com/blog/592405
//  http://blog.csdn.net/christophe2008/article/details/6046456
public class JavaShellUtil {
    //     
    private static final String basePath = "/root/";
 
    //   Shell            (    )
    private static final String executeShellLogFile = basePath
            + "executeShell.log";
 
    //      Kondor   Shell    (    )
    private static final String sendKondorShellName = basePath
            + "songjy.sh";
 
    public int executeShell(String shellCommand) throws IOException {
        System.out.println("shellCommand:"+shellCommand);
        int success = 0;
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        //        ,       
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
 
        try {
            stringBuffer.append(dateFormat.format(new Date()))
                    .append("    Shell   ").append(shellCommand)
                    .append(" \r
"); Process pid = null; String[] cmd = { "/bin/sh", "-c", shellCommand }; // Shell pid = Runtime.getRuntime().exec(cmd); if (pid != null) { stringBuffer.append(" :").append(pid.toString()) .append("\r
"); // bufferedReader Shell bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024); pid.waitFor(); } else { stringBuffer.append(" pid\r
"); } stringBuffer.append(dateFormat.format(new Date())).append( "Shell \r
:\r
"); String line = null; // Shell , stringBuffer while (bufferedReader != null && (line = bufferedReader.readLine()) != null) { stringBuffer.append(line).append("\r
"); } System.out.println("stringBuffer:"+stringBuffer); } catch (Exception ioe) { stringBuffer.append(" Shell :\r
").append(ioe.getMessage()) .append("\r
"); } finally { if (bufferedReader != null) { OutputStreamWriter outputStreamWriter = null; try { bufferedReader.close(); // Shell OutputStream outputStream = new FileOutputStream(executeShellLogFile); outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); outputStreamWriter.write(stringBuffer.toString()); System.out.println("stringBuffer.toString():"+stringBuffer.toString()); } catch (Exception e) { e.printStackTrace(); } finally { outputStreamWriter.close(); } } success = 1; } return success; } public static void main(String[] args) { try { new JavaShellUtil().executeShell(sendKondorShellName); } catch (IOException e) { e.printStackTrace(); } } }

좋은 웹페이지 즐겨찾기