Invoking an external process with another user in java

We have a java application running as a windows service. Certain functionality should execute the binary, but with another user who ran the application.

Is there a way by which we can call exe using the "Run as another user" style.

I checked the ProcessBuilder API but did not find anything related to the user. Is there any third party tool to achieve this.

+4
source share
3 answers

You can use PSExec to execute processes as another user. The command line looks like this:

psexec.exe -u username -p password mybinary.exe 

You can then use ProcessBuilder to create a team around this.

Edit: here is an example of how you can do this:

 public int startProcess(String username, String password, String executable, String... args) throws IOException { final String psexec = "C:\\PsTools\\psexec.exe"; //psexec location //Build the command line List<String> command = new LinkedList<String>(); command.add(psexec); if(username != null) { command.add("-u"); command.add(username); command.add("-p"); command.add(password); } command.add(executable); command.addAll(Arrays.asList(args)); ProcessBuilder builder = new ProcessBuilder(command); Process process = builder.start(); int returnCode; try { returnCode = process.waitFor(); } catch (InterruptedException e) { returnCode = 1; } return returnCode; } 

Then you can use it as follows:

 startProcess("Bob", "Password", "Notepad.exe", "C:\\myfile.txt"); 
+2
source

I believe that you can use the runas DOS command as a last resort, if you cannot find something else. (Type runas at the dos prompt for usage information.)

Edit: Unfortunately, according to the note here , this apparently won’t work from the service.: / You might be able to create a small separate wrapper application that you could invoke and then invoke the binary using runas .

0
source

Runtime.getRuntime (). exec (?) method.

0
source

All Articles