0

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...

3 Answers 3

2

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 ...

Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

0

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!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.