Android 用java语言执行Shell命令
最近项目中需要用到java语言来执行shell命令,在网上查了资料, 把自己在项目里用到的命令整理成了工具类开放给大家,希望对大家有用。功能不全,后期我会慢慢添加整合。
public class ShellUtils {
public static final String COMMAND_SU = "su";
public static final String COMMAND_SH = "sh";
public static final String COMMAND_EXIT = "exit\n";
public static final String COMMAND_LINE_END = "\n";
private ShellUtils() {
throw new AssertionError();
}
/**
* 查看是否有了root权限
*
* @return
*/
public static boolean checkRootPermission() {
return execCommand("echo root", true, false).result == ;
}
/**
* 执行shell命令,默认返回结果
*
* @param command
* command
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot) {
return execCommand(new String[] { command }, isRoot, true);
}
/**
* 执行shell命令,默认返回结果
*
* @param commands
* command list
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(List<String> commands,
boolean isRoot) {
return execCommand(
commands == null ? null : commands.toArray(new String[] {}),
isRoot, true);
}
/**
* 执行shell命令,默认返回结果
*
* @param commands
* command array
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String[] commands, boolean isRoot) {
return execCommand(commands, isRoot, true);
}
/**
* execute shell command
*
* @param command
* command
* @param 运行是否需要root权限
* @param isNeedResultMsg
* whether need result msg
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot,
boolean isNeedResultMsg) {
return execCommand(new String[] { command }, isRoot, isNeedResultMsg);
}
/**
* execute shell commands
*
* @param commands
* command list
* @param 运行是否需要root权限
* @param 是否需要返回运行结果
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(List<String> commands,
boolean isRoot, boolean isNeedResultMsg) {
return execCommand(
commands == null ? null : commands.toArray(new String[] {}),
isRoot, isNeedResultMsg);
}
/**
* execute shell commands
*
* @param commands
* command array
* @param 运行是否需要root权限
* @param 是否需要返回运行结果
* @return <ul>
* <li>if isNeedResultMsg is false, {@link CommandResult#successMsg}
* is null and {@link CommandResult#errorMsg} is null.</li>
* <li>if {@link CommandResult#result} is -1, there maybe some
* excepiton.</li>
* </ul>
*/
public static CommandResult execCommand(String[] commands, boolean isRoot,
boolean isNeedResultMsg) {
int result = -;
if (commands == null || commands.length == ) {
return new CommandResult(result, null, null);
}
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec(
isRoot ? COMMAND_SU : COMMAND_SH);
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) {
continue;
}
// donnot use os.writeBytes(commmand), avoid chinese charset
// error
os.write(command.getBytes());
os.writeBytes(COMMAND_LINE_END);
os.flush();
}
os.writeBytes(COMMAND_EXIT);
os.flush();
result = process.waitFor();
// get command result
if (isNeedResultMsg) {
successMsg = new StringBuilder();
errorMsg = new StringBuilder();
successResult = new BufferedReader(new InputStreamReader(
process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
return new CommandResult(result, successMsg == null ? null
: successMsg.toString(), errorMsg == null ? null
: errorMsg.toString());
}
/**
* 运行结果
* <ul>
* <li>{@link CommandResult#result} means result of command, 0 means normal,
* else means error, same to excute in linux shell</li>
* <li>{@link CommandResult#successMsg} means success message of command
* result</li>
* <li>{@link CommandResult#errorMsg} means error message of command result</li>
* </ul>
*
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a>
* 2013-5-16
*/
public static class CommandResult {
/** 运行结果 **/
public int result;
/** 运行成功结果 **/
public String successMsg;
/** 运行失败结果 **/
public String errorMsg;
public CommandResult(int result) {
this.result = result;
}
public CommandResult(int result, String successMsg, String errorMsg) {
this.result = result;
this.successMsg = successMsg;
this.errorMsg = errorMsg;
}
}
}
Android 用java语言执行Shell命令的更多相关文章
- 【Hadoop离线基础总结】通过Java代码执行Shell命令
通过Java代码执行Shell命令 需求 在实际工作中,总会有些时候需要我们通过java代码通过远程连接去linux服务器上面执行一些shell命令,包括一些集群的状态管理,执行任务,集群的可视化界面 ...
- C++/Php/Python 语言执行shell命令
编程中经常需要在程序中使用shell命令来简化程序,这里记录一下. 1. C++ 执行shell命令 #include <iostream> #include <string> ...
- Java远程执行Shell命令
1. Jar包:ganymed-ssh2-build210.jar 2. 步骤: a) 连接: Connection conn = new Connection(ipAddr); conn.conne ...
- Linux下C语言执行shell命令
有时候在代码中需要使用到shell命令的情况,下面就介绍一下怎么在C语言中调用shell命令: 这里使用popen来实现,关于popen的介绍,查看 http://man7.org/linux/man ...
- java 执行shell命令及日志收集避坑指南
有时候我们需要调用系统命令执行一些东西,可能是为了方便,也可能是没有办法必须要调用.涉及执行系统命令的东西,则就不能做跨平台了,这和java语言的初衷是相背的. 废话不多说,java如何执行shell ...
- Android Java执行Shell命令
最新内容建议直接访问原文:http://www.trinea.cn/android/android-java-execute-shell-commands/ 主要介绍Android或Java应用中如何 ...
- Android执行shell命令
一.方法 /** * 执行一个shell命令,并返回字符串值 * * @param cmd * 命令名称&参数组成的数组(例如:{"/system/bin/cat", &q ...
- Android执行shell命令 top ps
Android执行shell命令 一.方法 /** * 执行一个shell命令,并返回字符串值 * * @param cmd * 命令名称&参数组成的数组(例如:{"/system/ ...
- Java 实现 ssh命令 登录主机执行shell命令
Java 实现 ssh命令 登录主机执行shell命令 1.SSH命令 SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Network Working Group)所制定:SS ...
随机推荐
- Form表单中不同的按钮进行不同的跳转
本文参考:http://my.oschina.net/sallency/blog/300568 在开发工作共我们往往会遇到一个表单需要包含多个action不同的提交动作,这时候就不能在使用submit ...
- js中编写velocity逻辑
<script type="text/javascript"> $(function(){ #foreach( $var in $entity.showConfigs ...
- Vue笔记:使用 VS Code 断点调试
直接在 Chrome 的调试窗口中调试 Vue 代码有诸多不便, 好在 Visual Studio Code 中提供了 Debugger for Chrome 插件,能够通过配置直接在 VS Code ...
- sql-原生jdbc连接7步
原生jdbc链接一般分为7步, 来获取链接并执行sql语句 1, 准备4大参数 static { url = "jdbc:mysql://localhost:3306/test" ...
- AR介绍
AR介绍 AR全名扩增实境,是一种实时融合现实与虚拟的图像技术. AR技术的三板斧:感知(寻找目标定位位置-与环境交互),渲染(实现产品交互-与客户交互),追踪(捕捉目标运动轨迹-客户环境上下文). ...
- 和我一起打造个简单搜索之ElasticSearch入门
本文简单介绍了使用 Rest 接口,对 es 进行操作,更深入的学习,可以参考文末部分. 环境 本文以及后续 es 系列文章都基于 5.5.3 这个版本的 elasticsearch ,这个版本比较稳 ...
- logstash-input-jdbc同时同步多个表
同步一个表,可以参考我的上一篇 logstash-jdbc-input与mysql数据库同步 同步多个表的做法,跟一个表类似,唯一不同的是 .conf 文件中的配置 在这里我加了一个脚本文件jdbc- ...
- 管理git生成的多个ssh key
http://www.bootcss.com/p/git-guide/ 问题阐述 当有多个git账号的时候,比如一个github,用于自己进行一些开发活动,再来一个gitlab,一般是公司内部的git ...
- Qt编写自定义控件12-进度仪表盘
前言 进度仪表盘主要应用场景是标识一个任务进度完成的状况等,可以自由的设置范围值和当前值,为了美观还提供了四种指示器(圆形指示器/指针指示器/圆角指针指示器/三角形指示器),各种颜色都可以设置,其中的 ...
- JVM学习记录-类加载器
前言 JVM设计团队把类加载阶段中的“通过一个类的全限定名来获取描述此类的二进制字节流”这个动作放到Java虚拟机外面去实现,以便让应用程序自己决定如何去获取所需要的类.实现这个动作的代码模块称为“类 ...