Passing parameters from a Java program to shell script - java

I am developing a web application wherein I am using JSP as my front end and shell script as my back end. Thus I would be passing parameters from input JSP to the shell script via a Java Program(Business Layer). I would like to know how would I be able to pass parameters from Java to shell script and execute the same.Thank you.

you can use ProcessBuilder to pass parameter to shell script.
ProcessBuilder pb = new ProcessBuilder("shellscript", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();

I have figured out the answer and I think this might be helpful for people.
Please refer to the code
public static BufferedReader process() throws IOException
{
ProcessBuilder pb = new ProcessBuilder("/home/XXXX/Desktop/request.sh","Apple");
String line;
Process process=pb.start();
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
return br;
}
Here "Apple" is the input parameter for the shell script and that will be stored in $1(environmental variable) and this could be accessed from shell script and when something needs to be sent from shell script to Java, echo from shell script and get that from process.inputStream() in Java ..

Related

Difference when executing linux command from terminal and java runtime process

I'm looking a way to write running log of python which is executed by java app via script.
Let's say my script is:
import time
for x in range(120):
print("Running ", x)
time.sleep(1)
Here is my current solution:
Trigger script using java
String cmd = "python script.py";
var process = Runtime.getRuntime().exec(cmd, null, new File(sandboxPath));
Write log to new file:
String traceLogCmd = String.format("strace -p %s -s 9999 -e trace=write -o output.txt", process.pid());
Runtime.getRuntime().exec(traceLogCmd, null, new File(sandboxPath));
Now the problem is output.txt only has content whenever the python script is done executing so that I cannot tailf the output file.
Meanwhile if I execute python script.py and strace command dirrectly from terminal, the output is exactly what I expected.
Can someone correct me if I did something wrong or have a another way to get python log?
Thanks in advance.
Use ProcessBuilder instead of Runtime.exec(). More details: When Runtime.exec() won't
The following code will append to StringBuilder object output of the script sb.append(line);. It would not be difficult to write that content to a file.
Process p = new ProcessBuilder("sh", "-c", "python", "path-to-your-script").start();
String result = getCommandResult(p.getInputStream());
private static String getCommandResult(InputStream stream) throws IOException {
StringBuilder sb = new StringBuilder();
try (InputStreamReader isr = new InputStreamReader(stream);
BufferedReader in = new BufferedReader(isr)) {
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
}
return sb.toString().trim();
}

How to launch a python script from java ee? [duplicate]

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.
You could do either
Put your command to a shell script and execute that shell script with .exec() or
You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
#Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().
Process p = Runtime.exec(
new String[]{"python", "script.py", packet.toString()});
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
You would do worse than to try embedding jython and executing your script. A simple example should help:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
If you need further help, leave a comment. This does not create an additional process.
First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"
String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line = "", output = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
output = sb.toString();
System.out.println(output);

Java ProcessBuilder: OutputStream(Reader) of a process never gets ready() for *certain* commands

I've written an interface to call shell commands from Java for testing purposes. For a few commands, that works quite fine, but for others, the OutputStream of the process never gets ready(). Does anyone have an explanation ? I give the full code:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.err.print("cmd: ");
String line=in.readLine();
The following are all fine for "cat -n", not for "sed s/a/e/"
ProcessBuilder pb = new ProcessBuilder(Arrays.asList(("bash -c \""+line+"\"").split(" ")));
// ProcessBuilder pb = new ProcessBuilder(Arrays.asList(("cmd /C "+line).split(" ")));
// ProcessBuilder pb = new ProcessBuilder("cmd","/C",line);
// ProcessBuilder pb = new ProcessBuilder("bash","-c",line);
// ProcessBuilder pb = new ProcessBuilder(Arrays.asList(line.split(" ")));
Interaction with the process:
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedWriter toP = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
BufferedReader fromP = new BufferedReader(new InputStreamReader(p.getInputStream()));
for(line = in.readLine(); line!=null; line=in.readLine()) {
toP.write(line+"\n");
toP.flush();
System.err.println("stdin: \""+line+"\"");
while(!fromP.ready()); // sed hangs, cat doesn't
System.out.println("result: \""+fromP.readLine()+"\"");
}
One can find plenty of information on ProcessBuilder issues, and for most of them, wrapping stdin and stdout into different Threads seems to be a solution. But if indeed this is the solution, then why ?
An further: Does anyone have an explanation why the straight-forward approach fails and under what circumstances this occurs ? From the example, I can rule out that it is the way the arguments are presented or the specific shell (cmd/bash).
I'm working with Java 1.6 on a Windows7 machine with Cygwin installed, hence both bash and cmd. Could that be a Cygwin issue ?

Execute command using Java on Windows

I want to execute a command mspview -r "C:\\Users\\SS\\Desktop\\phantomjs-1.9.2-windows\\image.tif". How can I do it via Java code? I am trying to do this with a batch file. The same command when I run with the help of RUN. I am getting correct output. I have executed a .exe program with the help of a batch file with the following code C:\Users\SS\Desktop\phantomjs-1.9.2-windows\phantomjs.exe.
You're basically asking how to run shell commands in java, right?
Runtime.getRuntime().exec("whatever system call you want");
You need to use ProcessBuilder
Process process = new ProcessBuilder(
"C:\\PathToExe\\exe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
code that is already found on stackoverflow
Execute external program in java

How to execute Python script from Java (via command line)?

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.
You could do either
Put your command to a shell script and execute that shell script with .exec() or
You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
#Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().
Process p = Runtime.exec(
new String[]{"python", "script.py", packet.toString()});
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
You would do worse than to try embedding jython and executing your script. A simple example should help:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
If you need further help, leave a comment. This does not create an additional process.
First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"
String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line = "", output = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
output = sb.toString();
System.out.println(output);

Categories

Resources