在Java中以管理员身份运行命令行并停止Windows服务

时间:2014-07-19 09:59:25

标签: java windows command-line windows-services administrator

我有java代码应该停止Windows服务 当我尝试其他命令,不需要管理员权限,但是要停止Windows服务,我必须以管理员身份启动命令行 我尝试使用示例代码来启动记事本,只是为了检查这个与命令行的java合作是否很有效。

String[] start = {"cmd.exe", "/c", "start", "notepad"};                              

Process runtimeProcess = Runtime.getRuntime().exec(start);
int processComplete = runtimeProcess.waitFor();

但是如果我尝试命令以失败的管理员身份运行命令行:

String[]  startAsAdmin= new String [] {
"CMD.EXE",
"/C",
"RUNAS /profile /user:"
+ "administrator"
+ " ", "start", "notepad"};

Process runtimeProcess = Runtime.getRuntime().exec(startAsAdmin);
runtimeProcess.waitFor();

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(runtimeProcess.getInputStream()));

BufferedReader stdError = new BufferedReader(new
InputStreamReader(runtimeProcess.getErrorStream()));

BufferedWriter stdOutput = new BufferedWriter(new
OutputStreamWriter(runtimeProcess.getOutputStream()));

读取命令的输出并将我的原始密码放到命令行 当需要密码时(Zadejte heslo专业管理员意味着英文要求的密码)

System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
    if (s.startsWith("Zadejte heslo pro administrator:")) {
        stdOutput.append("password").flush();
    }
}

为什么我把我的原始密码放到这样的命令行上它不起作用?它说访问拒绝,但我确定密码是正确的,下一个问题是有什么可能的方法我怎么能这样做而不在代码中显示我的密码?

哦,我现在看到你的更新,但它仍然没有启动记事本:

String[] startAsAdmin= new String [] {
"CMD.EXE",
"/C",
"echo password123 | RUNAS /profile /user:"
+ "administrator"
+ " ", "start", "notepad"};

Process runtimeProcess = Runtime.getRuntime().exec(startAsAdmin);
int processComplete = runtimeProcess.waitFor();

1 个答案:

答案 0 :(得分:1)

你应该试试这个:

String[]  stopAdmin= new String [] {
    "CMD.EXE",
    "/C",
    "echo password123 | RUNAS /profile /user:"
    + "administrator"
    + " ", "net", "stop", Service_Name};

Process runtimeProcess = Runtime.getRuntime().exec(stopAdmin);

希望这有帮助。