Reputation: 160
how to run a batch file from java using administrator privileges?
I am trying to do this.But code is not working.
String cmd = "runas /profile /user:Administrator /cmd.exe /C certutil -addstore ROOT E:\\WORK\\UI\\DesktopRecorder\\userdata\\certgen\\X509CA\\ca\\new_ca.crt";
Runtime run = Runtime.getRuntime();
Process process = run.exec(cmd);
Upvotes: 1
Views: 5628
Reputation: 61
You can create a shortcut to your bat file and make it run as administrator from Properties > Advanced,
Now that you created a shortcut to your bat file lets say its name is example.bat
and its located on C drive, so it means that its full name is c:\\example.bat.lnk
In order to run this shortcut, you will need to run it using ProcessBuilder, it should look like that:
ProcessBuilder pb = new ProcessBuilder("cmd", "/c","c:\\example.bat.lnk");
Process p = pb.start();
It won't work using Runtime.getRuntime().exec();
Upvotes: 2
Reputation: 26
runas needs its main input parameter encapsulated in double quotes. The kicker is that cmd.exe does too, if you are passing it a command string with spaces, so you will have to use escape characters for it to work on the windows command prompt:
runas /profile /user:Administrator "cmd.exe /C \"certutil -addstore ROOT E:\\WORK\\UI\\DesktopRecorder\\userdata\\certgen\\X509CA\\ca\\new_ca.crt\""
You would then have to escape that entire string again for it to work in your java code:
String cmd = "runas /profile /user:Administrator \"cmd.exe /C \\\"certutil -addstore ROOT E:\\\\WORK\\\\UI\\\\DesktopRecorder\\\\userdata\\\\certgen\\\\X509CA\\\\ca\\\\new_ca.crt\\\"\"";
Sometimes in runas with a nested cmd call, you don't have to escape the backslash \ characters, so if that fails, you may want to try replacing the sequences of four backslashes with two. Good luck!
Upvotes: 0