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 ...
随机推荐
- 安装SVN并进行汉化的详细步骤
安装SVN并进行汉化的详细步骤 SAE提供了不同的代码部署方式,可以分为两类:一是通过SVN客户端部署,这是SAE推荐的代码部署方法.另一个是通过非SVN客户端部署,即在线代码在线编辑器和推荐应用安装 ...
- Alpha冲刺(3/10)——追光的人
1.队友信息 队员学号 队员博客 221600219 小墨 https://www.cnblogs.com/hengyumo/ 221600240 真·大能猫 https://www.cnblogs. ...
- [转]Use HandleBars in Express
http://fraserxu.me/posts/Using-Handlebarsjs-with-Expressjs/ 在Express项目中使用Handlebars模板引擎 31 Aug 2014 ...
- java—单例设计模式
单例设计模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点. 1.构造方法私有化 2.声明一个本类对象 3.给外部提供一个静态方法获取对象实例 什么时候使用? 1.通过在工具类的设计中使用: ...
- linux解压zip乱码解决方案
1.向系统添加windows下的字符编码: sudo vim /var/lib/locales/supported.d/local 添加一下编码: zh_CN.GBK GBK zh_CN.GB231 ...
- tomcat如何正确的开启远程调试功能
在日常开发中,有时需要对远程服务器上的应用进行远程调试,对于tomcat,要进行远程调试其实很简单,只需要在启动tomcat时开启jpda服务即可. 什么是JPDA呢? JPDA(JavaPlatfo ...
- mycat中间件--schema.xml配置文件详解
schema.xml管理着MyCat的逻辑库.表.分片规则.DataNode以及DataSource.弄懂这些配置,是正确使用MyCat的前提. <?xml version="1.0& ...
- linux文件命令汇总
查看文件内容命令 cat 直接输出在命令行,适用于很少内容时候的输出, vim .vi 通过 编辑命令的只读模式进行文件内容的查看(翻页快捷键好像是 ctrl + F 下一页, ctrl + B 上 ...
- screen 实战后台命令执行备份
一.安装 [root@vmware ~]# yum install -y screen 二.直接在命令行键入 screen 命令 [root@vmware ~]# screen 三.暂时终端会话 那么 ...
- 从QQ音乐开发,探讨如何利用腾讯云SDK在直播中加入视频动画
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由腾讯游戏云发表于云+社区专栏 看着精彩的德甲赛事,突然裁判一声口哨,球赛断掉了,屏幕开始自动播放"吃麦趣鸡盒,看德甲比赛&q ...