Runtime exec on ubuntu - java

I try to run the wavemon command from java and read the output.
But I can't make the Runtime.exec method work.
The echo command in comments works and prints "hello", but the wavemon command just returns "". Wavemon is installed, I even tried it with it's full path (/usr/bin/wavemon) as an argument.
Nothing works.
// call wavemon
Runtime rt = Runtime.getRuntime();
String[] cmd = { "sh", "-c", "wavemon", "-i wlan1", "-d" };
//String[] cmd = { "sh", "-c","echo hello" };
Process proc = rt.exec(cmd);
proc.waitFor();
// read wavemon output into string
Scanner is = new Scanner(new InputStreamReader(proc.getInputStream()));
StringBuffer buffer = new StringBuffer();
while (is.hasNext()) {
buffer.append(is.nextLine());
}
proc.destroy();
System.out.println(buffer.toString());
The output of the wavemon command starts with an empty line, but since I use a scanner, this should not matter?
$ wavemon -i wlan1 -d
Configured device: wlan1 (IEEE 802.11abgn)
Security: WPA, WPA2, TKIP, CCMP
...
A little detail, this code is used in the Spring framework (spring-boot, tomcat container).

You should not need the "sh -c". Try just using only:
String[] cmd = { "wavemon", "-i","wlan1", "-d" };
Also, you should put the waitFor() after reading the lines from the scanner, as this holds the thread until the process is done. However, the process might not finish until you read it's output. You can get even fancier and read all of the streams on separate threads.
This article has all the details on it http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

Related

Pipe ("|") doesn't work with ProcessBuilder in Android [duplicate]

I'm trying to use Java's ProcessBuilder class to execute a command that has a pipe in it. For example:
ls -l | grep foo
However, I get an error:
ls: |: no such file or directory
Followed by:
ls: grep: no such file or directory
Even though that command works perfectly from the command line, I can not get ProcessBuilder to execute a command that redirects its output to another.
Is there any way to accomplish this?
This should work:
ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo");
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
The simplest way is to invoke the shell with the command line as the parameter. After all, it's the shell which is interpreting "|" to mean "pipe the data between two processes".
Alternatively, you could launch each process separately, and read from the standard output of "ls -l", writing the data to the standard input of "grep" in your example.
Since Java 9, there’s genuine support for piplines in ProcessBuilder.
So you can use
List<String> result;
List<Process> processes = ProcessBuilder.startPipeline(List.of(
new ProcessBuilder("ls", "-l")
.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE),
new ProcessBuilder("grep", "foo")
.redirectError(ProcessBuilder.Redirect.INHERIT)
));
try(Scanner s = new Scanner(processes.get(processes.size() - 1).getInputStream())) {
result = s.useDelimiter("\\R").tokens().toList();
}
to get the matching lines in a list.
Or, for Windows
List<String> result;
List<Process> processes = ProcessBuilder.startPipeline(List.of(
new ProcessBuilder("cmd", "/c", "dir")
.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE),
new ProcessBuilder("find", "\"foo\"")
.redirectError(ProcessBuilder.Redirect.INHERIT)
));
try(Scanner s = new Scanner(processes.get(processes.size() - 1).getInputStream())) {
result = s.useDelimiter("\\R").tokens().toList();
}
These examples redirect stdin of the first process and all error streams to inherit, to use the same as the Java process.
You can also call .redirectOutput(ProcessBuilder.Redirect.INHERIT) on the ProcessBuilder of the last process, to print the results directly to the console (or wherever stdout has been redirected to).

Having a hard time with linux command calls in Java with exec()

I'm trying to use Runtime.getRuntime().exec() to call a program as if it was called from the terminal, but it just crashes with a fatal error after reading the first file.
In the terminal I run the command like so:
mace4 -c -f inputFile.in > outputFile.out
It works as expected, reading from the first file and outputting in the second one.
In Java I try to run it this way:
String args[] = new String[]{"mace4", "-c", "-f", inputFileName ,">",outputFileName};
try {
String s;
Process proc = Runtime.getRuntime().exec(args, null, new File("/home/user/workDirectory/"));
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
proc.waitFor();
proc.destroy();
As soon as the program reaches the end of the first file, it throws this:
Fatal error: read_all_input, file > not found
The program is quite old and I can't seem to find a way to get a more detailed error out of it..
I tried calling it with these arguments {"sh or bash", "-c", "mace4", "-c", "-f", inputFileName ,">",outputFileName} which makes the program run and then freeze (or at least nothing appears in the console)..
Am I calling the terminal command wrong and if yes what should I change?
PS: this is my first question here, if I missed anything, I'm sorry..
It looks like you're trying to use the Bash output redirection operator >. This redirects the output of the program you're running to a file (or another program)
This answer explains how to do this using ProcessBuilder which should work for what you're trying to do here.
For example:
ProcessBuilder pb = new ProcessBuilder("mace4", "-c", "-f", inputFileName);
pb.redirectOutput(new File(outputFileName));
Process p = pb.start();

complete CMD command not running from java

I am running the below query through Java on a Postgres DB using psql:
psql.exe -U <user> -w -h <host> -d <db_name> -a -f <file> 2> "<path_to_file>\psql.log"
Initially, for quite some time the java program did create the file. Then I ran into another problem, that it was not overwriting the log file. So i used file.delete() function after every time this log file got created via java.
Now, Java is not even creating the log file for some reason. If I run the above manually in command prompt, it runs absolutely fine, but not via java code. I can see this command getting run in the java log, but it does not create the log file even when i have removed the file.delete() function
I researched a lot on it but could not find any solution. Any help would be highly appreciated.
its a long code..so i will tell you the relevant part.
I am calling a function from a thread. Code is below for that function:
public static void SaveACopyfileToServer(int auditid,String filepath,String fname,String tb_name,String plpgsql_path) throws Exception
{
Map<String, String> env = System.getenv();
String plpgsql = "\""+plpgsql_path+"\" -U "+env.get("PG_USER")+" -w -h "+env.get("PG_HOST")+" -d "+env.get("PG_DB")+" -a -f "+"\""+filepath+"copy_"+tb_name+auditid+".sql\" 2> \"C:\\ER\\ETL\\logs\\psql.log\"";
System.out.println(plpgsql);
Process p = Runtime.getRuntime().exec(plpgsql);
p.getOutputStream().close();
p.waitFor();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
Calendar cal10 = Calendar.getInstance();
System.out.println("Data loaded for "+tb_name+auditid+" at "+sdf.format(cal10.getTime()));
}
After this i am calling another function which is:
public static void extracterrorreason(String fname,int auditid,String sessionid,Connection con_pg) throws FileNotFoundException, IOException, InterruptedException{
File file = new File("C:\\ER\\ETL\\logs\\psql.log");
if(file.exists())
{
System.out.println("File present");
}
else
{
System.out.println(file+" not found");
}
if (file.length()!=0){
System.out.println("Log file being read is "+file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
String out_err = line.substring(line.indexOf("ERROR"));
System.out.println(out_err);
System.out.println("Error while loading the file into Database for file "+fname);
String comment = "CopyToStage','"+out_err;
Utils.updateAuditDetailTable(auditid, sessionid, -1, comment, true, con_pg,"");
br.close();
//file.delete();
}
}
The first function used to create the psql.log file, but now it does not even create it. Not sure where is the problem. Every time i run the code and from the second function,i get the printline that log file not found. The part before the redirection of the output of the cmd command works fine.
I tried process builder also..
I even tried it with Process builder
String plpgsql = "\""+plpgsql_path+"\" -U "+env.get("PG_USER")+" -w -h "+env.get("PG_HOST")+" -d "+env.get("PG_DB")+" -a -f "+"\""+filepath+"copy_"+tb_name+auditid+".sql\" 2> \"C:\\ER\\ETL\\psql_" +auditid +".log\"";
ProcessBuilder pb = new ProcessBuilder("cmd.exe",plpgsql);
Process p =pb.start();
p.getOutputStream().close();
p.waitFor();
I expect that the problem is that Runtime.getRuntime().exec(plpgsql) is splitting the command line into arguments incorrectly. Basically, exec does not understand quoting. Instead, it splits wherever it sees one or more spaces ... even if those spaces are in quotes.
The solution is to use the exec(String[]) overload, and pass each individual argument as a separate string; e.g.
.exec(new String[]{plpgsql_path,
"-U",
env.get("PG_USER"),
"-w,
"-h",
// etcetera
});
UPDATE
I didn't notice that you were using > output redirection as well1.
That doesn't work with exec either. (And the same applies to all shell syntax.) To get redirection, you need to use ProcessBuilder and one of the redirect methods.
The other alternative is to run the command in a shell. Pass the command as a string, and let the shell take care of the quote handling, substitution of environment variables, globbing, redirection ... and so on.
For example (if you were running on UNIX, Linux or MacOSX):
.exec(new String[]{"/bin/sh", "-c", plpgsql});
For Windows
.exec(new String[]{"cmd.exe", "/C", plpgsql});
Note the "/C" option in the Windows case!
1 - It serves you right for not line-breaking that ~200 character line in your source code! Check out what Java coding standards say about source line lengths ...

Run consecutive Commands Linux with java runtime exec

I need to run two commands Linux using java code like this:
Runtime rt = Runtime.getRuntime();
Process pr=rt.exec("su - test");
String line=null;
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while((line=input.readLine()) != null) {
System.out.println(line);
}
pr = rt.exec("whoami");
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
The problem is the output of the second command ("whoami") doesn't display the current user which used on the first command ("su - test")!
Is there any problem on this code please?
In the general case, you need to run the commands in a shell. Something like this:
Process pr = rt.exec(new String[]{"/bin/sh", "-c", "cd /tmp ; ls"});
But in this case that's not going to work, because su is itself creating an interactive subshell. You can do this though:
Process pr = rt.exec(new String[]{"su", "-c", "whoami", "-", "test"});
or
Process pr = rt.exec(new String[]{"su", "test", "-c", "whoami"});
Another alternative is to use sudo instead of su; e.g.
Process pr = rt.exec(new String[]{"sudo", "-u", "test", "whoami"});
Note: while none of the above actually require this, it is a good idea to assemble the "command line" as an array of Strings, rather than getting exec to do the "parsing". (The problem is that execs splitter does not understand shell quoting.)
As stated in the Javadoc for Runtime.exec():
Executes the specified string command in a separate process.
each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the whoami command will be executed in another subprocess, again using the user that initially launched the program.
su test -c whoami
will give you the result you want.
If you want to run multiple commands in a way the commands would execute in a subshell if need be see the response here
How can I run multiple commands in just one cmd windows in Java? (using ProcessBuilder to simulate a shell)

running Echo from Java

I'm trying out the Runtime.exec() method to run a command line process.
I wrote this sample code, which runs without problems but doesn't produce a file at c:\tmp.txt.
String cmdLine = "echo foo > c:\\tmp.txt";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmdLine);
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line;
StringBuilder output = new StringBuilder();
while ((line = input.readLine()) != null) {
output.append(line);
}
int exitVal = pr.waitFor();
logger.info(String.format("Ran command '%s', got exit code %d, output:\n%s", cmdLine, exitVal, output));
The output is
INFO 21-04 20:02:03,024 - Ran command
'echo foo > c:\tmp.txt', got exit code
0, output: foo > c:\tmp.txt
echo is not a standalone command under Windows, but embedded in cmd.exe.
I believe you need to invoke a command like "cmd.exe /C echo ...".
The > is intrepreted by the shell, when echo is run in the cmmand line, and it's the shell who create the file.
When you use it from Java, there is no shell, and what the command sees as argument is :
"foo > c:\tmp.txt"
( Which you can confirm, from the execution output )
You can't just pass "> c:\tmp.txt" to Runtime.exec as part of the command line to make redirection happen. From the Javadocs: "All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream())."
If you want to redirect output to a file, to the best of my knowledge the only way to do that would be to open the file in Java, do getInputStream, and then read from the process's input stream and write to the desired file.

Categories

Resources