views:

205

answers:

3

Hello All...

I am developing an application where i required to run some of the scripts of unix from Java Code.

Platform i am using is Unix, Tomcat 5.5..

For that, My Sample Code is as follows :

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("netstat -i|tail -n +3|cut -d ' ' -f1");
System.out.println("exitValue = "+proc.exitValue());

I have given all the rights to tomcat user.

Now, my program output cases are :

Script                         exitValue()
=======                        ============
netstat -i                          0
netstat -i|tail -n +3               4
sudo netstat -i                     1
sudo netstat -i|tail -n +3          1

Above table suggest that only 1st script is executing in unix, all others are failing.

I am not sure, but i am just assuming that i have to run Tomcat Server as a root user..

Can anybody have any other solution, then please reply..

Thanks in advance...

A: 

Using | to chain commands in Unix is part of the shell, and Runtime.exec() runs the command directly, not though the shell. A quick fix may be (untested as I don't have a Unix box available at this moment) to prefix the shell as the first command.

Process proc = runtime.exec("/bin/sh netstat -i|tail -n +3|cut -d ' ' -f1");
Jason Faust
+1  A: 

If I remember correctly, pipes ("|") are handled by the shell. Java will probably not handle them at all ...

There are a few workarounds :

  • run bash with your commands as a parameter :

    runtime.exec("bash -c \"netstat -i|tail -n +3|cut -d ' ' -f1\"");

  • write a bash script that run all those commands and run this script from Java :

    #!/bin/bash
    netstat -i|tail -n +3|cut -d ' ' -f1

  • create the pipes in Java : read the output of netstat -i and connect it in Java to tail -n +3 ...

Guillaume
A: 

Got the solution of above problem..

I have just created simple shell script file, and put the script inside that .sh file.

Now at the java side, i am just calling simple shell script file..

Process proc = runtime.exec("sh /usr/tmp/try1.sh");

That's it!!!

Nirmal