简体   繁体   中英

run .bat file from other systems java code

I want to the run the bat file present in the other system through eclipse java.Below is the code to run if the bat file is in our system .

import java.io.IOException;
import java.io.InputStream;

public class batchFile_execution_throught_java {

public static void main(String[] args) {
     Runtime runtime = Runtime.getRuntime();
     try
     {

     Process p1 = runtime.exec("cmd /c C:\\Users\\root\\Desktop\\sample.bat");
     InputStream is = p1.getInputStream();
     int i = 0;
     while( (i = is.read() ) != -1)
     {
     System.out.print((char)i);
     }

     }
     catch(IOException ioException)
     {
     System.out.println(ioException.getMessage() );
     }
}

}

My first try will be to create a shared folder in windows, so you can access to remote file in the same way you do now:

 Process p1 = runtime.exec("cmd /c \\alias_of_folder\\sample.bat");

If create shared folder is not an option, what you need is to open an connection to the other computer from with your Java application.

  • OpenSSH site has information that will give ou ssh support in Java .
  • Also check JSch and it's examples .

UPDATE from this answer :

You can also combine Jsch with Expect4j and this way have a better control on the commands you want to execute ( nice example here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM