Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading