Execute a CMD command with administrator privileges from Java

1

For a final project, I need to create my own hotspot, using a Java application developed by me, but to execute the CMD command I need administrator privileges, but as I could do it from Java

This is the code I'm using to execute the CMD commands

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;


public class Test {


    public static void main(String[] args) {

        try {

            Process proceso = Runtime.getRuntime().exec("netsh wlan set hostednetwork mode=allow ssid=miHotspot key=12345678");
            InputStream inputstream = proceso.getInputStream();
            BufferedInputStream bf = new BufferedInputStream(inputstream);
            byte[] contents = new byte[1024];

            int bytesRead = 0;
            String cmdContent="";
            while ((bytesRead = bf.read(contents)) != -1) {                
                cmdContent += new String(contents, 0, bytesRead);
            }
            System.out.println(cmdContent);
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

}

This is the result I get when I run it

    
asked by Abisur Diaz Ramirez 05.12.2018 в 03:27
source

1 answer

0

You could create a shortcut with administrator privileges, access would be something like this:

correrá en el cmd /c Rundll32.exe Powrprof.dll,SetSuspendState

And your java code could execute the shortcut like:

Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c start \"\" \"accesoDirectoCreado.lnk\"")

To run as an administrator, check by right clicking on the shortcut - > properties > advanced > run as administrator (place the check here).

Another option would be a little simpler to implement, it will depend on your criteria to use one or the other (if your S.O is in English, place Administrator, if it is Spanish, place Administrator):

Runtime.getRuntime().exec("runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"");
    
answered by 05.12.2018 / 03:50
source