Unable to send OS X terminal command via Java - java

I am trying to see if an iPhone is in tehtered mode on OS X and I am unable to send a terminal command using this code:
String [] cmdArray = new String[1];
cmdArray[0] = "/usr/sbin/networksetup -getinfo \"iPhone USB\"";
SendCommandForResponse(cmdArray);
...
static String SendCommandForResponse(String[] commandArray) throws IOException {
InputStream processOutput;
BufferedReader reader = null;
String line = " ", output = " ";
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(commandArray);
processOutput = p.getInputStream();
reader = new BufferedReader(new InputStreamReader(processOutput));
while ((line = reader.readLine()) != null) {
System.out.println(line);
output += line + "\n";
}
return output;
}
When this code is ran, I receive this error:
IOException: java.io.IOException: Cannot run program
"/usr/sbin/networksetup -getinfo "iPhone USB"": error=2, No such file
or directory
I am able to run this command successfully through terminal manually but when ran inside NetBeans it gives an exception. What am I doing wrong? I am new to Java on OS X.

You should fill the command array like this:
String[] cmdArray = new String[3];
cmdArray[0] = "/usr/sbin/networksetup";
cmdArray[1] = "-getinfo";
cmdArray[2] = "iPhone USB";
Or in short:
String[] cmdArray = { "/usr/sbin/networksetup", "-getinfo", "iPhone USB" };
The first item should be only the command (the program to run)
The next items are the arguments
There is no need for extra quotes around an argument with a space in it.
When you run a command from Terminal directly, the shell interprets the command and separates it for you - which is why you need the quotes. But when you are running it from Java, the command is not handed to a shell and is not parsed. You have to do the separation of the command and the arguments yourself.

Related

Executing linux command from java using exec('command') method

I am trying to execute a Linux command from my java class using the method exec() from the Runtime class in this way:
public static String xxUtilInfoFile (String sPath , String sFileName) throws Exception
{
Runtime r = null;
Process p = null;
String line_value="";
String output_data="";
/*execute the process*/
r = Runtime.getRuntime();
p = r.exec("file -bi " + sPath + sFileName);
p.waitFor();
/*Return the standard error output*/
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
output_data = in.readLine();
return output_data;
}
The Linux command I want to use is file -bi fileName and it runs well except in the case the fileName has blanks inside, and that is the point.
I've already tried to use double quotes and backslash (\) because this method runs in the Linux bash console, but it doesn't run if I pass it as an argument of exec method.
Could anyone help me to resolve this issue?
Perhaps, you should pass an array of Strings to the exec() method at line 9 of your code:
p = r.exec(new String[]{ "file", "-bi", sPath, sFileName});

Why does running MAKE from a Java application result in an error message?

I try to run Linux shell command from Java. The commands work fine directly on the shell, but one always crash.
I have a makefile and I try to run the make through Java.
My Java code:
String command = "make generate FILE=" + name ;
String [] envp = { } ;
File dir = new File ( System.getProperty("user.dir")) ;
Process proc = Runtime.getRuntime().exec(command,envp,dir);
proc.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
My makefile:
generate:
llvm-as -f VSOP_Executable/$(FILE).ll -o $(FILE).bc
llc $(FILE).bc
gcc -c $(FILE).s -o $(FILE).o
gcc $(FILE).o -o $(FILE) -no-pie
It always crash at the last line, where I try to generate an executable.
The error:
makefile:47: recipe for target 'generate' failed
Solved as Paul Hicks wrote in his comment. The reason was clearing all environment variables.
I changed the code and removed the empty envp. It seems to work now.
String cmd = "make generateVSOP FILE=" + name;
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}

Using Runtime.getRuntime().exec with multiple parameters

So I trying to use Runtime.getRuntime().exec to execute a openview command from Java code. This exact command runs fine on command prompt on the server does the necessary updates, but fails to perform when executed through Java code. The issue is that it returns exit status code of success i,e "0" when invoked through Java, but doesn't performs the updates it is suppose to do (appears like it is not executing).
Here is the command :
opcmsg application='Tester Down 11' object='My Support' severity=minor msg_grp='MyGroup' msg_text='DEV: -m=New Details:Request Detail description'
Here is the code :
String[] command = {
"opcmsg",
"application=\'Tester Down 11\'",
"object=\'My Support\'",
"severity=minor",
"msg_grp=\'MyGroup\'",
"msg_text=\'DEV: -m=New Details:Request Detail description\'"
}
p = Runtime.getRuntime().exec(command);
InputStream stderr = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String errorDescription = null;
while ( (errorDescription = br.readLine()) != null)
LOGGER.info(errorDescription);
exitStatus = p.waitFor();
LOGGER.info("exitStatus : " + exitStatus);
This worked :
String[] command = { "/bin/sh",
"-c",
"opcmsg application=\'Tester Down 11\' object=\'My Support\' severity=minor msg_grp=\'MyGroup\' msg_text=\'DEV: -m=New Details:Request Detail description\' " }

Buffered Reader Outputting Runtime exec Commands

Created this function to input unix commands and output the outputs of that unix command. But, I am having trouble with the unix commands I use. "ls" works to output the list of files, but if I do "ls -lart" it will output null. Having trouble further debugging or why this doesn't work. Code below.
private String[] unixCommand (String command, Boolean boolOutput) throws IOException, InterruptedException{
Process run;
int i = 0;
String output = "";
String[] finalOutput = new String[1000];
sendToProcessView("Unix Command: " + command);
run = Runtime.getRuntime().exec(command);
run.waitFor();
sendToProcessView("In Unix Command");
if (boolOutput == true){
sendToProcessView("In Output Mode of Unix Command");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(run.getInputStream()));
sendToProcessView("Passed Buffer Reader");
while ((output = stdInput.readLine()) != null) {
sendToProcessView("Output: " + output);
finalOutput[i] = output;
i++;
}
}
return finalOutput;
}
When interacting with the console, you should exec the console itself, and then use the Process input stream to send commands, eg (pseudocode - I'm not set up to test java code from my location, sorry)
sendToProcessView("Unix Command: " + command);
run = Runtime.getRuntime().exec("bash");
PrintStream in = new PrintStream(run.getOutputStream());
in.println("ls -lart");
You can then shut the process down by sending "exit" and reading the results the way you were, or using a threaded listener, like DataFetcher

Cannot launch shell script with arguments using Java ProcessBuilder

I am trying to execute a shell script with command line arguments using ProcessBuilder, this shell script inturn calls two other shell scripts that uses this argument. The first shell script runs fine, but when the second one is started it returns exit code 1.
ProcessBuilder snippet from Java Program:
//scenario - A string that holds a numerical value like 1 or 2 etc
String[] command2 = {"/bin/bash", "<path to shell script>/runTemporaryTestSuite.sh", scenario};
ProcessBuilder pb2 = new ProcessBuilder(command2);
Process p2 = pb2.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
//print - is an object ref of response.getWriter() //
print.println("Output of running "+Arrays.toString(command2)+" is: ");
while ((line = br.readLine()) != null) {
print.println(line);
}
try {
int exitValue = p2.waitFor();
print.println("<br><br>Exit Value of p2 is " + exitValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
runTemporaryTestSuite.sh
#!/bin/bash
sh <path to script>/clearRegressionResult.sh (This runs fine)
sh <path to script>/startRegression.sh $1 (This is where the issue occurs)
startRegression.sh looks like:
SUITE_PATH="./"
java -DconfigPath=${SUITE_PATH}/config.xml -Dscenario=$1 -Dauto=true -jar test.jar
My output:
Output of running [/bin/bash, /runTemporaryTestSuite.sh, 29] is:
Exit Value of p2 is 1
Any help in resolving this is really appreciated.
In think the problem is not that you cannot launch shell script with arguments, I was curious and I did a test
public class Main {
public static void main(String[] args) throws IOException {
String[] command = {"/bin/bash", "test.sh", "Argument1"};
ProcessBuilder p = new ProcessBuilder(command);
Process p2 = p.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
System.out.println("Output of running " + command + " is: ");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
here is the test.sh script
echo Hello im the script, here your args $#
Here the output
Output of running [Ljava.lang.String;#604e9f7f is:
Hello im the script, here your args Argument1
What I think is just that your startRegression.sh exit with a non-0 status (aka it failed somewhere) and it have repercussion, runTemporaryTestSuite.sh will also exit with a non-zero status, and so on hence the message : Exit Value of p2 is 1
What I see right now,
SUITE_PATH="./"
java -DconfigPath=${SUITE_PATH}/config.xml [..] the configPath will be .//config.xml so maybe you have a plain file not found issue? I might be wrong, hope it helped

Categories