to run shell script through java - java

I want to run a shell script through java .I am using license generation tool,It can be call with the help of ./LicenseGen.sh command,under it I require to execute another command
create licensekey -x license-input.xml
which create a new licensekey.xml file where license-input.xml is a input file and licensekey is a output xml file how it is posssible in java please help me.
my code is
import java.io.*;
import java.util.*;
public class ProcessExample {
/**
* #param args
*/
public static void main(String args[]) throws IOException {
File file=new File("/opt");
// List<String> list=new List<String>();
ProcessBuilder processBuilder = new ProcessBuilder("./LicenseGen.sh");
processBuilder.directory(file);
Process process=processBuilder.start();
//processBuilder.command("create licensekey -x license-input.xml");
//process=processBuilder.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);
}
}
}

You can't execute the script directly since it has to be interpreted by a shell like bash.
Note that bash is an executeable.
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/path/LicenseGen.sh");

Use commons cli http://commons.apache.org/cli/
Good luck!

I have used JSch extensively for remote login and script executions. I used google Expect4j with Jsch for executing scripts on remote machines in expect mode(send/wait). Since, you have to execute command one after another, you can try this.
It can also be used for local execution that you require. The only worry is that you need to login (into your local machine) for execution.
For jsch, go to http://www.jcraft.com/jsch/
For Expect4j, go to http://code.google.com/p/expect4j/
Thanks.

Related

How can I run a shell script, written in Bash on Ubuntu, from Java in a Windows 10 environment?

How can I run a shell script, written in Bash on Ubuntu, from Java in a Windows 10 environment?
I'm trying to use this code but it is not running nor executing the script.
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
ProcessBuilder builder = new ProcessBuilder(
"bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
Process p = builder.start();
BufferedReader r = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line != null) { System.out.print(line);}
else{break;}
}
}
First of all: did you try to execute this command from command line? If you did and it worked it means that problem is not with bash on windows but with your java program.
If you cannot execute it from command line then fix this problem first
I cannot test my program because I use Ubuntu but can advice you to try smth like this: (wait until program is over)
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(
"bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
Process p = builder.start();
/* waitFor() method stops current thread until this process is over */
p.waitFor();
// I think that scanner is a nicer way of parsing output
Scanner scanner = new Scanner(p.getInputStream());
while (scanner.hasNextLine()) {
// you do not have to create `line` outside the loop
// it does not change performance of a program
String line = scanner.nextLine();
System.out.println(line);
}
}
}
If you are trying to run a script using Java in a Windows environment, I would suggested executing it differently.
I have adapted you code from a precious question asked here :
How to run Unix shell script from Java code?
Also, this question will help you with your question:
Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)
public static void main(String[] args) throws IOException {
Process proc = Runtime.getRuntime().exec(
"/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");
BufferedReader read = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while (read.ready())
{
System.out.println(read.readLine());
}
}
I believe this is what you are looking for. I believe that your Java code was a little off and these edits should help you. After you build the java executable, you could be able to run it via Window's Command Prompt.

Executing a python script inside java map reduce

I need to execute a python script inside a java mapreduce program.
Here, in the mapper class , I need execute the the python command :
python methratio.py --ref=../refernce/referncefile -r -g --out=Ouputfile ./Inputfile
Here the Inputfile is the input file in hdfs and the outputfile (in hdfs) is where the python script writes the ouput.
Can I use process builder or any other better options are there ??
I don't know if this can help you, but you can execute system commands in this way in java:
public static void main(String[] args) throws IOException {
String s = null;
String command = "python <your_command>";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
You can see a detailed example in http://alvinalexander.com/java/edu/pj/pj010016
Hope this help you :D

Java program to run shell commands from a windows machine

I am trying to run a Java program to shell out commands on a remote (Linux) machine. I can get the putty.exe to run and then connect to the machine using SSH keys. But am not able to run the actual commands such as "bash" "ps-ef" or "ls -la". Currently using the Java runtime.exec, not sure if using the java.lang.ProcessBuilder would help? What am I doing wrong ? Any help/guidance would be greatly appreciated.. Thanks in advance
package hello;
import java.io.*;
public class RuntimeExample {
public static void main(String args[]) throws IOException {
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[]{"C:\\Users\\yky90455\\Desktop\\putty.exe","abc#login.testserver.helloworld.co.uk","bash", "ps -ef"});
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running the command is:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try Jsch From here to get the shell scrips executed from Java to some remote Linux machine. I have worked on this and it was really fun.although you may find little shortage of docs for understanding this but you can overcome that easily.
Also consider ExpectJ which is a wrapper around TCL Expect. The project does not appear to have any active development since mid 2010, but I have used it for SSH in the past.
http://expectj.sourceforge.net/apidocs/expectj/SshSpawn.html
Thanks for all your answers. I tried Ganymed SSH-2 library. It works well for the basic commands on the remote machine. I will have to explore other APIs in case I run into any limitation with SSH-2.
public class triggerPutty {
public static void main(String[] a) {
try {
String command = "putty.exe user#abc.text.com -pw password -m C:\\containing_comman.txt";
Runtime r = Runtime.getRuntime();
Process p = null;
p = r.exec(command);
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
-m helps to run your command from that file.
You can keep N number of commands in that file.. ## Heading ##

how to launch a shell script in a new gnome terminal, from a java program

I'm trying to run a shell script (say myscript.sh) from a java program.
when i run the script from terminal, like this :
./myscript.sh
it works fine.
But when i call it from the java program, with the following code :
try
{
ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
It doesnt goes the same way.
Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.
Question : Is there some way to launch this script in a new terminal using java.
PS : i've found that "gnome-terminal" command launches a new terminal in shell,
But, i'm unable to figure out, how to use the same in a java code.
i'm quite new to using shell scripting. Please help
Thanks in advance
In java:
import java.lang.Runtime;
class CLI {
public static void main(String args[]) {
String command[] = {"/bin/sh", "-c",
"gnome-terminal --execute ./myscript.sh"};
Runtime rt = Runtime.getRuntime();
try {
rt.exec(command);
} catch(Exception ex) {
// handle ex
}
}
}
And the contents of the script are:
#!/bin/bash
echo 'hello!'
bash
Notes:
You'll do this in a background thread or a worker
The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
The shell script is located in the same path as the calling Java class.
Don't overrwrite your entire PATH...
pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.
Try this instead
pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));
Or, use the full directories to your commands in your script file.
You must set your shell script file as executable first and then add the below code,
shellScriptFile.setExecutable(true);
//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("Shell script executed properly");
}
This worked for me on Ubuntu and Java 8
Process pr =new ProcessBuilder("gnome-terminal", "-e",
"./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();
The previous code creates a new terminal in a specificied directory and executes a command
script.sh Must have executable permissions
public class ShellFileInNewTerminalFromJava {
public static void main(String[] arg) {
try{
Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
}catch(Exception e){
e.printStackTrace();
}
}
}

runtime.exec() taking infinite time to execute code

I want to execute a command which takes 2 arguments.
1.input file name
2.output file name.
The command is sixV1.1 outputFile.txt
The code is:
String cmd= "sixV1.1 <inputFile.txt >outputFile.txt";
Process p=Runtime.getRuntime().exec(cmd);
int retValue=p.waitFor();
when the i run above code,it is taking infinite time.
Is it possible to give <, > charecters in cmd .Please suggest me....
The right way to do input/output redirection when you start a process in Java is to write/read from the process's streams:
Process p = Runtime.getRuntime().exec("sixV1.1");
InputStream is = p.getInputStream();
// read from is and write to outputFile.txt
OutputStream os = p.getOutputStream();
// read from inputFile.txt and write to os
There's a fantastic blog post by Michael C. Daconta about successful command line calls using Runtime in Java. It's not as easy as you might think!
The following code extract from that blog post describes "MediocreExecJava", a class that successfully runs a program using Runtime.exec() and manages its input and output without hanging. I've used it before and it works. I highly recommend reading the post to understand why!
import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}

Categories