tharriott
tharriott

Reputation: 111

How to write a string to a cmd prompt using ProcessBuilder in Java?

I have a batch (.bat) program that asks that user to supply a hostname and password. (Two fields) I am using a separate Java application to gather to automate this task and so I need it to enter multiple hostnames at once into the script. However, I am having a hard time accomplishing this goal using ProcessBuilder. Please take a look at the below code:

This code I have only redirects the input and output to the java process. However, I would solely like to write to the cmd. Please let me know if there is any way. Thanks

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws InterruptedException,
            IOException {
        ProcessBuilder pb = new ProcessBuilder("cmd" ," /k d: && cd DATA\\Virtualization Scripts\\EMC ESXi Grab && Script_Run");
        //inherit IO
        pb.inheritIO();
        Process process = pb.start();
        process.waitFor();
    }
}

Upvotes: 0

Views: 204

Answers (1)

Sambit
Sambit

Reputation: 8011

@Tharriott, as per our discussion, first of all you have to modify a bit your batch script like this. I provide below the code.

@ECHO OFF 
set host=%1 
set password=%2

echo Host Name : %host%
echo Password : %password%

"D:\UPSDATA\Virtualization Scripts\EMC ESXi Grab\EMC-ESXi-GRAB-1.3.10\emcgrab.exe" -host %host% -vmsupport -user root -password %password% -case 00000000 -legal -customer UPS -party 00000 -contact user -phone NA -email NA 

exit

Imagine that the name of the batch script is emc-grab.bat.

Now you have to run the above batch file like this.

:/emc-grab.bat

one example is like this

D:/test/emc-grab.bat abcd.dellemc.com pa$$word99

Now what is next ?

In your java gui program, capture hostname and password, then in the processbuilder class, pass the complete command along with the file name, hostname and password.

I provide below the code snippet.

String hostNameAndPassword = "captured Host Name"+" "+"captured password";
ProcessBuilder pb = new ProcessBuilder("cmd" ,"some path:/emc-grab.bat "+hostNameAndPassword);

Try it, it will solve your problem.

Upvotes: 1

Related Questions