tags:

views:

347

answers:

2

We have a java application running as a windows service. A particular functionality needs to execute a binary but with a different user then which started the application.

Is there any way by which we can invoke an exe with 'Run as a different user' style.

I checked API of ProcessBuilder but didn't found anything related to user. Is there any 3rd party tool to achieve this.

A: 

I believe you can use the runas DOS command in a pinch, if you can't find something else. (Type runas in a dos prompt for usage info.)

Edit: Unfortunately, according to a note here this apparently won't work from a service. :/ You might be able to create a small separate wrapper app that you could invoke which would then invoke the binary with runas, though.

Amber
But there is no way to specify the password.
Kamal Joshi
+1  A: 

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

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

You can then use ProcessBuilder to build the command around this.

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

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

You can then use it like this:

startProcess("Bob", "Password", "Notepad.exe", "C:\\myfile.txt");
Jared Russell