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命令执行完毕后的退出 ...
随机推荐
- JavaScript exec()方法
exec() 方法用于检索字符串中的正则表达式的匹配.返回一个数组,其中存放匹配的结果.如果未找到匹配,则返回值为 null. var str = "我今年25岁明年26岁后年27岁千年24 ...
- 2018湖南省第14届大学生计算机程序设计竞赛 A字符画
Description 读入 w,请输出 2018 的字符画,两个数字之间有 w 个空格.具体格式请参考样例输出. 1 ≤ w ≤ 2018 Input 输入文件只包含 1 个整数 w. Output ...
- Insert 语句对 nologging 与 logging表 在不同场景下的优化
前言 前段时间报表数据库上有条insert sql语句,插入的大量数据,执行非常慢,需要对其进行分析优化. 分析步骤是在:ARCHIVE与NOARCHIVE模式下进行. 测试场景: 分别对表的常规插入 ...
- 零基础入门学习Python(23)--递归:这帮小兔崽子
知识点 我们都知道兔子繁殖能力是惊人的,如下图: 我们可以用数学函数来定义: 假设我们需要求出经历了20个月后,总共有多少对小兔崽子? 迭代实现 def fab(n): n1 = 1 n2 = 1 n ...
- Linux CentOS7.5静默安装Oracle11gR2
网上有很多安装教程,但大多不够完整,参照了一些教程,实测安装成功,整理出来分享给大家! 一.官方最低要求配置 内存:1G(官方最低要求1G) 硬盘:40G(企业版安装所需4.29G和1.7G数据文件) ...
- Qt Widgets Application可执行程序发布方式
前言 写好的Qt程序想打包发布,之前按照Qt快速入门系列教程里的方法,直接选release,构建,之后找到exe,拷贝几个dll,然而报错如图: 后来找到教程:http://tieba.baidu.c ...
- CSU1217
就跟数字出现奇数次道理是一样的,将一个数转化为2进制后找出现奇数次个1的位置,最后将其输出来便是出现奇数次的数 #include <cstdio> int main() { int n,a ...
- [luoguP2146] 软件包管理器(树链剖分)
传送门 看着很吓人,其实就是个树链剖分模板. 可支持操作: 1.将节点 x 到 根 的路径上的值都变成 1 2.将以节点 x 为根的子树的值都变成 0 1A爽~ ——代码 #include <c ...
- Spring data jpa 复杂动态查询方式总结
一.Spring data jpa 简介 首先我并不推荐使用jpa作为ORM框架,毕竟对于负责查询的时候还是不太灵活,还是建议使用mybatis,自己写sql比较好.但是如果公司用这个就没办法了,可以 ...
- 守卫者的挑战(codevs 1997)
题目描述 Description 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜寻着关押applepi的监狱的所在地.突然,眼前一道亮光闪过.“我,Nizem,是黑魔法圣殿的守卫者.如 ...