Java Program That Runs Commands with Linux Terminal

How do i run a Linux terminal cmd from a java program

You can use the below command format to run your Linux command.

Runtime r = Runtime.getRuntime();
Process p = r.exec(yourcmd);

Please go through Running unix command from Java and Unable to run Unix command in Java-Stackoverflow

Hope you get your answers here.

Java Program that runs commands with Linux Terminal

You "could" read the process input and when you "detect" the password prompt, display a JOptionPane and request that the user enter the password.

You "could" prompt the user for the password before you start the process, knowing that you are going to need to send it to the process.

You would probably still need to monitor the output of the process to determine when you need to send the password though.

Let's start with...

Runtime.getRuntime().exec("sudo python ./flashimage.py");

You are ignoring the Process completely. Neither are you processing the output, but you have no means to provide input to the process...

Generally, Runtime#exec is problematic at best. You are far better of using ProcessBuilder....

// Build the command to be executed.  Note that each parameter becomes
// it's own argument, this deals with parameters that contain spaces
// much better then Runtime#exec alone...
ProcessBuilder pb = new ProcessBuilder("sudo", "python", "./flashimage.py");
pb.redirectError();

InputStream is = null;
try {
Process p = pb.start();
is = p.getInputStream();
StringBuilder output = new StringBuilder(80);
int in = -1;
while ((in = is.read()) != -1) {
if (in != '\n') {
output.append((char)in);
// You will need to define PASSWORD_PROMPT
if (PASSWORD_PROMPT.equals(output.toString())) {
String text = JOptionPane.showInputDialog("Password");
OutputStream os = p.getOutputStream();
os.write(text.getBytes());
}
} else {
System.out.println(output.toString());
output.delete(0, output.length());
}
}
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e) {
}
}

Now, undoubtedly, someone will point out (at least) two problems with this approach...

  1. JOptionPane.showInputDialog("Password"); will present a normal JTextField, which won't hide the password characters and
  2. String is not the safest way to to store a password...

Instead, we should use a JPasswordField and convert the resulting char array to a byte array...

JPasswordField password = new JPasswordField(10);
JLabel label = new JLabel("Password: ");
JPanel panel = new JPanel();
panel.add(label);
panel.add(password);

int option = JOptionPane.showConfirmDialog(null, panel, "Password", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
char[] userPassword = password.getPassword();
byte[] bytes = new byte[userPassword.length * 2];
for (int i = 0; i < userPassword.length; i++) {
bytes[i * 2] = (byte) (userPassword[i] >> 8);
bytes[i * 2 + 1] = (byte) userPassword[i];
}
os.write(bytes);
}

How to run commands you can run on terminal in Java

The existing answers give you the information on how to solve your problem in code, but they don't give a reason why your code is not working.

When you execute a program on a shell, there's significant processing done by the shell, before the program is ever executed. Your command line

    String[] command = {"ag","startTimes conf.js >> pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);

assumes that the command ag is run with the single argument startTimes conf.js >> pro.txt - most likely not what you want to do. Let's go one step further: What if you wrote

    String[] command = {"ag","startTimes", "conf.js", ">>", "pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);

?

This would assume that the ag command knows about the >> parameter to redirect its output - and here is where the shell comes into play: The >> operator is an instruction to the shell, telling it what to do with the output from stdout of the process. The process ag, when started by the shell, never has an idea of this redirection and has no clue about >> and the target file name at all.

With this information, just use the code samples from any of the other answers. I won't copy them into mine for proper attribution.

Executing terminal commands from java

I don't have a Linux system here to play with, but I'm pretty certain that the second command above is trying to compile Java files named "Test.java", "&&", "java" and "Test"; in other words the Runtime.exec() method treats arguments literally instead of applying shell interpretation.

You could probably get it to work with something along the lines of:

Process p = Runtime.getRuntime().exec(
new String[] { "sh", "-c", "javac Test.java && java Test" });

Linux terminal command execution with java

The commands you try to run will all run in parallel, without any control over which will run first or their order.

That means some command can (and will) fail if the are happening in the wrong order.

One simple way to solve it is to call waitFor on the Process object, to wait for each command to finish before starting the next.

I recommend you create a new function to run a command and wait for it to finish:

private void runCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);

// Wait for command to finish
proc.waitFor();
} catch (IOException e) {
System.out.println("Error running command: " + e.toString());
}
}

Then you can call this for each of your commands:

runCommand("rm -r /home/ctm-tech/Documenti/App/Thermaskin");
runCommand("cp -r /media/ctm-tech/FXPoWer_1/Thermaskin /home/ctm-tech/Documenti/App/");
runCommand("java -jar /home/ctm-tech/Documenti/App/Thermaskin/dist/Thermaskin.jar");
runCommand("sudo eject /media/ctm-tech/FXPoWer_1");

These commands will now run in the exact sequence called.

Run command in linux terminal using java program?

You need to run it using bash executable like this:

 Runtime.getRuntime().exec("/bin/bash -c \"unset DISPLAY\"");


Related Topics



Leave a reply



Submit