Java - Executing exe with Admin Rights

Ângelo picture Ângelo · Apr 15, 2014 · Viewed 8.6k times · Source

I'm currently developing a study tool which groups several portable system management tools (mainly sysinternal tools). I have a simple frame with a JButton.

What am I trying to do? - Along with my java file i have an exe file (for example purposes let's use config.exe) which needs elevated rights to run.

After the user clicks on the button how can i do this execute this file?

EDIT: I just found one other way to do it. I made a exe from my jar file and went to the compatibility tab and checked "Always Run as admin" Thank you for all of your help.

Answer

ShihabSoft picture ShihabSoft · Apr 15, 2014

First of all locate the directory in which the exe file is located.Then create a text file named as

"Your_Exe_File_Name".exe.manifest

Just put the below contents to the file and save it.

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.1.1.1"
   processorArchitecture="X86"
   name="MyApp.exe"
   type="win32"/>
  <description>elevate execution level</description>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
  <security>
   <requestedPrivileges>
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
   </requestedPrivileges>
  </security>
  </trustInfo>
 </assembly>

Now use this in your java code to invoke the exe.It will be automatically invoked with Admin Rights.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2",).start();
InputStream is = process.getInputStream();//Get an inputstream from the process which is being executed
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);//Prints all the outputs.Which is coming from the executed Process
}

I think it will be helpful for you.