使用run-as在ADB shell中复制文件

Log*_*kup 7 shell android adb

有没有办法编写一个脚本,使用run-as从ADB shell复制文件?

我知道在adb shell中复制的唯一方法就是使用cat source > dest(编辑:现代android版本有cp命令,这使得这个问题变得不必要了),但是我只能引用一个深层的大于号 - 所以我的脚本可以将它传递给adb shell,但不能传递给adb shell run-as.

例如,这有效:

adb shell "cat source > dest"

但这不是:

adb shell run-as "cat source > dest"

这不是:

adb shell "run-as cat source \> dest"

我甚至尝试创建一个小脚本并将其上传到设备,但我似乎无法从adb shell运行脚本 - 它告诉我"权限被拒绝".我也不能chmod脚本.

我想这样做的原因是将文件复制到应用程序的私有存储区域 - 具体来说,我使用脚本来修改共享首选项并将修改后的首选项放回原处.但是,只有应用程序本身或root可以写入我想要的文件.

此方案中的用例是将文件复制到设备上的受保护位置,而不是检索它; 对于检索,这个问题已经有了很好的答案.

Log*_*kup 12

按照Chris Stratton的建议,我最终使用它的方式如下(将共享首选项复制回设备):

adb push shared_prefs.xml /sdcard/temp_prefs.xml
cat <<EOF | adb shell
run-as com.example.app
cat /sdcard/temp_prefs.xml > /data/data/com.example.app/shared_prefs/com.example.app_preferences.xml
exit
exit
EOF
Run Code Online (Sandbox Code Playgroud)

直接管道adb shell run-as没有工作,我不知道为什么,但管道adb shell做.诀窍是然后从交互式shell调用run-as,并继续接受来自管道的输入.

HERE doc让我可以轻松地将换行符嵌入到单独的命令中,通常只是让它可读; 我没有分号的运气,但这可能是因为我做事的方式.我相信它可能适用于管道多个命令/换行符的其他方法; 一旦我终于开始工作,我就停止了实验.

两个出口是必要的,以防止悬挂的外壳(可用CTRL-C播放); 一个用于run-as,另一个用于adb shell自身.看来,Adb的shell对文件结尾没有很好的响应.


Ale*_* P. 8

OP尝试将以下3个命令(他在交互式shell会话中一个接一个地执行没有问题)组合成一个非交互式命令:

adb shell
run-as com.example.app
cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml
Run Code Online (Sandbox Code Playgroud)

为简单起见,让我们从一个交互式adb shell会话开始。如果我们只是尝试将最后两个命令合并为一行:

run-as com.example.app cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml
Run Code Online (Sandbox Code Playgroud)

由于shell重定向的工作原理,此操作不起作用-仅使用cat /sdcard/temp_prefs.xml该命令的一部分运行com.example.app UID

许多人“知道”将围绕重定向的命令部分放在引号中:

run-as com.example.app "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"
Run Code Online (Sandbox Code Playgroud)

这是行不通的,因为该run-as命令不够智能,无法分析整个命令。它期望将可执行文件作为下一个参数。正确的方法是改为使用sh

run-as com.example.app sh -c "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"
Run Code Online (Sandbox Code Playgroud)

那么我们可以仅adb shell添加命令并完成它吗?不必要。通过从PC运行命令,您还可以添加另一个本地Shell及其解析器。特定的转义要求取决于您的操作系统。在Linux或OSX中(如果您的命令尚未包含'),可以很容易地用单引号将整个命令引起来,如下所示:

adb shell 'run-as com.example.app sh -c "cat /sdcard/temp_prefs.xml > shared_prefs/com.example.app_preferences.xml"'
Run Code Online (Sandbox Code Playgroud)

但是有时使用带(-或更少)引号的替代解决方案会更容易:

adb shell run-as com.example.app cp /sdcard/temp_prefs.xml shared_prefs/com.example.app_preferences.xml
Run Code Online (Sandbox Code Playgroud)

或者,如果您的设备没有以下cp命令:

adb shell run-as com.example.app dd if=/sdcard/temp_prefs.xml of=shared_prefs/com.example.app_preferences.xml
Run Code Online (Sandbox Code Playgroud)

还要注意我是如何使用它shared_prefs/com.example.app_preferences.xml而不是完整文件的/data/data/com.example.app/shared_prefs/com.example.app_preferences.xml-通常在run-as命令内部,当前目录是HOME软件包的目录。