Java does not execute one sh file, and never ends - java

I'm trying to execute one sh file that run postgres commands, but it never ends.
The sh file is that:
#!/bin/bash
echo "My ARGUMENTS $1 $2 $3 $4";
psql -h $1 -p $2 -U $3 -d template1 -c "drop database IF EXISTS $4";
psql -h $1 -p $2 -U $3 -d template1 -c "create database $4";
echo "OPERATION COMPLETED";
And my java method is the following:
public void createDB() {
try{
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls");
ProcessBuilder pb = new ProcessBuilder("/tmp/test.sh", "localhost", "5432", "postgres", "newDB");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}catch (Exception e) {
System.out.println("ERORR");
}
}
the output is:
My ARGUMENTS localhost 5432 postgres newDB
But never execute the second psql statement, can someone help me please.

The soluction was the following:
public void createDB() {
try{
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls");
ProcessBuilder pb = new ProcessBuilder("/tmp/test.sh", "localhost", "5432", "postgres", "newDB");
// set environment variable password
env.put("PGPASSWORD", "123456");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}catch (Exception e) {
System.out.println("ERORR");
}
}
I pass the password by enviroment variable. Thanks to all!

Related

How to execute cmd line of psexec and log to text file in a single line using JAVA?

I am trying to execute the following line in java(with escaped characters):
"psexec -i -d \\\\computerName -u user -p pass calc 2>
somePath\\psexecOut.txt"
I use the following method to execute cmd lines:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
The line is executed and calc is starting , but the log part doesn't work. The log file psexecOut.txt is not created.
When I run the command normally (without excaped characters) in cmd it runs fine and the log file is created, but using java it doesn't create the log file.
I suspect that > needs to be escaped but as I read it's already escaped as it is.
How can I execute the psexec with log to text file in a single cmd line using java like I can do manually in windows console ?
Solved:
As lit suggested in the comments: cmd.exe /c works.
So the corrected method is:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec("cmd.exe /c "+command); // <-correction done here
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
Try putting cmd.exe /C at the beginning of the command? It is cmd.exe that interprets the > redirection.
"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"

How to get processbuilder command before execution

I want to know the command that will be executed before it happens.
String cmd[] = {"curl",
"-X",
"POST",
"https://api.renam.cl/medicion/insert?access-token={Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD}",
"-H",
"content-type: application/json",
"-d",
json.toString()};
ProcessBuilder pb = new ProcessBuilder(cmd);
Log.debug("COMANDO.TOSTRING " + pb.command().toString());
Process p = pb.start();
Log.debug(p.getOutputStream().toString());
p.waitFor();
BufferedReader reader
= new BufferedReader(new InputStreamReader(p.getInputStream()));
String readline;
while ((readline = reader.readLine()) != null) {
Log.debug(readline);
}
With the readline I have the server answer output but I don't know hot to get the curl command I have exectuted with the processbuilder.
EDIT 1:
I just need to send this command by using the linux console:
curl -X POST 'https://api.com/data/insert?access-token=Yoq3UGQqDKP4D1L3Y6xIYp-Lb6fyvavpF3Lm-8cD' -H 'content-type: application/json' -d '{ "pm25":2, "timestamp":1495077872, "dispositivo_mac": "12:34:56:78:90:12" }'
Basically I need to print the cmd array processed by the ProcessBuilder object to see it before the star method execution.
I had success with this code:
ProcessBuilder pb = new ProcessBuilder(command);
logger.debug(String.join(" ",pb.command().toArray(new String[0])));
Here is code for printing the runnable command:
private String getRunnableCommand(ProcessBuilder processBuilder)
{
List<String> commandsList = processBuilder.command();
StringBuilder runnableCommandBuilder = new StringBuilder();
int commandIndex = 0;
for (String command : commandsList)
{
if (command.contains(" "))
{
runnableCommandBuilder.append("\"");
}
runnableCommandBuilder.append(command);
if (command.contains(" "))
{
runnableCommandBuilder.append("\"");
}
if (commandIndex != commandsList.size() - 1)
{
runnableCommandBuilder.append(" ");
}
commandIndex++;
}
return runnableCommandBuilder.toString();
}
It will surround arguments containing spaces properly with quotation marks.

Java ProcessBuilder executing command has no output

I am using ProcessBuilder to execute git command inside my java application. The output string is correct when the command is "git status" or "git branch", however the output was empty when the command is "git clone". I wonder how can I get the output string of "git clone". Thanks in advance.
try {
ProcessBuilder pb = new ProcessBuilder("git", "clone", "address");
Process pr = pb.start();
BufferedReader buf = new BufferReader(new InputStreamReader(pr.getInputStream()));
String cmdLine = "";
while ((cmdLine = buf.readLine()) != null) {
System.out.println(cmdLine);
}
} catch (Exception e) {
}

How can I run command from Java code and read the output?

I am writing a code to execute a command and reading the output
If I run the command on command prompt, it looks like this
Command is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
Command produces multi line output. How can I print this output in my java code?
I have written following code, but it produces output as command itself that is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
rather than actual command output as we can see it in the screenshot
final String cmd = "java -cp \"*\" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin";
final String path = "C:/Project/stanford-corenlp-full-2015-01-29/stanford-corenlp-full-2015-01-29";
String input = "excellent";
String cmdString = "echo '" +input + "' | " + cmd;
Process process = Runtime.getRuntime().exec(cmdString,null, new File(path));
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
Try using ProcessBuilder:
try {
ProcessBuilder pb = new ProcessBuilder("your command here");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (InterruptedException e) {
//handle exception
}

Running executable from java fails

I am trying to run mdb-export on a file I know exist in that directory. But it does not seem to execute. "ls-l" will so I am sure that the java code is working. The command will execute perfectly from bash.
The failing command is
/usr/bin/mdb-export -Q -d ';' -D '%Y-%m-%d %H:%M:%S' /home/jocke/viking.mdb resultat >> resultat.csv
private void runCommand() {
try {
String workingdirectory=System.getProperty("user.dir");
Runtime runtime = Runtime.getRuntime();
//Process process = runtime.exec("/usr/bin/mdb-export -Q -d ';' -D '%Y-%m-%d %H:%M:%S' /home/jocke/viking.mdb resultat >> resultat.csv");
Process process = runtime.exec("/usr/bin/mdb-export /home/jocke/viking.mdb resultat >> resultat.csv");
//
process.waitFor();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
You cannot use output redirection this way. Use a ProcessBuilder instead:
ProcessBuilder pb = new ProcessBuilder("/usr/bin/mdb-export", "/home/jocke/viking.mdb", "resultat");
File csv = new File("resultat.csv");
pb.redirectOutput(Redirect.appendTo(csv);
Process p = pb.start();

Categories

Resources