简体   繁体   English

如何使用管理员权限从Java运行批处理文件?

[英]how to run a batch file from java using administrator privileges?

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

You can create a shortcut to your bat file and make it run as administrator from Properties > Advanced, 您可以创建bat文件的快捷方式,并通过“属性”>“高级”以管理员身份运行该文件,

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 现在,您已经创建了bat文件的快捷方式,可以说它的名称为example.bat并且位于C驱动器上,这意味着它的全名为c:\\\\example.bat.lnk

In order to run this shortcut, you will need to run it using ProcessBuilder, it should look like that: 为了运行此快捷方式,您将需要使用ProcessBuilder来运行它,其外观应如下所示:

ProcessBuilder pb = new ProcessBuilder("cmd", "/c","c:\\example.bat.lnk");   
Process p = pb.start();

It won't work using Runtime.getRuntime().exec(); 使用 Runtime.getRuntime().exec(); 将无法使用 Runtime.getRuntime().exec();

runas needs its main input parameter encapsulated in double quotes. runas需要将其主要输入参数封装在双引号中。 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: 更重要的是cmd.exe也会这样做 ,如果您要向其传递带空格的命令字符串,那么您将必须使用转义字符使其在Windows命令提示符下工作:

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: 然后,您将不得不再次转义整个字符串以使其在Java代码中起作用:

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. 有时在带有嵌套cmd调用的runas中,不必转义反斜杠\\字符,因此,如果失败,则可能需要尝试将两个反斜杠的序列替换为两个。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM