Java – Run command line as administrator in Java and stop windows service

administratorcommand linejavawindowswindows-services

I have java code which should stop windows service
When i try it on other commands which do not need admin permissions that works great but to stop windows service i have to start command line as administrator
I tried for example code to start notepad just for checking if this cooperation java with command line works great.

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

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

but if i try command to run command line as administrator that failed:

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

read the output from the command and put my original password to command line
when password is required (Zadejte heslo pro administrator means password required in english)

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

Why if i put my original password to command line like this it didn't works? It said Access Denied, but im sure that password is right and the next question is is there any possible way how can i do it without show my password in code?

Ohhh sry i now see ur update, but it still didn't start notepad:

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

Best Answer

You Should try this:

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

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

Hope this helps.