在Java

时间:2015-05-25 16:14:43

标签: java cmd

我正在尝试编写一个以服务名称作为参数的函数。问题是我只能在cmd(在Windows中)启动和停止服务,只有当我以管理员身份运行它时。我如何以管理员身份在java中运行cmd?你能帮我么??感谢

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";



        }   
}

我也试过这个但仍然无效

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();

0 个答案:

没有答案