我尝试运行这个 Java 应用程序:
public class Run_Process {
public static void main(String[] args) {
String myCommandIp = "netsh interface ip set address name=\"Ethernet\" static 192.168.0.4 255.255.255.0 192.168.0.1 1";
String myCommand2Dns = "netsh interface ipv4 add dnsserver \"Ethernet\" address=192.168.0.1 index=1";
runCommand(myCommandIp);
runCommand(myCommand2Dns);
}
static void runCommand(String command) {
try {
new ProcessBuilder(command.split(" ")).redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
但我得到:
The requested operation requires elevation(Run as administrator)
如何再次启动我的应用程序,并使用“run as”动词请求提升?我在 Python 中就是这样做的。但是,我需要帮助才能用 Java 完成此操作。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes, sys, subprocess
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
subprocess.call(['wmic', '/output:usracc.txt', 'useraccount', 'list', 'full', '/format:csv'])
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
这个问题已经被问过很多次了,但我需要一个具体的例子来说明我的情况,因为我是菜鸟。
我将解释为什么这不是链接问题的重复。使用快捷方式不是一种选择。我必须假设用户不知道如何创建快捷方式。 JNA
和 wizmo
解决方案没有解释。 Here它说:
So, in the Java world, you just have to do exactly what everyone else has to do: launch your app again, requesting elevation. There are several ways to launch elevated, the 'run as' verb probably being the easiest.
因此,我请求帮助如何在 Java 中使用带有“run as”动词和 ShellExecute 的解决方案。
最佳答案
好的,这就是我问题的答案。我将把它留在这里以供将来引用。首先,我从here下载了JNA 。使用 java -jar jna.jar
运行它们并导入到我的 Eclipse 项目中。
如果您在 UAC 中回答"is",则会以管理员身份打开 cmd,然后运行 netsh
命令。启动 UAC 的是 runas
。您可以使用open
以普通用户身份启动cmd。
This所以答案对我的 jna
帮助很大,a this在 ShellExecute 中传递参数也是如此。 Here您可以阅读 /S
和 /C
的作用。
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteA(WinDef.HWND hwnd,
String lpOperation,
String lpFile,
String lpParameters,
String lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
Shell32.INSTANCE.ShellExecuteA(h, "runas", "cmd.exe", "/S /C \"netsh interface ip set address name=\"Wi-Fi\" static 192.168.88.189 255.255.255.0 192.168.88.1 1\"", null, 1);
关于java - 如何在 Java 中使用 'run as' 动词请求海拔高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50292020/