Execute Shell Commands

This feature allows you to execute Shell commands or complete Shell scripts on the device. All commands are executed as the root user. Additionally, to support long-running scripts, this feature also supports scripts that run in the background without exiting.

Foreground Command Execution

You can use it as shown below to quickly execute a command or script. This operation will block the current process, so your script or command should not run for too long. It is intended for short-running scripts (0-10 seconds).

cmd = d.execute_script("whoami")
>>> d.execute_script("notexist")
exitstatus: 127
stderr: "mksh: <stdin>[2]: notexist: inaccessible or not found\n"

The output returns the exit status code, as well as the standard output and standard error.

print (cmd.stdout)
print (cmd.stderr)
print (cmd.exitstatus)
>>> result = d.execute_script("id")
>>> print (result.stdout)
b'uid=0(root) gid=0(root)\n'
>>> print (result.stderr)
b''
>>> print (result.exitstatus)
0

Background Command Execution

Background command execution is used for long-running scripts. Considering that users might write infinite loops or scripts with endless output, which could exhaust memory, it is not possible to retrieve the execution results of background scripts. If you need to get the script's output, you should handle file output within the script itself.

The following call will execute a long-running sleep script. It returns an sid string, which is the ID of this background script.

script = "sleep 100; exit 0;"
sid = d.execute_background_script(script)

If the script encounters an unexpected situation, you can also use the following call to forcibly terminate the script running in the background.

d.kill_background_script(sid)

You can use the following call to check if the background script has finished running by its sid.

d.is_background_script_finished(sid)
>>> script = "sleep 100; exit 0;"
>>> sid = d.execute_background_script(script)
>>> print (sid)
ba06da93-c3aa-4457-b90e-247e42a16207
>>> d.is_background_script_finished(sid)
False
>>> d.kill_background_script(sid)
True
>>> d.is_background_script_finished(sid)
True