通过UAC提升ProcessBuilder进程的权限?

16

我正在尝试运行一个外部可执行文件,但显然需要提升权限。这是代码,改编自使用ProcessBuilder的示例(因此数组只有一个参数):

    public static void main(String[] args) throws IOException {
        File demo = new File("C:\\xyzwsdemo");
        if(!demo.exists()) demo.mkdirs();
        String[] command = {"C:\\fakepath\\bsdiff4.3-win32\\bspatch.exe"};
        ProcessBuilder pb = new ProcessBuilder( command );
        Process process = pb.start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running %s is:\n", Arrays.toString(command));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        try {
            int exitValue = process.waitFor();
            System.out.println("\n\nExit Value is " + exitValue);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

运行时它返回这个结果:

Exception in thread "main" java.io.IOException: Cannot run program "C:\Users\Gilliane\Downloads\bsdiff4.3-win32\bspatch.exe": CreateProcess error=740, The requested operation requires elevation

我已经浏览了一些内容,并知道在C#中,可以通过以下方式请求提升权限(如此线程所示):

startInfo.Verb = "runas";

但是,使用ProcessBuilder看不到类似的选项。另一种方法是在目标系统上安装Elevation Tools并使用ProcessBuilder调用“提升”提示。然而,我不想强制使用我的程序的人也安装这些提升工具。

还有其他方法吗?

2个回答

15

使用ProcessBuilder无法完成此操作,您需要调用Windows API。

我已经使用JNA并使用类似以下代码的方式实现了这一点:

Shell32X.java:

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.Shell32;
import com.sun.jna.platform.win32.WinDef.HINSTANCE;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.win32.W32APIOptions;

public interface Shell32X extends Shell32
{
    Shell32X INSTANCE = (Shell32X)Native.loadLibrary("shell32", Shell32X.class, W32APIOptions.UNICODE_OPTIONS);

    int SW_HIDE = 0;
    int SW_MAXIMIZE = 3;
    int SW_MINIMIZE = 6;
    int SW_RESTORE = 9;
    int SW_SHOW = 5;
    int SW_SHOWDEFAULT = 10;
    int SW_SHOWMAXIMIZED = 3;
    int SW_SHOWMINIMIZED = 2;
    int SW_SHOWMINNOACTIVE = 7;
    int SW_SHOWNA = 8;
    int SW_SHOWNOACTIVATE = 4;
    int SW_SHOWNORMAL = 1;

    /** File not found. */
    int SE_ERR_FNF = 2;

    /** Path not found. */
    int SE_ERR_PNF = 3;

    /** Access denied. */
    int SE_ERR_ACCESSDENIED = 5;

    /** Out of memory. */
    int SE_ERR_OOM = 8;

    /** DLL not found. */
    int SE_ERR_DLLNOTFOUND = 32;

    /** Cannot share an open file. */
    int SE_ERR_SHARE = 26;



    int SEE_MASK_NOCLOSEPROCESS = 0x00000040;


    int ShellExecute(int i, String lpVerb, String lpFile, String lpParameters, String lpDirectory, int nShow);
    boolean ShellExecuteEx(SHELLEXECUTEINFO lpExecInfo);



    public static class SHELLEXECUTEINFO extends Structure
    {
        /*
  DWORD     cbSize;
  ULONG     fMask;
  HWND      hwnd;
  LPCTSTR   lpVerb;
  LPCTSTR   lpFile;
  LPCTSTR   lpParameters;
  LPCTSTR   lpDirectory;
  int       nShow;
  HINSTANCE hInstApp;
  LPVOID    lpIDList;
  LPCTSTR   lpClass;
  HKEY      hkeyClass;
  DWORD     dwHotKey;
  union {
    HANDLE hIcon;
    HANDLE hMonitor;
  } DUMMYUNIONNAME;
  HANDLE    hProcess;
         */

        public int cbSize = size();
        public int fMask;
        public HWND hwnd;
        public WString lpVerb;
        public WString lpFile;
        public WString lpParameters;
        public WString lpDirectory;
        public int nShow;
        public HINSTANCE hInstApp;
        public Pointer lpIDList;
        public WString lpClass;
        public HKEY hKeyClass;
        public int dwHotKey;

        /*
         * Actually:
         * union {
         *  HANDLE hIcon;
         *  HANDLE hMonitor;
         * } DUMMYUNIONNAME;
         */
        public HANDLE hMonitor;
        public HANDLE hProcess;

        protected List getFieldOrder() {
            return Arrays.asList(new String[] {
                "cbSize", "fMask", "hwnd", "lpVerb", "lpFile", "lpParameters",
                "lpDirectory", "nShow", "hInstApp", "lpIDList", "lpClass",
                "hKeyClass", "dwHotKey", "hMonitor", "hProcess",
            });
        }
    }

}

Elevator.java:

package test;

import test.Shell32X.SHELLEXECUTEINFO;

import com.sun.jna.WString;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;

public class Elevator
{
    public static void main(String... args)
    {
        executeAsAdministrator("c:\\windows\\system32\\notepad.exe", "");
    }

    public static void executeAsAdministrator(String command, String args)
    {
        Shell32X.SHELLEXECUTEINFO execInfo = new Shell32X.SHELLEXECUTEINFO();
        execInfo.lpFile = new WString(command);
        if (args != null)
            execInfo.lpParameters = new WString(args);
        execInfo.nShow = Shell32X.SW_SHOWDEFAULT;
        execInfo.fMask = Shell32X.SEE_MASK_NOCLOSEPROCESS;
        execInfo.lpVerb = new WString("runas");
        boolean result = Shell32X.INSTANCE.ShellExecuteEx(execInfo);

        if (!result)
        {
            int lastError = Kernel32.INSTANCE.GetLastError();
            String errorMessage = Kernel32Util.formatMessageFromLastErrorCode(lastError);
            throw new RuntimeException("Error performing elevation: " + lastError + ": " + errorMessage + " (apperror=" + execInfo.hInstApp + ")");
        }
    }
}

谢谢快速回复!我会在我的应用程序范围内测试这个,然后告诉你它的效果如何。 - Kitty Kymaera
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Affi
我一开始有些犹豫尝试这个,因为我不太懂代码,但它完美地运行了。谢谢你的分享! - 1813222
@user1813222 你做了什么?我收到了一个classDefFound错误。 - Jan
这不是ProcessBuilder的替代品,因为它没有考虑工作目录... - marcolopes
@marcolopes 工作目录可以通过 SHELLEXECUTEINFO 的 lpDirectory 参数进行设置。 - prunge

0

Prunge的答案对我来说很好用。但是在做了更多的研究后,我发现了另一种使用VB脚本和批处理文件的方法。我更喜欢这种方法,因为使用VB脚本不会在每次打开我的应用程序时弹出黑色cmd窗口。

  1. 创建一个普通的批处理文件来打开外部可执行文件。 我将要打开一个MySQL服务器可执行文件

    @echo off
    cd "C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin"
    :: 标题不需要:
    start /MIN  mysqld.exe
    exit
    
  2. 将其保存为mysql.bat

  3. 现在创建一个带有管理员权限的VB脚本,并在结尾处添加脚本以打开mysql.bat文件。

最后,CreateObject("Wscript.Shell").Run 运行了名为 mysql.bat 的批处理文件。
Set WshShell = WScript.CreateObject("WScript.Shell")'
 If WScript.Arguments.length = 0 Then
    Set ObjShell = CreateObject("Shell.Application")
    ObjShell.ShellExecute "wscript.exe", """" & _
    WScript.ScriptFullName & """" &_
    " RunAsAdministrator", , "runas", 1
    Wscript.Quit
    End if
    CreateObject("Wscript.Shell").Run "C:\Users\Shersha\Documents\NetBeansProjects\Berries\batch\mysql.bat",0,True
  1. 现在将此文件保存为mysql_start.vbs
  2. 最后从Java运行VB脚本。

就这样了。

 try {
    Runtime.getRuntime().exec("wscript C:\\\\Users\\\\Shersha\\\\Documents\\\\NetBeansProjects\\\\Berries\\\\batch\\\\mysql_start.vbs");
        } catch (IOException e) {
                            System.out.println(e);
                            System.exit(0);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接