Home > Net >  run cmd command as administrator through java program
run cmd command as administrator through java program

Time:12-24

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

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

CodePudding user response:

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:

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. Now you're redirecting streams yourself, but you can easily let ProcessBuilder handle that for you:

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);
  •  Tags:  
  • java
  • Related