Run Java File as Administrator with Full Privileges

Run Java file as Administrator with full privileges

This answer is for those who are wiling to provide administrative privileges to their jars or java classes. After successfully developing an exe to edit files kept in admin. restricted directories, I have developed these steps to follow for you, hope this may help you:
Things to understand:
1) Jars won't be directly compiled with privileges rather, you have to wrap them with some other mainfest file to finally have exe files capable of running on windows xp/ vista/ or higher version with privileges. Actually the possible answer uptil now is that before running, exe forces user to give admin rights unlike before where user is expected to know how to run jar with admin rights which isn't friendly.

Now the simple steps:

  1. Create your jar file like try2.jar containing some mainifest file-- My1.mf as like always.So, the absolute path of the jar file would be C:\try.jar.

  2. Now you need to download a software "Launch4j" which will help you to wrap jar files.Its download links is : http://sourceforge.net/projects/launch4j/files/launch4j-3/3.1.0-beta2/

  3. Now take out 5 min. and watch this tutorial: http://www.youtube.com/watch?v=mARUFRknTYQ ;this will tell you basic functions of Launch4j. But here it won't be clear how to create a manifest file for your exe.

  4. After learning this, then create a manifest file, it is a simple text file with extension ".manifest" saved. But here certain things to be taken care of: Firstly, your mainfest file has to have same name as that of your final exe to be created. In my case, name of my exe was supposed to be "Launchme.exe" thus, my manifest file had to be named as "Launchme.manifest". Secondly, in manifest file just copy this content:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
    <requestedPrivileges>
    <requestedExecutionLevel level="highestAvailable" uiAccess="False" />
    </requestedPrivileges>
    </security>
    </trustInfo>
    </assembly>

copy the above code into your manifest file. here line 6 is the key of whole issue. Then save it and close it.


  1. Now start Launch4j, fill all the taught textfields as like in video as per your conditions. In Wrapper mainfest column add this file manifest file. Then click "save configuration" option and then click-- Build Wrapper.

Now you have exe containing your jar which requests user to give admin rights before executing. Now user is free from knowing anything other than clicks!

Elevate Java application while running

As has been pointed in comments, sadly the Java (or any other process) cannot be elevated while running. While in the case of JWM, it could be theoretically possible to move whole program context from normal user java.exe to elevated one, I don't think it's possible. I hope some day someone will come and tell me I'm wrong.

Surprisingly, even with restart in place, this was a tricky task that took me a while to figure out.

The non java part

First, how do we exactly run a program elevated from command line? There's an answer and you can see it's not simple. But we can break it to this VBS script:

Set UAC = CreateObject("Shell.Application") 
UAC.ShellExecute "program name", "command line parameters", "working directory", "runas", 1

Soon, it also turns out that we won't have any success running java.exe from VBS script. In the end, I decided to run a helper batch file. Finally, here (answer to question in the last link) we have a complete set of two scripts which really run the given .jar file elevated. Here's improved version that allows quick testing by drag'n'dropping the Jar file on it:

' Require first command line parameter
if WScript.Arguments.Count = 0 then
MsgBox("Jar file name required.")
WScript.Quit 1
end if

' Get the script location, the directorry where it's running
Set objShell = CreateObject("Wscript.Shell")

strPath = Wscript.ScriptFullName

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
'MsgBox(strFolder)

' Create the object that serves as runnable something
Set UAC = CreateObject("Shell.Application")
' Args:
' path to executable to run
' command line parameters - first parameter of this file, which is the jar file name
' working directory (this doesn't work but I use it nevertheless)
' runas command which invokes elevation
' 0 means do not show the window. Normally, you show the window, but not this console window
' which just blinks and disappears anyway
UAC.ShellExecute "run-normally.bat", WScript.Arguments(0), strFolder, "runas", 0

WScript.Quit 0

The Java part

Java part is more straightforward. What we need to do is to open new process and execute the prepared scripts in it.

   /**
* Start this very jar file elevated on Windows. It is strongly recommended to close any existing IO
* before calling this method and avoid writing anything more to files. The new instance of this same
* program will be started and simultaneous write/write or read/write would cause errors.
* @throws FileNotFoundException if the helper vbs script was not found
* @throws IOException if there was another failure inboking VBS script
*/
public void StartWithAdminRights() throws FileNotFoundException, IOException {
//The path to the helper script. This scripts takes 1 argument which is a Jar file full path
File runAsAdmin = new File("run-as-admin.vbs");;
//Our
String jarPath;

//System.out.println("Current relative path is: " + s);

try {
jarPath = "\""+new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getAbsolutePath()+"\"";
} catch (URISyntaxException ex) {
throw new FileNotFoundException("Could not fetch the path to the current jar file. Got this URISyntax exception:"+ex);
}
//If the jar path was created but doesn't contain .jar, we're (most likely) not running from jar
//typically this happens when running the program from IDE
//These 4 lines just serve as a fallback in testing, should be deleted in production
//code and replaced with another FileNotFoundException
if(!jarPath.contains(".jar")) {
Path currentRelativePath = Paths.get("");
jarPath = "\""+currentRelativePath.toAbsolutePath().toString()+"\\AutoClient.jar\"";
}
//Now we check if the path to vbs script exists, if it does we execute it
if(runAsAdmin.exists()) {
String command = "cscript \""+runAsAdmin.getAbsolutePath()+"\" "+jarPath;
System.out.println("Executing '"+command+"'");
//Note that .exec is asynchronous
//After it starts, you must terminate your program ASAP, or you'll have 2 instances running
Runtime.getRuntime().exec(command);

}
else
throw new FileNotFoundException("The VBSScript used for elevation not found at "+runAsAdmin.getAbsolutePath());
}

Run Java application as administrator on Windows

Okay, I've finally managed to get a solution for this problem that I'm happy with; it's a bit on the ugly side, but it works for what I'm doing.

I borrowed the code from this answer to do the actual privilege elevation; from there, the question was one of actually getting that solution to work with Java. The code for that ends up looking like this:

    if (!checkPrivileges()) {
try {
String jarPath = DownloaderMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(jarPath, "UTF-8");
decodedPath = decodedPath.substring(1, decodedPath.length());
Elevator.executeAsAdministrator(System.getProperty("java.home") + "\\bin\\java", "-jar " + "\"" + decodedPath + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// Run with elevated privileges
}

The checkPrivileges method is unchanged from above and the Elevator class is virtually identical to the one that appears in the linked solution (I just took out the unneeded main method). This solution assumes that the process to be elevated is a jar; it shouldn't be too difficult to change this around to suit your individual needs.

opening jar file with admin privilege

If I understand correctly, you're trying to run java from a command prompt but want admin privileges. In that case, right-click on the "command prompt" and choose "run as administrator", then you can

java -jar myprogram.jar

from the command prompt as before.

However do you really want to allow this program to edit your hosts file? I'd recommend you find out what it's trying to do and make the change manually if you're happy with it.

Java: run as administrator

You have to create a manifest file that specifies that your application needs administrator permissions. You can include the manifest in your exe or keep it as a separate file (yourapp.exe.manifest)

http://msdn.microsoft.com/en-us/library/bb756929.aspx

How to start a java jar with administrators privileges on windows 7

You can run cmd under Administrator and launch ANTRLWorks using java -jar command.

Java - Executing exe with Admin Rights

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.



Related Topics



Leave a reply



Submit