duqhiqiku
duqhiqiku

Reputation: 51

Java run terminal command and send input

I have master password for terminal setup and I would like to create a Java program which adds a few extra features. To do this I need to send and receive input/output from the terminal. I tried what was suggested in Java Program that runs commands with Linux Terminal but didn't have any luck. For some reason the input isn't passed in and Your master password: is printed out if I force stop (which is were the input was supposed to be passed in). Below is my code, can anyone see what I am doing wrong?

try
{
    // Send the command
    Process process = new ProcessBuilder("mpw", "-u", "Name", "-t", "l", "Website").start();
    String key = "somekey";
    OutputStream stdOutput = process.getOutputStream();
    // Send an input
    stdOutput.write(key.getBytes());
    // Store the input (and error) in a buffer
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // Read the output from the command:
    int data;
    while ((data = stdInput.read()) != -1)
        System.out.write(data);

    while ((data = stdError.read()) != -1)
        System.out.write(data);

    System.out.flush();
}
catch (IOException e) { e.printStackTrace(); }

Thanks in advance

Upvotes: 1

Views: 1966

Answers (1)

duqhiqiku
duqhiqiku

Reputation: 51

Thanks to Abra I was able to find the solution. For anyone looking at this later, here is the code that worked:

// Create a new process and run the command
String[] command = new String[] {"mpw", "-u", "Name", "-t", "l", "Website"}; // Can also directly be put into the process builder as an argument without it being in an array
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();

OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();

// Store the input and output streams in a buffer
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
BufferedReader error = new BufferedReader(new InputStreamReader(stderr));

// Send input
writer.write("password\n"); // Don't forget the '\n' here, otherwise it'll continue to wait for input
writer.flush();
//writer.close(); // Add if doesn't work without it

// Display the output
String line;
while ((line = reader.readLine()) != null) System.out.println(line);
// Display any errors
while ((line = error.readLine()) != null) System.out.println(line);

This should work for any command, I got the solution from Writing to InputStream of a Java Process

Upvotes: 3

Related Questions