Skip to content

Instantly share code, notes, and snippets.

@dreamkidd
Created April 7, 2015 04:27
Show Gist options
  • Save dreamkidd/b243ac04657a6b85317b to your computer and use it in GitHub Desktop.
Save dreamkidd/b243ac04657a6b85317b to your computer and use it in GitHub Desktop.
执行Shell命令
package com.baimes.utils;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Ds_Kidd on 2015/4/7 0007.
*/
public class JavaShellUtil {
//基本路径
private static final String bashPath = "";
//记录Shell执行情况的日志文件的位置(绝对路径)
private static final String executeShellLogFile = bashPath + "executeShell.log";
//需要执行的Shell的文件位置(Shell)
private static final String executeShellFile = bashPath +"executeShell.sh";
/**
* 执行Shell脚本方法
* @param shellCommand shell命令
* @return 返回0表示为不成功,返回1表示成功
*/
public int executeShell(String shellCommand) throws IOException {
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\n");
Process pid = null;
String[] command = {"/bin/sh","-c",shellCommand};
pid = Runtime.getRuntime().exec(command);
if (pid != null){
stringBuffer.append("进程号:").append(pid.toString()).append(" \r\n");
}else {
stringBuffer.append("没有进程号 \r\n");
}
} catch (IOException e) {
stringBuffer.append("执行Shell命令时异常: \r\n").append(e.getMessage()).append("\r\n");
}finally {
if(bufferedReader != null){
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream,"utf-8");
outputStreamWriter.write(stringBuffer.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment