execute batch file remotely java

时光总嘲笑我的痴心妄想 提交于 2019-12-03 16:26:24

In the past I've done it quick and dirty with PSExec

Just start that from your program as its own process with the required arguments to gain access to the batch on the remote computer.

NagendraPrakash Karri

This is working code that we are using currently:

try {            
   ProcessBuilder launcher = new ProcessBuilder();
   Map<String, String> environment = launcher.environment();
   launcher.redirectErrorStream(true);
   launcher.directory(new File("\\\\<your remote computer name>\\TIERS\\DEV1\\RP\\VISUAL_BASIC\\"));

   environment.put("name", "var");
   launcher.command("your.exe");
   Process p = launcher.start(); // And launch a new process

} catch (Exception e){
   e.printStackTrace();
}

I don't think you can do UNC paths for the ProcessBuilder, but it doesn't really matter in any case.

To run a .bat file, you need to run a windows command shell and have that execute the .bat file, and the command shell doesn't support UNC paths... The way around it is to run your command like this:

cmd.exe /C "pushd \\testserver\someFolderName && test.bat && popd"

Essentially, you're telling the cmd prompt to mount your remote folder as a temporary drive (pushd \testserver\someFolderName), run test.bat and then unmount the temporary drive (popd).

it also works in java as below:

Process p1 = Runtime.getRuntime().exec("cmd.exe /C pushd \\yourserver\yourfolderpath && yourexecutable.bat && popd");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!