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 ...
随机推荐
- How To Crop Bitmap For UWP
裁剪图片主要是借助于 BitmapDecoder.GetPixelDataAsync() 以及 BitmapTransform对象来实现. 实现的代码如下: using System; using S ...
- python中@staticmethod与@classmethod
@ 首先这里介绍一下‘@’的作用,‘@’用作函数的修饰符,是python2.4新增的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行.只可以对模块或者类定义的函数进行修饰,不允许修饰一个 ...
- [Java初探04]__字符串(String类)相关
前言 接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面 ...
- C/C++求职宝典21个重点笔记(常考笔试面试点)
这是我之前准备找工作时看<C/C++求职宝典>一书做的笔记,都是一些笔试面试中常考的重点难点问题,但比较基础,适合初学者看. 1. char c = '\72'; 中的\72代表一个字符, ...
- Linux配置多个Tomcat同时运行
Linux系统下怎样配置多个Tomcat同时运行呢,首先修改变量为第一个tomcat,然后修改第二个tomcat启动的脚本 1.修改环境变量 # vi /etc/profile ####### 工程1 ...
- 卸载或重新安装Redis集群
卸载或重新安装Redis集群 1.如果需要修改端口号,则需要将原来的Redis各节点的服务器卸载,并重新安装, 卸载服务命令如下: D:/Redis/redis-server.exe --servic ...
- nginx-access.log的logstash解析
1.nginx的access的格式: log_format hehe '$http_host $server_addr $remote_addr [$time_local] "$reques ...
- bootstrap 通过js代码创建和关闭插件
插件的创建机制 默认情况下,boostrap.js文件被页面加载执行完成后,boostrap会自动根据html元素的data-toggle属性和相关class创建插件对象.有时候,我们不希望boost ...
- [转]TFS常用的命令行详解
本文转自:http://blchen.com/tfs-common-commands/ 微软的TFS和Visual Studio整合的非常好,但是在开发过程中,很多时候只用GUI图形界面就会发现一些复 ...
- Autofac和nopcommerce中的Autofac, 还有反射
随笔分类 - Ioc Ioc容器Autofac系列(3)-- 三种注册组件的方式 摘要: 简单来说,所谓注册组件,就是注册类并映射为接口,然后根据接口获取对应类,Autofac将被注册的类称为组件. ...