在 运行 时提升 Java 应用程序
Elevate Java application while running
我的软件出现了一个棘手的问题。我正在制作一个与另一个现有软件(游戏)交互的程序。用户报告他 运行 拥有管理员权限的游戏,在这种情况下,我的程序停止为他工作。
简短的调查表明,有些人确实需要 运行 管理员帐户下的游戏,而有些则不需要。如果我的程序能够检测到这一点并在管理员帐户下 运行ning 时警告用户,那就太好了:
如果用户单击 "Elevate",我想请 windows 提升 java.exe
运行 我的 jar
文件并调用典型的 UAC 对话框。
显然,这次的问题不是关于 java updater,而是关于 JRE
我的问题是:这可能吗? windows 可以提升我的 java.exe
实例的权限吗? java有办法吗?或者我可以使用命令行命令吗?
我想避免重新启动程序(尽管这可能不是什么大问题)。
编辑:
如果您查看评论,您会发现无法避免应用程序的重启 - 进程只能 start 提升,而不是 become 提升 .不幸的是,这有点改变了问题。基本上,它现在听起来更像是:“如何以管理员权限重新启动我的应用程序?”。当然,除非有像两个 java.exe
共享一个罐子这样的技巧...
正如评论中所指出的,遗憾的是 Java(或任何其他进程)无法在 运行ning 时提升。虽然在 JWM 的情况下,理论上可以将整个程序上下文从普通用户 java.exe 移动到提升的用户,但我认为这是不可能的。我希望有一天有人会来告诉我我错了。
令人惊讶的是,即使 restart 就位,这也是一项棘手的任务,我花了一段时间才弄明白。
非java部分
首先,我们如何 运行 从命令行提升程序? There's an answer 可见这并不简单。但是我们可以将它分解为这个 VBS 脚本:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "program name", "command line parameters", "working directory", "runas", 1
很快,结果也证明我们 . In the end, I decided to run a helper batch file. Finally, (在最后 link 中回答问题)我们有一套完整的两个脚本,它们确实 运行 给定的 .jar
文件提升。这是改进的版本,允许通过拖放 Jar 文件进行快速测试:
' 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
Java部分
Java 部分更直接。我们需要做的就是开启新的进程,并在其中执行准备好的脚本。
/**
* 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());
}
这是我的版本。它创建一个 VBScript 脚本,然后执行它。此 仅 如果正在 运行 的程序在 jar 文件中,因此您必须 运行 您的 IDE 作为管理员才能实际测试你的程序。
public static void relaunchAsAdmin() throws IOException {
relaunchAsAdmin(ThisClass.class); //Change ThisClass to the class that this method is in
}
public static void relaunchAsAdmin(Class<?> clazz) throws IOException {
if(isCurrentProcessElevated()) {
return;
}
final String dir = System.getProperty("java.io.tmpdir");
final File script = new File(dir, "relaunchAsAdmin" + System.nanoTime() +
".vbs");
try {
script.createNewFile();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(script));
osw.append("Set s=CreateObject(\"Shell.Application\")" + ln + "s.ShellExecute \"" +
System.getProperty("java.home") + "\bin\java.exe" + "\",\"-jar \"\"" +
new File(clazz.getProtectionDomain().getCodeSource(
).getLocation().toURI()).getAbsolutePath() + "\"\"\",,\"runas\",0" +
ln + "x=createObject(\"scripting.fileSystemObject\").deleteFile(" +
"WScript.scriptfullname)");
osw.close();
if(System.getenv("processor_architecture").equals("x86")) {
Runtime.getRuntime().exec("C:\Windows\System32\wscript.exe \"" +
script.getAbsolutePath() + "\"");
} else {
Runtime.getRuntime().exec("C:\Windows\SysWoW64\wscript.exe \"" +
script.getAbsolutePath() + "\"");
}
} catch(URISyntaxException e) {
e.printStackTrace();
}
Runtime.getRuntime().exit(0);
}
注意有点乱。我之前一直在使用这个方法,所以它被换行到 100 个字符(除了我为这个答案写的评论)。
isCurrentProcessElevated()
方法必须以一种或另一种方式实施。你可以尝试使用JNI,或者你可以使用纯粹的Java方法,比如写入Program Files或System32目录,看看是否失败。
显然,此解决方案仅适用于 Windows。我从来不需要在 Linux 或 Mac 系统上提升(主要是因为我没有任何 Mac 系统,而且我不使用 Linux - 我只是玩它)。
如果仍然感兴趣:在 Windows 7 我的 Java 电梯工作。当在 Java 应用程序的主要方法中使用时,它会提升 运行 Java 进程。只需添加 -elevate
作为最后一个程序参数并在 main 方法中使用电梯。
电梯class:
package test;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
/**
* Elevates a Java process to administrator rights if requested.
*/
public class JavaElevator {
/** The program argument indicating the need of being elevated */
private static final String ELEVATE_ARG = "-elevate";
/**
* If requested, elevates the Java process started with the given arguments to administrator level.
*
* @param args The Java program arguments
* @return The cleaned program arguments
*/
public static String[] elevate(String[] args) {
String[] result = args;
// Check for elevation marker.
boolean elevate = false;
if (args.length > 0) {
elevate = args[args.length - 1].equals(ELEVATE_ARG);
}
if (elevate) {
// Get the command and remove the elevation marker.
String command = System.getProperty("sun.java.command");
command = command.replace(ELEVATE_ARG, "");
// Get class path and default java home.
String classPath = System.getProperty("java.class.path");
String javaHome = System.getProperty("java.home");
String vm = javaHome + "\bin\java.exe";
// Check for alternate VM for elevation. Full path to the VM may be passed with: -Delevation.vm=...
if (System.getProperties().contains("elevation.vm")) {
vm = System.getProperty("elevation.vm");
}
String parameters = "-cp " + classPath;
parameters += " " + command;
Shell32.INSTANCE.ShellExecute(null, "runas", vm, parameters, null, 0);
int lastError = Kernel32.INSTANCE.GetLastError();
if (lastError != 0) {
String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
errorMessage += "\n vm: " + vm;
errorMessage += "\n parameters: " + parameters;
throw new IllegalStateException("Error performing elevation: " + lastError + ": " + errorMessage);
}
System.exit(0);
}
return result;
}
}
Java 应用程序的主要方法中的用法:
public static void main(String[] args) {
String[] args1 = JavaElevator.elevate(args);
if (args1.length > 0) {
// Continue as intended.
...
我知道,这是一个非常基本的实现 - 足以解决我的日常问题之一:从 Eclipse 启动提升的进程。但也许它指出了某人的方向......
我的软件出现了一个棘手的问题。我正在制作一个与另一个现有软件(游戏)交互的程序。用户报告他 运行 拥有管理员权限的游戏,在这种情况下,我的程序停止为他工作。
简短的调查表明,有些人确实需要 运行 管理员帐户下的游戏,而有些则不需要。如果我的程序能够检测到这一点并在管理员帐户下 运行ning 时警告用户,那就太好了:
如果用户单击 "Elevate",我想请 windows 提升 java.exe
运行 我的 jar
文件并调用典型的 UAC 对话框。
显然,这次的问题不是关于 java updater,而是关于 JRE
我的问题是:这可能吗? windows 可以提升我的 java.exe
实例的权限吗? java有办法吗?或者我可以使用命令行命令吗?
我想避免重新启动程序(尽管这可能不是什么大问题)。
编辑:
如果您查看评论,您会发现无法避免应用程序的重启 - 进程只能 start 提升,而不是 become 提升 .不幸的是,这有点改变了问题。基本上,它现在听起来更像是:“如何以管理员权限重新启动我的应用程序?”。当然,除非有像两个 java.exe
共享一个罐子这样的技巧...
正如评论中所指出的,遗憾的是 Java(或任何其他进程)无法在 运行ning 时提升。虽然在 JWM 的情况下,理论上可以将整个程序上下文从普通用户 java.exe 移动到提升的用户,但我认为这是不可能的。我希望有一天有人会来告诉我我错了。
令人惊讶的是,即使 restart 就位,这也是一项棘手的任务,我花了一段时间才弄明白。
非java部分
首先,我们如何 运行 从命令行提升程序? There's an answer 可见这并不简单。但是我们可以将它分解为这个 VBS 脚本:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "program name", "command line parameters", "working directory", "runas", 1
很快,结果也证明我们 .jar
文件提升。这是改进的版本,允许通过拖放 Jar 文件进行快速测试:
' 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
Java部分
Java 部分更直接。我们需要做的就是开启新的进程,并在其中执行准备好的脚本。
/**
* 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());
}
这是我的版本。它创建一个 VBScript 脚本,然后执行它。此 仅 如果正在 运行 的程序在 jar 文件中,因此您必须 运行 您的 IDE 作为管理员才能实际测试你的程序。
public static void relaunchAsAdmin() throws IOException {
relaunchAsAdmin(ThisClass.class); //Change ThisClass to the class that this method is in
}
public static void relaunchAsAdmin(Class<?> clazz) throws IOException {
if(isCurrentProcessElevated()) {
return;
}
final String dir = System.getProperty("java.io.tmpdir");
final File script = new File(dir, "relaunchAsAdmin" + System.nanoTime() +
".vbs");
try {
script.createNewFile();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(script));
osw.append("Set s=CreateObject(\"Shell.Application\")" + ln + "s.ShellExecute \"" +
System.getProperty("java.home") + "\bin\java.exe" + "\",\"-jar \"\"" +
new File(clazz.getProtectionDomain().getCodeSource(
).getLocation().toURI()).getAbsolutePath() + "\"\"\",,\"runas\",0" +
ln + "x=createObject(\"scripting.fileSystemObject\").deleteFile(" +
"WScript.scriptfullname)");
osw.close();
if(System.getenv("processor_architecture").equals("x86")) {
Runtime.getRuntime().exec("C:\Windows\System32\wscript.exe \"" +
script.getAbsolutePath() + "\"");
} else {
Runtime.getRuntime().exec("C:\Windows\SysWoW64\wscript.exe \"" +
script.getAbsolutePath() + "\"");
}
} catch(URISyntaxException e) {
e.printStackTrace();
}
Runtime.getRuntime().exit(0);
}
注意有点乱。我之前一直在使用这个方法,所以它被换行到 100 个字符(除了我为这个答案写的评论)。
isCurrentProcessElevated()
方法必须以一种或另一种方式实施。你可以尝试使用JNI,或者你可以使用纯粹的Java方法,比如写入Program Files或System32目录,看看是否失败。
显然,此解决方案仅适用于 Windows。我从来不需要在 Linux 或 Mac 系统上提升(主要是因为我没有任何 Mac 系统,而且我不使用 Linux - 我只是玩它)。
如果仍然感兴趣:在 Windows 7 我的 Java 电梯工作。当在 Java 应用程序的主要方法中使用时,它会提升 运行 Java 进程。只需添加 -elevate
作为最后一个程序参数并在 main 方法中使用电梯。
电梯class:
package test;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
/**
* Elevates a Java process to administrator rights if requested.
*/
public class JavaElevator {
/** The program argument indicating the need of being elevated */
private static final String ELEVATE_ARG = "-elevate";
/**
* If requested, elevates the Java process started with the given arguments to administrator level.
*
* @param args The Java program arguments
* @return The cleaned program arguments
*/
public static String[] elevate(String[] args) {
String[] result = args;
// Check for elevation marker.
boolean elevate = false;
if (args.length > 0) {
elevate = args[args.length - 1].equals(ELEVATE_ARG);
}
if (elevate) {
// Get the command and remove the elevation marker.
String command = System.getProperty("sun.java.command");
command = command.replace(ELEVATE_ARG, "");
// Get class path and default java home.
String classPath = System.getProperty("java.class.path");
String javaHome = System.getProperty("java.home");
String vm = javaHome + "\bin\java.exe";
// Check for alternate VM for elevation. Full path to the VM may be passed with: -Delevation.vm=...
if (System.getProperties().contains("elevation.vm")) {
vm = System.getProperty("elevation.vm");
}
String parameters = "-cp " + classPath;
parameters += " " + command;
Shell32.INSTANCE.ShellExecute(null, "runas", vm, parameters, null, 0);
int lastError = Kernel32.INSTANCE.GetLastError();
if (lastError != 0) {
String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
errorMessage += "\n vm: " + vm;
errorMessage += "\n parameters: " + parameters;
throw new IllegalStateException("Error performing elevation: " + lastError + ": " + errorMessage);
}
System.exit(0);
}
return result;
}
}
Java 应用程序的主要方法中的用法:
public static void main(String[] args) {
String[] args1 = JavaElevator.elevate(args);
if (args1.length > 0) {
// Continue as intended.
...
我知道,这是一个非常基本的实现 - 足以解决我的日常问题之一:从 Eclipse 启动提升的进程。但也许它指出了某人的方向......