[英]Java on Windows: Test if a Java application is run as an elevated process (with Administrator privileges)
[英]Run Java application as administrator on Windows
我正在用Java編寫安裝程序,因此需要提升權限才能訪問Program Files目錄。 根據我在網上找到的信息,我編寫了如下實現:
public static void main(String args[]) {
if (!checkPrivileges()) { // spawn a copy w/ elevated privileges
Runtime runtime = Runtime.getRuntime();
try {
Process p = runtime.exec(
"runas /profile /user:Administrator \"java -cp . main.Main\"");
} catch (IOException e) { ... }
} else {
// Run with elevated privileges
}
}
我用於檢查權限的測試稍微修改一下,在這里找到的答案如下所示:
private static boolean checkPrivileges() {
File testPriv = new File("C:\\Program Files\\");
if (!testPriv.canWrite()) return false;
File fileTest = null;
try {
fileTest = File.createTempFile("test", ".dll", testPriv);
} catch (IOException e) {
return false;
} finally {
if (fileTest != null)
fileTest.delete();
}
return true;
}
當我運行它時,它失敗了特權測試 - 正如預期的那樣 - 並調用exec。 通過查看p.isAlive()
檢查調用是否有效,這表明該進程實際上是活着的; 但是,我沒有看到任何新進程的證據,Windows也沒有提示我授予權限。
我不熟悉在Java中使用exec()
,所以很可能我以某種方式誤解了它的用法。 就此而言,我試圖在這里做甚么可能嗎? 如果沒有,是否有一個直接的選擇,實際上會得到我正在尋找的結果?
好的,我終於設法找到了一個我很滿意的問題的解決方案; 它有點丑陋,但它適用於我正在做的事情。
我借用了這個答案中的代碼來實現特權提升; 從那里,問題是實際上獲得使用Java的解決方案之一。 代碼最終看起來像這樣:
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
}
checkPrivileges
方法從上面保持不變, Elevator
類幾乎與鏈接解決方案中出現的相同(我剛剛取出了不需要的main
方法)。 該解決方案假設要升高的過程是一個罐子; 改變這一點以滿足您的個人需求應該不會太難。
我認為實現這一目標的最佳方法是使用microsoft為開發人員構建的工具,因為您無法在簡單的Java中實現。 在這種情況下使用清單文件http://msdn.microsoft.com/en-us/library/aa375632(v=vs.85).aspx只需構建包裝器.exe,請求此權限,然后生成您的java程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.