Executing openssl command using Java runtime [duplicate] - java

How am I to execute a command in Java with parameters?
I've tried
Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});
which doesn't work.
String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);
This doesn't work as well, because the m parameter is not specified.

See if this works (sorry can't test it right now)
Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});

Use ProcessBuilder instead of Runtime#exec().
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();

The following should work fine.
Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");

Below is java code for executing python script with java.
ProcessBuilder:
First argument is path to virtual environment
Second argument is path to python file
Third argument is any argumrnt you want to pass to python script
public class JavaCode {
public static void main(String[] args) throws IOException {
String lines = null;
ProcessBuilder builder = new ProcessBuilder("/home/env-scrapping/bin/python",
"/home/Scrapping/script.py", "arg1");
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((lines = reader.readLine())!=null) {
System.out.println("Line: " + lines);
}
}
}
First is virtual environment path

Related

Issue while deleting folder from hdfs with java.lang.Process

Issue while executing hadoop command from java.lang.Process.
hadoop fs -rm -R -skipTrash pathToFolder
this command directly executed on unixbox is working but when I try to execute it from Process it says '-rm -R' unknown command.
public class Test1 {
public static void main(String[] args) throws IOException {
String[] commandToDelete = new String[]{"hadoop", "fs","-rm -R", "-skipTrash", "hdfs://pathToFolder"};
Process process = Runtime.getRuntime().exec(commandToDelete);
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(process.exitValue());
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = errorReader.readLine()) != null) {
System.out.println(line);
}
errorReader.close();
}
}
From same location I am able to delete file but not folder any suggestions please.
From exec(String[] cmdarray)
Executes the specified command and arguments in a separate process.
This is a convenience method. An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).
So you below command is run in separate process thats why -rm -R is unknown command:
String[] commandToDelete = new String[]{"hadoop", "fs","-rm -R", "-skipTrash", "hdfs://pathToFolder"};
Run like below:
String command = "hadoop fs -rm -R -skipTrash hdfs://pathToFolder"
Process process = Runtime.getRuntime().exec(command);
A more robust solution (that prevents your subsequent problem with space in the path) is to stay with the String[] form but split the arguments correctly:
String[] commandToDelete = new String[]{"hadoop", "fs", "-rm", "-R", "-skipTrash", "hdfs://pathToFolder"};

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();
}

Run exec file using Java on Mac

I need to start a server using bash, so I had created an UNIX shell , but I am not able to execute it with Java from Eclipse.
I tried the following code which doesn't work :
Process proc = Runtime.getRuntime().exec(./startServer);
Here is content of the startServer file :
#!/bin/bash
cd /Users/sujitsoni/Documents/bet/client
npm start
You can try the following two options.
Option 1
Process proc = Runtime.getRuntime().exec("/bin/bash", "-c", "<Abosulte Path>/startServer");
Option 2
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "<Absolute Path>/startServer");
pb.directory(new File("<Absolute Path>"));
Process proc = pb.start();
A couple Of things can go wrong:
The path to the file you have given might be wrong for eclipse it can take relative path but from the command line, it will take the absolute path.
error=13, Permission denied - If the script file doesn't have required permissions. In your scenario, that might not the case as you are not getting any error.
At last, you are executing the script by java program so the output of your script will not be printed out. In your scenario, this might be the case. You need to capture the output of script from BufferedReade and print it. ( In your case server might have started but you are not seeing the logs/output of the script.
See the code sample below for printing output.
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("./startServer");
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output);
}

How to run shell script which is stored in a String variable using Java?

I need to execute a shell script in Java. My shell script is not in a file, it is actually stored in a String variable. I am getting my shell script details from some other application.
I know how to execute different commands in Java as shown below:
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/david/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/david"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
In my case, I will have script information in a json string variable from which I am extracting the content of script:
{"script":"#!/bin/bash\n\necho \"Hello World\"\n"}
Below is my code in which I am extracting script content from above json and now I am not sure how can I execute this script and also pass some parameters to it. For now, I can pass any simple string parameters:
String script = extractScriptValue(path, "script"); // this will give back actual shell script
// now how can I execute this shell script using the same above program?
// Also how I can pass some parameters as well to any shell script?
After executing the above script, it should print out Hello World.
You need to start a Process with the shell, and then send your script to its input stream. The following is just a proof of concept, you'll need to change some things (like creating the process with ProcessBuilder):
public static void main(String[] args) throws IOException, InterruptedException {
// this is your script in a string
String script = "#!/bin/bash\n\necho \"Hello World\"\n echo $val";
List<String> commandList = new ArrayList<>();
commandList.add("/bin/bash");
ProcessBuilder builder = new ProcessBuilder(commandList);
builder.environment().put("val", "42");
builder.redirectErrorStream(true);
Process shell = builder.start();
// Send your script to the input of the shell, something
// like doing cat script.sh | bash in the terminal
try(OutputStream commands = shell.getOutputStream()) {
commands.write(script.getBytes());
}
// read the outcome
try(BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
// check the exit code
int exitCode = shell.waitFor();
System.out.println("EXIT CODE: " + exitCode);
}

Java runtime's .exec() wont open executable

I am trying to execute another file using Runtime and Process
try
{
Runtime run = Runtime.getRuntime();
Process pro = run.exec("C:\\Users\\user\\Desktop\\file.exe");
}
catch(Exception a)
{
a.printStackTrace();
}
I can enter this command in either run or cmd and am able to open the file but running it through my program it won't open. There are no errors, it just doesn't open.
To better understand what is going on (and it is actually a requirement of the Process class), you need to redirect the input and error streams of your process - and using a ProcessBuilder is the recommended way to start processes:
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("C:\\Users\\user\\Desktop\\file.exe");
runProcess(pb)
}
private static void runProcess(ProcessBuilder pb) throws IOException {
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
You must do
Process pro = run.exec("C:\\Users\\user\\Desktop\\file.exe",null,"C:\\Users\\user\\Desktop\\");
Please see Run .exe file from Java from file location
Try this way:
String []cmdarray = new String[4];
cmdarray[0] = "cmd";
cmdarray[1] = "/c";
cmdarray[2] = "start";
cmdarray[3] = "C:\\Users\\user\\Desktop\\file.exe";
Runtime.getRuntime().exec(cmdarray);
Try this one, create a batch file ,like start_file.bat.
The content like this:
cd C:\Users\user\Desktop ----- Goto this directory
C: ----- This line is very important
file.exe
Both the two approaches work well.
Runtime r = Runtime.getRuntime();
String []cmdarray = new String[4];
cmdarray[0] = "cmd";
cmdarray[1] = "/c";
cmdarray[2] = "start";
cmdarray[3] = "C:/users/desktop/start_file.bat";
r.exec(cmdarray);
And this one:
r.exec("C:/users/desktop/start_file.bat");
You can read the output from this new process.

Categories

Resources