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
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命令的更多相关文章
- Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现
# coding=utf8 import paramiko """ /* python -m pip install paramiko python version 3. ...
- Python下调用Linux的Shell命令
有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的.那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1. os 模块 ...
- java基础/java调用shell命令和脚本
一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...
- loadrunner调用plink,远程linux执行shell命令
loadrunner调用plink,远程linux执行shell命令 脚本: Action() { char* cmd; cmd = lr_eval_string("C:\\\&qu ...
- 【转载】如何在C语言中调用shell命令
转载自:http://blog.csdn.net/chdhust/article/details/7951576 如何在C语言中调用shell命令 在linux操作系统中,很多shell命令使用起来非 ...
- Linux主要shell命令详解(上)
[摘自网络] kill -9 -1即实现用kill命令退出系统 Linux主要shell命令详解 [上篇] shell是用户和Linux操作系统之间的接口.Linux中有多种shell,其中缺省使用的 ...
- 用Python调用Shell命令
Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如下几种方式: 第一种 ...
- Awk中调用shell命令
Awk中调用shell命令 需求 在awk中,有时候需要调用linux系统中命令,如计算字符串的MD5值,并保存下来. 方法参考 call a shell command from inside aw ...
- python 调用shell命令三种方法
#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...
- python 调用shell命令的方法
在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...
随机推荐
- docker centos7 配置和宿主机同网段IP
docker centos7 配置和宿主机同网段IP 1.安装brctl 命令 # yum -y install bridge-utils 2.编辑网卡配置文件 # vi ifcfg-eno16777 ...
- c++ 回调的实现
什么是回调?通常发生在需要两个角色即调用者与实现者的情形上,即我们希望当产生某个事件时,调用实现者定义的某个函数.当然这个概念很大,不是说操作系统的信号量,条件变量什么的,是在语言级别实现,如一个Fr ...
- 题解 洛谷P4198/BZOJ2957【楼房重建】
每个楼房,还有修改操作.简单的想到用线段树来维护信息. 显然线段树只需要维护y/x即可,对于每一个楼房,能看见的条件就是前面楼房的y/x的严格小于当前楼房的y/x. 线段树的区间修改不再赘述. 那么怎 ...
- POJ 1664 放苹果( 递推关系 )
链接:传送门 思路:苹果m个,盘子n个.假设 f ( m , n ) 代表 m 个苹果,n个盘子有 f ( m , n ) 种放法. 根据 n 和 m 的关系可以进一步分析: 特殊的 n = 1 || ...
- sizeof and strlen 的区别
首先,strlen 是函数,sizeof 是运算操作符,二者得到的结果类型为 size_t,即 unsigned int 类型.大部分编译程序在编译的时候就把 sizeof 计算过了,而 strlen ...
- HTML5地理定位-Geolocation API
HTML5提供了一组Geolocation API,来自navigator定位对象的子对象,获取用户的地理位置信息Geolocation API使用方法:1.判断是否支持 navigator.geol ...
- ArcGIS:Hello World Maps
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout ...
- MySQL-----增
增 **创建用户** create user 'alex'@'192.168.1.1' identified by '123123'; create user 'alex'@'192.168.1.%' ...
- POJ1222熄灯问题【位运算+枚举】
EXTENDED LIGHTS OUT Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 14231 Accepted: 8 ...
- Directory获取方式
1) FSDirectory.open FSDirectory.open()会以最合适的方式来获取一个Directory对象. 2) RAMDirectory 可以将磁盘中的索引加载到内存中,访问速度 ...