简体   繁体   English

通过 java 程序以管理员身份运行 cmd 命令

[英]run cmd command as administrator through java program

I need to build a java program to reset.network in windows 10, this command needs cmd to be opened as administrator I tried to build it, but it gives me this error我需要在 windows 10 中构建一个 java 程序来 reset.network,此命令需要 cmd 以管理员身份打开我尝试构建它,但它给了我这个错误

Cannot run program "runas /profile /user:Administrator "cmd.exe /c Powrprof.dll,SetSuspendState"": CreateProcess error=2, The system cannot find the file specified

this is my code这是我的代码

try {
            String[] command
                    = {
                        "runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"",};
            Process p = Runtime.getRuntime().exec(command);
            new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
            new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
            PrintWriter stdin = new PrintWriter(p.getOutputStream());
            stdin.println("netsh winsock reset");
            stdin.close();
            int returnCode = p.waitFor();
            System.out.println("Return code = " + returnCode);

            stat_lbl.setText("Network reset Successfully");

        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }

I don't understand what the problem is and how can I resolve it我不明白问题是什么以及如何解决

You're giving the command as an array with a single element, which is treated as a single command.您将命令作为具有单个元素的数组提供,该元素被视为单个命令。 You're already giving the command as an array - split it accordingly, where runas is the command, and everything else is an argument to runas :您已经将命令作为数组给出 - 相应地拆分它,其中runas是命令,其他所有内容都是runas的参数:

String[] command = {
        "runas",
        "/profile",
        "/user:Administrator",
        "cmd.exe /c Powrprof.dll,SetSuspendState",
};

Note that you don't have to add quotes to the last argument.请注意,您不必为最后一个参数添加引号。

You can make your program a bit better by using ProcessBuilder .您可以使用ProcessBuilder使您的程序更好一些。 Now you're redirecting streams yourself, but you can easily let ProcessBuilder handle that for you:现在您要自己重定向流,但您可以轻松地让ProcessBuilder为您处理:

Process p = new ProcessBuilder(command).inheritIO().start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM