java操作linux,调用shell命令

java操作linux,调用shell命令
复制代码
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test001 {
public static String exec(String command) throws InterruptedException {
String returnString = “”;
Process pro = null;
Runtime runTime = Runtime.getRuntime();
if (runTime == null) {
System.err.println(“Create runtime false!”);
}
try {
pro = runTime.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null) {
returnString = returnString + line + “\n”;
}
input.close();
output.close();
pro.destroy();
} catch (IOException ex) {
Logger.getLogger(Test001.class.getName()).log(Level.SEVERE, null, ex);
}
return returnString;
}

@Test
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> test() <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Exception {
    System.out.println(exec(</span>"ls -al"<span style="color: #000000;">));
}

}

复制代码

mac同样适用

调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0

复制代码
public static void callShell(String shellString) {  
    try {  
        Process process = Runtime.getRuntime().exec(shellString);  
        int exitValue = process.waitFor();  
        if (0 != exitValue) {  
            log.error("call shell failed. error code is :" + exitValue);  
        }  
    } catch (Throwable e) {  
        log.error("call shell failed. " + e);  
    }  
}
复制代码

 

 

 

复制代码
package test.shell;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaShellUtil {
//基本路径
private static final String basePath = “/tmp/”;

</span><span style="color: #008000;">//</span><span style="color: #008000;">记录Shell执行状况的日志文件的位置(绝对路径)</span>
<span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> String executeShellLogFile = basePath + "executeShell.log"<span style="color: #000000;">;

</span><span style="color: #008000;">//</span><span style="color: #008000;">发送文件到Kondor系统的Shell的文件名(绝对路径)</span>
<span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> String sendKondorShellName = basePath + "sendKondorFile.sh"<span style="color: #000000;">;

</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> executeShell(String shellCommand) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> IOException {
    </span><span style="color: #0000ff;">int</span> success = 0<span style="color: #000000;">;
    StringBuffer stringBuffer </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> StringBuffer();
    BufferedReader bufferedReader </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;

//格式化日期时间,记录日志时使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        stringBuffer.append(dateFormat.format(</span><span style="color: #0000ff;">new</span> Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n"<span style="color: #000000;">);

        Process pid </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
        String[] cmd </span>= {"/bin/sh", "-c"<span style="color: #000000;">, shellCommand};
        </span><span style="color: #008000;">//</span><span style="color: #008000;">执行Shell命令</span>
        pid =<span style="color: #000000;"> Runtime.getRuntime().exec(cmd);
        </span><span style="color: #0000ff;">if</span> (pid != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
            stringBuffer.append(</span>"进程号:").append(pid.toString()).append("\r\n"<span style="color: #000000;">);
            </span><span style="color: #008000;">//</span><span style="color: #008000;">bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);</span>

pid.waitFor();
} else {
stringBuffer.append(“没有pid\r\n”);
}
stringBuffer.append(dateFormat.format(new Date())).append(“Shell命令执行完毕\r\n执行结果为:\r\n”);
String line = null;
//读取Shell的输出内容,并添加到stringBuffer中
while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append(“执行Shell命令时发生异常:\r\n”).append(ioe.getMessage()).append("\r\n");
} 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());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}

}

复制代码

 

 

更多资料:

http://www.cnblogs.com/shihaiming/p/5884859.html

http://www.jb51.net/article/69930.htm

 

分类: 编程技术
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值