How to run terminal command in Android application? - java

How to send a command to the terminal through android app and get the output back? For example, sending "ls /" and getting the output to print it in the GUI?

You have to use reflection to call android.os.Exec.createSubprocess():
public String ls () {
Class<?> execClass = Class.forName("android.os.Exec");
Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
int[] pid = new int[1];
FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
String output = "";
try {
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
}
catch (IOException e) {}
return output;
}

Different solutions could be found here: http://code.google.com/p/market-enabler/wiki/ShellCommands
I've not tested them yet.

Try this answer there is way to run shell commands on android programmatically
https://stackoverflow.com/a/3350332/2425851

Related

Java function to toggle socket state via raspberry pi

I have a function in java which is being executet on my raspberry pi and should send a signal to toggle the targeted sockets state to on / off.
Thats my current function:
public static void rcswitch(int housecode,int unitcode, int onoff) throws InterruptedException, IOException {
String housestring = Integer.toString(housecode);
String unitstring = Integer.toString(unitcode);
String onoffstring = Integer.toString(onoff);
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "sudo /home/pi/rcswitch-pi/send", housestring, unitstring, onoffstring);
Process proc = builder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
}
However, it doesn't seem like the terminal is receiving the command as it does not output anything. It should show something like "command received" and execute it then. When I normally execute the /send command in the terminal it works just fine. In eclipse it just works fine and throws the expected error.
Thanks for your answers :)
It is most likely that an error has occured while executing the command. Keep in mind that Process#getInputStream() does not include standard error stream of the process. You should use Process#getErrorStream(). Something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}

How to execute code from a String in Java

I'm trying to work on a security system which needs remote debugging.So what I'm searching is a way to execute a code which is in a String,like the example below but with java.
try {
String Code = "rundll32 powrprof.dll, SetSuspendState";// the code we need to excecute
Runtime.getRuntime().exec(Code);
} catch (IOException e) {
}
String Code = "rundll32 powrprof.dll, SetSuspendState";
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(Code);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output.toString());
Please refer the following URL for further information http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
No friend you got it wrong.I really don't want to execute cmd codes.what i really want is to execute java commands.as a string which is passed as shown below.
example :
String code = "System.out.println("Test code")";
Runtime.getRuntime().exec(Code);
something like this.

put the output of the shell script into a variable in a Java program

Is there a way to get an output from a shell script program into a variable in Java program(not into the output file). The output of my shell script is the database query execution time and I need to assign that time value to a Java variable. (I am calling that shell script from Java program). And then I will need to do some other calculations on those values in Java.
Update to old question
Since Java 7 there is a new class which can easily deal with OS procecces: ProcessBuilder
.Let's assume we need to store the output of ip_conf.bat into a java String. Contents of c:\tmp\ip_conf.bat
#echo off
REM will go to standard output
ipconfig
REM will go to stadnard error
hey there!
You can read the input streams connected to the standard and error outputs of the subprocess:
ProcessBuilder pb = new ProcessBuilder("C:\\tmp\\ip_conf.bat");
Process p = pb.start();
String pOut = "";
try (InputStream stdOut = p.getInputStream();
BufferedInputStream bufferedStdOut = new BufferedInputStream(stdOut);
ByteArrayOutputStream result = new ByteArrayOutputStream()) {
int bytes = 0;
while ((bytes = bufferedStdOut.read()) != -1) {
result.write(bytes);
}
pOut = result.toString(Charset.defaultCharset().toString());
}
System.out.println(pOut);
InputStream stdErr = p.getErrorStream();
// same with the error stream ...
int exit = p.waitFor();
System.out.println("Subprocess exited with " + exit);
Below is the program that will help you store the full output of any script or any command into String object.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String output = obj.executeCommand("sh /opt/yourScriptLocation/Script.sh");
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
I just google it and there is a nice tutorial, full of examples here : http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
I know people prefere copy/paste but let's respect other people's work and go on their website :p

Java class return windows command line information

I am able to execute commands from the commandline with the code below. If a pass a working command to the code it processes and give me a return value. What I need is to get the response from the command line when it does not process correctly. So if I pass a copy command to the prompt and it executes I get a value. If I pass a copy command to the prompt and it fails I get no value. Here is my code
public String CommandLineExecuteReturn(String loc)
{
String returnValue = "";
String outValue = null;
try
{
Process p = Runtime.getRuntime().exec("cmd.exe /c "+ loc);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
;
returnValue = line;
}
}
catch (IOException e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
returnValue = stacktrace;
}
return returnValue ;
}
You also need to redirect the error stream (p.getErrorStream()) - note that reading from both streams will require two threads.
Alternatively and more easily, you could use a ProcessBuilder and call its redirectErrorStream(true) method.
See also this post.

How to Execute Windows Commands Using Java - Change Network Settings

In Java, I want to be able to execute a Windows command.
The command in question is netsh. This will enable me to set/reset my IP address.
Note that I do not want to execute a batch file.
Instead of using a batch file, I want to execute such commands directly. Is this possible?
Here is my implemented Solution for Future Reference:
public class JavaRunCommand {
private static final String CMD =
"netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0";
public static void main(String args[]) {
try {
// Run "netsh" Windows command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// Read command standard output
String s;
System.out.println("Standard output: ");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read command errors
System.out.println("Standard error: ");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Runtime.getRuntime().exec("netsh");
See Runtime Javadoc.
EDIT: A later answer by leet suggests that this process is now deprecated. However, as per the comment by DJViking, this appears not to be the case: Java 8 documentation. The method is not deprecated.
Use ProcessBuilder
ProcessBuilder pb=new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
//do something with commandline output.
}
You can run the command with Runtime.getRuntime().exec("<command>") (eg. Runtime.getRuntime().exec("tree")). But, this will only run executables found in path, not commands like echo, del, ... But only stuff like tree.com, netstat.com, ... To run regular commands, you will have to put cmd /c before the command (eg Runtime.getRuntime().exec("cmd /c echo echo"))
public static void main(String[] args) {
String command="netstat";
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works.
Runtime#exec().

Categories

Resources