1

I'm trying to write a function that has the name of a service as parameter. The problem is that i can only start and stop a service in cmd ( in windows) only if i run it as administrator. How can i run cmd in java as administrator? Can you please help me?? Thanks

public String stop(String name) {
    try {
        List<String> command = new ArrayList<String>();

        command.add("cmd.exe");
                    command.add("/c");
                    command.add("runas");
                    command.add("/user:Administrator");
                    command.add("\"net");
            command.add("stop");
                    command.add(name + "\"");
        System.out.println(command);
        Process servicesProcess = new ProcessBuilder(command).start();
        InputStream input = servicesProcess.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        StringBuffer queryResult = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            queryResult.append(line);
        }
        reader.close();
        servicesProcess.destroy();
        System.out.println(queryResult.toString());
        if (queryResult.toString().toLowerCase().contains("failed") || queryResult.toString().toLowerCase().contains("error")) {
            return "Failed @stop";
        }
        System.out.println("Stop service completed succesfully!");
        return "Succes @stop";
    } catch (IOException e) {
        return "Failed @stop";



        }   
}

I also tried with this and still doesn't work

List<String> command = new ArrayList<String>();

        command.add("cmd.exe");
        command.add("/c");
                    command.add("Powrprof.dll");
                    command.add(",");
                    command.add("SetSuspendState");

        command.add("net");
        command.add("stop");

        command.add(name);


        System.out.println(command);
        Process servicesProcess = new ProcessBuilder(command).start();
Yolanda
  • 11
  • 2

0 Answers0