execute batch file remotely java

我怕爱的太早我们不能终老 提交于 2019-12-21 05:31:25

问题


I want to execute a bat file located remotely on server \\testserver\someFolderName\test.bat. I am using process builder and wanted to chande the directory with procbuilder.directory(....), but could not succeed.

Any help is appreciated. Thanks


回答1:


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.




回答2:


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();
}



回答3:


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).




回答4:


it also works in java as below:

Process p1 = Runtime.getRuntime().exec("cmd.exe /C pushd \\yourserver\yourfolderpath && yourexecutable.bat && popd");


来源:https://stackoverflow.com/questions/3621231/execute-batch-file-remotely-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!