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 ...
随机推荐
- C#简单操作MongoDB
一 安装MongoDB 官网按需下载, 安装, 一步到位. 二 VS创建新项目 创建一个.netcore console项目, 然后nuget安装驱动MongoDB.Driver 三 建立连接 在Pr ...
- 使用.NetCore在Linux上写TCP listen 重启后无法绑定地址
拥抱.net core的过程中, 将公司的一套java项目改成了.net core 2.0版的. 里面的tcp服务被我用msdn的SocketAsyncEventArgs方式重写了, 然而在测试的过程 ...
- 剑指offer十之矩形覆盖
一.题目 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形.请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? 二.解答思路 如果第一步选择竖方向填充,则剩下的填充规模缩小 ...
- android初探
随着nodejs的不断发展,前端的范围越来越大,所以,适当的了解移动端是非常有必要的,比如使用RN开发app,前端必须要和安卓工程师沟通共同开发,那么学习android的基本知识就很重要了,因为目前安 ...
- TDD并不是看上去的那么美
原文:http://coolshell.cn/articles/3649.html 春节前的一篇那些炒作过度的技术和概念中对敏捷和中国ThoughtWorks的微辞引发了很多争议,也惊动了中国Thou ...
- 全网最详细的Sublime Text 3的插件官方网站(图文详解)
不多说,直接上干货! 全网最详细的Windows里下载与安装Sublime Text *(图文详解) 全网最详细的Sublime Text 3的激活(图文详解) 全网最详细的Sublime Text ...
- 选择 Python3.6 还是 Python 3.7
转自:白月黑羽在线教程:http://www.python3.vip/doc/blog/python/home/ 选择 Python3.6 还是 Python 3.7 Python 3.7 已经发布了 ...
- j2ee高级开发技术课程第四周
分析hello.java,在hello1项目中.下载链接:https://github.com/javaee/tutorial-examples/tree/master/web/jsf/hello1 ...
- ansible 角色登陆
用ansible 来管理远程的主机,最大的好处是方便,ansible不用在远程的主机上安装ansible的客户端,ansible只要能通过ssh连接上远程主机就 能对它进行管理.也就是说ansible ...
- CentOS7 apache
1.准备环境 centos7最小化安装 yum安装wget.vim.gcc.gcc-c++.cmake 2.安装apache2.4.10 官网:http://httpd.apache.org/ 下载源 ...