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
public void test() throws Exception {
System.out.println(exec("ls -al"));
} }

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/"; //记录Shell执行状况的日志文件的位置(绝对路径)
private static final String executeShellLogFile = basePath + "executeShell.log"; //发送文件到Kondor系统的Shell的文件名(绝对路径)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh"; 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[] cmd = {"/bin/sh", "-c", shellCommand};
//执行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
//bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
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

java操作linux,调用shell命令的更多相关文章

  1. Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现

    # coding=utf8 import paramiko """ /* python -m pip install paramiko python version 3. ...

  2. Python下调用Linux的Shell命令

    有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的.那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1. os 模块 ...

  3. java基础/java调用shell命令和脚本

    一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...

  4. loadrunner调用plink,远程linux执行shell命令

    loadrunner调用plink,远程linux执行shell命令   脚本: Action() {   char* cmd; cmd = lr_eval_string("C:\\\&qu ...

  5. 【转载】如何在C语言中调用shell命令

    转载自:http://blog.csdn.net/chdhust/article/details/7951576 如何在C语言中调用shell命令 在linux操作系统中,很多shell命令使用起来非 ...

  6. Linux主要shell命令详解(上)

    [摘自网络] kill -9 -1即实现用kill命令退出系统 Linux主要shell命令详解 [上篇] shell是用户和Linux操作系统之间的接口.Linux中有多种shell,其中缺省使用的 ...

  7. 用Python调用Shell命令

    Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如下几种方式: 第一种 ...

  8. Awk中调用shell命令

    Awk中调用shell命令 需求 在awk中,有时候需要调用linux系统中命令,如计算字符串的MD5值,并保存下来. 方法参考 call a shell command from inside aw ...

  9. python 调用shell命令三种方法

    #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...

  10. python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

随机推荐

  1. win7系统上VMware虚拟机安装linux7.2上网配置

    环境: 本机是window7系统,安装VMware虚拟机,在VMware安装了Rdhat系统,想上网,在网上搜索了不少的配置方法,这篇文章介绍的比较全面,感谢分享,摘抄在这里让更多的爱好者学习.我自己 ...

  2. django-2 models

    一个model 对应DB的一张表 models 以类的形式表现: 一些字段.数据的一些行为 对类.类的对象 操作,无需写SQL = >  object relation mapping  ORM ...

  3. 第十六节:Scrapy爬虫框架之项目创建spider文件数据爬取

    Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取所设计的, 也可以应用在获取API所返回的数据或 ...

  4. C语言学习4

    C/C++语言五大内存分区:堆.栈.自由存储区.全局/静态存储区和常量存储区 栈:就是那些由编译器在需要的时候分配,在不需要的时候自动清楚的存储区,里面的变量通常是全局变量.函数参数等. 堆:就是那些 ...

  5. 测试第一个Oracle存储过程

    存储过程语句 //简单存储过程的例子 //每调用一次打印一次hello world create or replace procedure sayhelloworld as begin dbms_ou ...

  6. 牛客网补题 New Game!(原Wannafly summer camp day2原题)

    思路:这个题在秦皇岛的时候好像没有写出来,反正我是没有写出来,题解是听懂了:把直线和圆都看做一个结点,圆和直线用点到直线的距离与半径差求出来,圆和圆之间用点和点之间的距离和半径差表示,最后最短路跑一遍 ...

  7. [codeforces494B]Obsessive String

    [codeforces494B]Obsessive String 试题描述 Hamed has recently found a string t and suddenly became quite ...

  8. noip模拟赛 单词

    分析:这道题真心难想.最主要的是怎么样不重复. 为了不重复统计,把所有符合条件的单词分成两类,一类是某些单词的前缀,一类是 不是任何单词的前缀.涉及到前缀后缀,维护两个trie树,处理3个数组a,b, ...

  9. hdu 361B

    #include<stdio.h> int a[100100]; int main() { int n,i,k; while(scanf("%d%d",&n,& ...

  10. P1072 Hankson的趣味题

    #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #inclu ...