从android执行shell命令

du7egjpx  于 2022-12-13  发布在  Shell
关注(0)|答案(4)|浏览(197)

我尝试从应用程序模拟器终端(您可以在Google Play中找到它)执行此命令,在此应用程序中,我写入su并按回车键,因此写入:
screenrecord --time-limit 10 /sdcard/MyVideo.mp4
并再次按下回车键,开始使用android kitkat的新功能录制屏幕。
所以我试着用下面的代码从java中执行相同的代码:

Process su = Runtime.getRuntime().exec("su");
Process execute = Runtime.getRuntime().exec("screenrecord --time-limit 10 /sdcard/MyVideo.mp4");

但不工作,因为该文件没有创建。显然,我运行在安装了Android Kitkat的根设备上。问题在哪里?我如何解决?因为从终端模拟器的作品,在Java中没有?

fnx2tebb

fnx2tebb1#

您应该获取刚刚启动的su进程的标准输入,并在其中写下命令,否则您将使用当前的UID运行命令。
请尝试以下操作:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}
tvmytwxo

tvmytwxo2#

@CarloCannas对代码的修改:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You欢迎为 outputStream.close() 找到更好的位置)
用法示例:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

**更新:**要获得结果(输出到stdout),请用途:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

静默关闭多个Closeables(Soсket may be no Closeable)的实用程序为:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}
r7knjye2

r7knjye23#

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;
5vf7fwbs

5vf7fwbs4#

迟回复,但会对某人有利。你可以在exec()方法中使用sh命令。下面是我的例子:

try {
    File workingDirectory = new File(getApplicationContext().getFilesDir().getPath());
    Process shProcess = Runtime.getRuntime().exec("sh", null, workingDirectory);
    try{
        PrintWriter outputExec = new PrintWriter(new OutputStreamWriter(shProcess.getOutputStream()));
        outputExec.println("PATH=$PATH:/data/data/com.bokili.server.nginx/files;export LD_LIBRARY_PATH=/data/data/com.bokili.server.nginx/files;nginx;exit;");
        outputExec.flush();
    } catch(Exception ignored){  }
    shProcess.waitFor();
} catch (IOException ignored) {
} catch (InterruptedException e) {
    try{ Thread.currentThread().interrupt(); }catch(Exception ignored){}
} catch (Exception ignored) { }

首先调用shell,然后更改(设置)其中必要的环境,最后用它启动nginx。
这也适用于无根设备。
你好。

相关问题