/*********************
* @CLASS:CallShell
* @DESCRIPTION:在服务器端调用shell执行操作
* @AUTHOR:yehui
* @VERSION:v1.0
* @DATE:2013-4-8 下午3:34:33
*/
public class CallShell {
public static int callShell(String shellString) {
Process process = null;
String[] shell = new String[] { "/bin/sh", "-c", shellString };
int exitValue = 0;
StringBuffer result=new StringBuffer();
try {
process = Runtime.getRuntime().exec(shell, null, null);
exitValue = process.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
result.append(line).append("\r\n");
}
input.close();
// 判断返回数据是否正确
if (result.toString().indexOf("failed") == -1){
exitValue=1;
} else {
exitValue=-1;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return exitValue;
}
/**
* @param args
*/
public static void main(String[] args) {
callShell("/home/svn/proj/D13AL/document/shell/test.sh");
// callShell("sh /home/svn/proj/D13AL/document/0_20_Cob.sh");
}
* @CLASS:CallShell
* @DESCRIPTION:在服务器端调用shell执行操作
* @AUTHOR:yehui
* @VERSION:v1.0
* @DATE:2013-4-8 下午3:34:33
*/
public class CallShell {
public static int callShell(String shellString) {
Process process = null;
String[] shell = new String[] { "/bin/sh", "-c", shellString };
int exitValue = 0;
StringBuffer result=new StringBuffer();
try {
process = Runtime.getRuntime().exec(shell, null, null);
exitValue = process.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
result.append(line).append("\r\n");
}
input.close();
// 判断返回数据是否正确
if (result.toString().indexOf("failed") == -1){
exitValue=1;
} else {
exitValue=-1;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return exitValue;
}
/**
* @param args
*/
public static void main(String[] args) {
callShell("/home/svn/proj/D13AL/document/shell/test.sh");
// callShell("sh /home/svn/proj/D13AL/document/0_20_Cob.sh");
}
}
需要执行的shell
#!/bin/sh
#print hello world in the console window
a = "hello world"
echo $a
这个shell 会返回echo $a 所对应的值“hello world”,在
执行这个后,input中会保存有”hello world“!这样的话就可以对返回值进行判断,来得知shell是否已经执行成功!
注意:一定要为shell文件添加所必要的权限