- Execute command android code
- How to Execute Commands Remotely via SSH in Android?
- Step by Step Implementation
- Android Shell Command Reference
- Executing Shell Commands with Java
- Introduction
- Runtime.exec()
- Executing a Command from String
- Specify the Working Directory
- Using Environment Variables
- Free eBook: Git Essentials
- Running .bat and .sh Files
- ProcessBuilder
- ProcessBuilder: Executing Command from Strings
- ProcessBuilder: Specify the Working Directory
- ProcessBuilder: Environment Variables
- ProcessBuilder: Running .bat and .sh Files
- Conclusion
Execute command android code
An open source library to execute shell commands on Android or the JVM, written in Kotlin.
Download the latest JAR or grab via Gradle:
Alternatively, you can simply copy Shell.kt file to your project.
Construct a new Shell instance:
Note: If the shell does not exist a Shell.NotFoundException is thrown as a RuntimeException .
Execute a command and get the result:
A Shell.Command.Result contains the following:
- stdout : A list of lines read from the standard input stream.
- stderr : A list of lines read from the standard error stream.
- exitCode : The exit status from running the command.
- details : Additional information (start, stop, elapsed time, id, command)
Add a callback when stdout or stderr is read:
Add a callback that is invoked each time a command completes:
Execute a command with custom options:
Optionally, you can configure how each command executes by setting a timeout, redirecting stderr to stdout, add callbacks for when the command reads a line from stdout/stderr or is cancelled.
Источник
How to Execute Commands Remotely via SSH in Android?
The SSH protocol uses encryption to secure the connection between a client and a server. All user authentication, commands, output, and file transfers are encrypted to protect against attacks in the network. More often than not you would need to SSH into your cloud Virtual Machines or a remote shell. Usually, we need an SSH client to establish an SSH connection. For Windows, the free (libre) GUI client PuTTY is used for this purpose. Here is how it looks like accessing a remote Linux shell in PuTTY:
The following tutorial illustrates how the same can be achieved in android. Note that we are going to implement this project using the Java language. Library: Apache MINA SSHD
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
Now we need to add the required dependencies in order to use the apache mina sshd library. Open app/src/build.gradle file in your project directory and add the following under dependencies:
// Adding implementations required for apache mina library
Источник
Android Shell Command Reference
Clone this wiki locally
#The Android Shell
A «shell» is a program that listens to keyboard input from a user and performs actions as directed by the user. Android devices come with a simple shell program. This shell program is mostly undocumented. Since many people are curious about it I thought I’d write up some documentation for it.
The built-in shell has very limited error handling. When you type a command name incorrectly it will say «permission denied», even though the real problem is that it couldn’t find the command:
#The PATH variable
The Android shell will run any program it finds in its PATH. The PATH is a colon (‘:’) seperated list of directories. You can find out what your shell’s PATH is set to by using the built-in echo command:
Depending upon your shell, you may see a different result.
#Built in Commands
Every shell has a few built-in commands. Some common built-in commands are:
- echo — prints text to stdout.
- set — sets shell variables
- export — makes shell variables available to command-line programs
- cd — change the current directory.
- pwd — print name of the current directory.
#Commands To find out what commands you have available to you, use the «ls» command on each of the directories in the PATH variable.
##Finding documentation for the Android commands.
Many of the Android commands are based on standard Linux (or bsd) commands. If you’re curious about a command, you can sometimes learn how it works by using the «man» command on a desktop Linux or OSX (Apple Macintosh) computer. The Linux or OSX version of the command may be different in details, but much of the documentation will still apply to the Android version of the command.
Another source of documentation for people without a Linux or OSX machine handy is to use a web browser and use a web search engine to search for the text: «man Linux command-name».
##List of commands
The following is a list of the commands that are present on a Nexus S phone running an Android 2.3.3 «user-debug» build. Many of these commands are not present on a «user» phone. (They are missing from a «user» phone because they are specific to developing or debugging the Android operating system.)
Notice that by default there is no /data/local/bin directory. You can create this directory using the «mkdir» command if you like.
The /sbin directory exists, but you don’t have permission to access it. You need root access. If you have a developer phone, or otherwise have root access to your phone you can see what’s in this directory.
Notice that the shell prompt changes from a ‘$’ to a ‘#’ to indicate that you have root access.
Notice also that neither of the /sbin commands are useful to the shell — the adb and ueventd files are ‘daemon’ programs used to implement the Android Debugger «adb» program that is used by developers.
Vendor/bin is where device vendors can put device-specific executables. These files are from a Nexus S.
This directory does not exist on a Nexus S.
am is the Android Activity Manager. It’s used to start and stop Android activities (e.g. applications) from the command line. Type am by itself to get a list of options.
Command line audio file player.
Used to apply patches to android files.
Command line audio recorder.
Backup manager — type command by itself to get documentation.
Draws the boot animation. You may have to reset your phone to get out of this.
Copy the contents of a file to standard output.
Change the mode of a file (e.g. whether it can be read or written.)
Change the owner of a file.
Compare two files byte-by-byte
The dalvik virtual machine. (Used to run Android applications.)
Prints the current date and time
Convert and copy a file. By default copies standard in to standard out.
Shows how much space is free on different file systems on your device.
Shows the current configuration of network interfaces (IP, MAC address etc)
Shows the current processes using the network interfaces (top, but for networks)
Manage the firewall
Send signals to processes.
Used to set up a file system link.
Prints the Android runtime log.
Make a directory.
A program that sends random events, used to test applications. (Like having a monkey playing with the device.)
Move a file from one directory to another. (Only on the same file system. Use «cat a > b» to copy a file between file systems.
List active processes.
Reboot the device.
Remove a directory.
Starts the Android runtime.
Stops the Android runtime.
Shows which processes are currently using the most CPU time.
Prints how long your device has been running since it was last booted.
Secure copy program. (Used to copy files over the network.)
Used to administer SQLite databases.
System trace command — use to see what system calls a program makes.
Start a shell with root privileges.
#Versions of the Android Shell
- Android 1.0 used a shell that had no tab completion or history editing.
- Android 2.3 added history editing. You can for example use the up/down arrows to edit previous commands.
Busybox is a program that contains a shell and a set of command line utilities. Search Android Market for «Busybox» and you should find some versions you can install. The Busybox shell includes tab completion and history editing. Some versions of Busybox for Android do not require that you root your phone.
You can install the full Debian shell and utilities. (Debian is a popular desktop Linux distribution.) I don’t know the details, and it may require a «rooted» phone. Try a web search for «Debian Android install».
Some custom ROMs come with their own shells and utilities. If you are using a custom ROM, check its documentation to find out what’s available.
Источник
Executing Shell Commands with Java
Introduction
In this article, we’ll take a look at how we can leverage the Runtime and ProcessBuilder classes to execute shell commands and scripts with Java.
We use computers to automate many things in our daily jobs. System administrators run many commands all the time, some of which are very repetitive and require minimal changes in-between runs.
This process is also ripe for automation. There’s no need to run everything manually. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
Runtime.exec()
The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it’s in.
By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute commands directly or run .bat / .sh files.
The exec() method offers a few overloaded variations:
- public Process exec(String command) — Executes the command contained in command in a separate process.
- public Process exec(String command, String[] envp) — Executes the command , with an array of environment variables. They’re provided as an array of Strings, following the name=value format.
- public Process exec(String command, String[] envp, File dir) — Executes the command , with the specified environment variables, from within the dir directory.
- public Process exec(String cmdArray[]) — Executes a command in the form of an array of Strings.
- public Process exec(String cmdArray[], String[] envp) — Executes a command with the specified environment variables.
- public Process exec(String cmdarray[], String[] envp, File dir) — Executes a command, with the specified environment variables, from within the dir directory.
It’s worth noting that these processes are run externally from the interpreter and will be system-dependent.
What’s also worth noting is the difference between String command and String cmdArray[] . They achieve the same thing. A command is broken down into an array anyway, so using any of these two should yield the same results.
It’s up to you to decide whether exec(«dir /folder») or exec(new String[] <"dir", "/folder">is what you’d like to use.
Let’s write up a few examples to see how these overloaded methods differ from each other.
Executing a Command from String
Let’s start off with the simplest approach out of these three:
Running this code will execute the command we’ve supplied in String format. However, we don’t see anything when we run this.
To validate if this ran correctly, we’ll want to get ahold of the process object. Let’s use a BufferedReader to take a look at what’s going on:
Now, when we run this method after the exec() method, it should yield something along the lines of:
Keep in mind that we’ll have to extract the process information from the Process instances as we go through other examples.
Specify the Working Directory
If you’d like to run a command from, say, a certain folder, we’d do something along the lines of:
Here, we’ve provided the exec() method with a command , a null for new environment variables and a new File() which is set as our working directory.
The addition of cmd /c before a command such as dir is worth noting.
Since I’m working on Windows, this opens up the cmd and /c carries out the subsequent command. In this case, it’s dir .
The reason why this wasn’t mandatory for the ping example, but is mandatory for this example is nicely answered by an SO user.
Running the previous piece of code will result in:
Let’s take a look at how we could supply the previous command in several individual parts, instead of a single String:
Running this piece of code will also result in:
Ultimately, regardless of the approach — using a single String or a String array, the command you input will always be broken down into an array before getting processed by underlying logic.
Which one you’d like to use boils down just to which one you find more readable.
Using Environment Variables
Let’s take a look at how we can use environment variables:
We can supply as many environment variables as we’d like within the String array. Here, we’ve just printed the value of var1 using echo .
Running this code will return:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Running .bat and .sh Files
Sometimes, it’s just much easier to offload everything into a file and run that file instead of adding everything programmatically.
Depending on your operating system, you’d use either .bat or .sh files. Let’s create one with the contents:
Then, let’s use the same approach as before:
This’ll open up the command prompt and run the .bat file in the working directory we’ve set.
Running this code surely enough results in:
With all of the overloaded exec() signatures taken care of, let’s take a look at the ProcessBuilder class and how we can execute commands using it.
ProcessBuilder
ProcessBuilder is the underlying mechanism that runs the commands when we use the Runtime.getRuntime().exec() method:
JavaDocs for the Runtime class
Taking a look at how the ProcessBuilder takes our input from the exec() method and runs the command, gives us a good idea of how to use it as well.
It accepts a String[] cmdarray , and that’s enough to get it running. Alternatively, we can supply it with optional arguments such as the String[] envp and File dir .
Let’s explore these options.
ProcessBuilder: Executing Command from Strings
Instead of being able to provide a single String, such as cmd /c dir , we’ll have to break it up in this case. For example, if we wanted to list the files in the C:/Users directory like before, we’d do:
To actually execute a Process , we run the start() command and assign the returned value to a Process instance.
Running this code will yield:
However, this approach isn’t any better than the previous one. What’s useful with the ProcessBuilder class is that it’s customizable. We can set things programmatically, not just via commands.
ProcessBuilder: Specify the Working Directory
Instead of supplying the working directory via the command, let’s set it programmatically:
Here, we’ve set the working directory to be the same as before, but we’ve moved that definition out of the command itself. Running this code will provide the same result as the last example.
ProcessBuilder: Environment Variables
Using ProcessBuilder s methods, it’s easy to retrieve a list of environment variables in the form of a Map . It’s also easy to set environment variables so that your program can use them.
Let’s get the environment variables currently available and then add some for later use:
Here, we’ve packed the returned environment variables into a Map and ran a forEach() on it to print out the values to our console.
Running this code will yield a list of the environment variables you have on your machine:
Now, let’s add an environment variable to that list and use it:
Running this code will yield:
Of course, once the program has finished running, this variable will not stay in the list.
ProcessBuilder: Running .bat and .sh Files
If you’d like to run a file, again, we’d just supply the ProcessBuilder instance with the required information:
Running this code results in the command prompt opening up and executing the .bat file:
Conclusion
In this article, we’ve explored examples of running shell commands in Java. We’ve used the Runtime and ProcessBuilder classes to do this.
Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
Источник