How to execute sh file from rest service on linux - java

I have a rest service written in java on linux machine.
I'm using:
p = Runtime.getRuntime().exec(cmmnd);
or
ProcessBuilder pb = new ProcessBuilder(cmmnd).inheritIO();
p = pb.start();
p.waitFor();
I can execute commands like mkdir, touch ...
But when i try to run sh file nothing happens (for example: sudo sh /home/mydir/myfile.sh)
Is it a permission issue? How can I resolve that?

Only file execution permission is not suffice here. First run the command sudo sh /home/mydir/myfile.sh from command prompt manually and check whether work or not? Is you sodo ask for a password? Is your web service account from where you are executing the command has permission to execute as sudo? Also check whether your web application has file access permission to location (means can it execute cd /home/mydir/) /home/mydir/myfile.sh or not?
Also in your code read the output and check what is the actual error?
p.getOutputStream();
Also try with:-
ProcessBuilder pb = new ProcessBuilder("sudo sh /home/mydir/myfile.sh");
pb.redirectOutput(new File("/new_path/out.txt"));
Process p = pb.start();
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}

Related

Execute a command file in jBPM

Is there any direct support (Asset) to run a batch file in jBPM.
I know that I can run Java code like below.
This is the java code I am trying to run.
ProcessBuilder pb = new ProcessBuilder("C:\\Files\\Test.bat");
Process p = pb.start();
int exitStatus = p.waitFor();
System.out.println("Execution Done. Status: "+exitStatus);
I am curious to if there is a direct way to run a Batch file directly without writing Java code manually.
I am not aware of how to execute the batch file but maybe you can try with
executing the shell script using work item handler.

Run sh script with java but it fails without showing the error

I am trying to loop into files, and run the script sh in each file using JAVA.
for (File file : files) {
if (file.isDirectory()) {
Runtime.getRuntime().exec("cmd.exe /c start "
+file.getAbsolutePath()+"\\creationNoPersisWF12.sh");
TimeUnit.SECONDS.sleep(1800);}}
The window of the script opens and get closed immediately.
However, when I try the execute the scripts sh from outside, they execute successfully.
I need some help please.
Process process = Runtime.getRuntime().exec("cmd.exe /c start "
+file.getAbsolutePath()+"\\creationNoPersisWF12.sh");
if(process.exitValue()!=0){
throw new RuntimeException(new String(process.getErrorStream().readAllBytes()));
}
you have to check the exit value and read the error stream for the errors since its a process on its own, it won't throw any error on its own after invoking the process you have to check if it ran successfully with exitvalue 0 or not.

Java - Wait for shell to complete tar task before process ends

I'm using java's "Process" command to execute a shell script.
In this shell script, it will break down files (from a folder) into smaller Mbs.
Once the files are being broken down, I will use SMTP to mail over those files via email.
The problem is, my mailing function runs before the shell script could actually finish chopping down my files. In the end, no email was being sent out (because apparently the folder is empty).
Here are my codes:
try {
log.info("Going to run the runtime.getRuntime() to execute tar zip files");
String tarLocation = prop.getProperty("tarzipfile.location") + prop.getProperty("tarshell.name");
Process p = Runtime.getRuntime().exec(new String[] {"cmd", "/c", tarLocation});
p.waitFor(); //This waitfor only waits for process, but not the shell to complete
log.info("exit: " + p.exitValue());
p.destroy();
} catch(Exception e) {
log.info("ERROR: Runtime error failed to tar files", e);
}
robot.process(); //Send out mail
My tar file
cd <my file dir>
tar cvzf - <my other file dir> | split --bytes=4MB - archive.tar.gz
What is a good way to counter this problem besides letting it 'sleep' for a few seconds?

Open a file using Java application

I'm trying to open the file using Runtime. This is similar to opening windows command prompt, and then executing the command.
Here is the code:
import java.io.IOException;
public class OpenFile {
public static void main(String[] args) {
String fileName = "E:\\Myfile.txt";
try {
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
The command prompt is opening successfully. But the file Myfile.txt is not opening. I'm getting the below error in console:
java.io.IOException: CreateProcess: E:\Myfile.txt error=193
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
at OpenFile.main(OpenFile.java:10)
How to open the file successfully?
Not really an answer, but I think it's important to describe what exactly is happening in the current version of the application.
In this part of your code;
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
You are executing an external command. To quote the question,
similar to opening windows command prompt, and then executing the
command
What you need to realize is that whatever you've given as the string gets executed. It isn't queued or anything. Thus, re-reading your code, you are asking your program to execute 2 different commands. The first would look like;
cmd.exe /c start
Which if run on the windows command prompt executes without issues. The second "command" your program attempts to execute looks like this;
E:\Myfile.txt
Try typing that into the command prompt - it will produce an error. Probably something like "command not found". This is what the exception java.io.IOException: CreateProcess is telling you. That Java was not able to create the new process you asked it to.
Now, as for actually answering the OP, I suggest this;
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});
Which, unfortunately looks exactly like an earlier answer.
You are trying to execute fileName in Runtime object, which is wrong! Try like below:
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});

Cannot execute external vb script from Java program through Jenkins Slave setup

Through Jenkins - Slave setup (running in Windows), we have created a ANT job which in internally calls the below JAVA Program,
String[] command = {"cmd" , "/c", System.getProperty("user.dir")+"/Read_email/ReadEmail.vbs"};
Process p = Runtime.getRuntime().exec(command);
System.out.println("Process Completed");
The ReadEmail.vbs file never gets called or executed.
There is no error message or warning getting generated.
When I run this java program from eclipse or through Master Jenkinks, VB Scripts gets executed without any errors.
Your
String[] command = {"cmd" , "/c", System.getProperty("user.dir")+"/Read_email/ReadEmail.vbs"};
relies on the executing process to know where to find cmd.exe and who to call for a .vbs.
I used a 'fully redundant':
String[] command = {"C:/WINDOWS/system32/cmd.exe" , "/c", "C:/WINDOWS/system32/cscript.exe", "E:/trials/SoTrials/answers/21228622/java/callme.vbs"};
try {
Process p = Runtime.getRuntime().exec(command);
} catch(Exception e) {
System.out.format("%s\n", e.toString());
}
successfully from a simple commandline program. I hope this strategy works for your more complicated Jenkins setup.

Categories

Resources