我试图从我的java代码运行.mpkg应用程序:
public void runNewPkg(){ try { String command = "sudo installer -pkg Snip.mpkg -target /Applications"; Process p = Runtime.getRuntime().exec(command); System.out.println(p.getErrorStream()); } catch (Exception ex) { ex.printStackTrace(); } }
我收到以下错误,我的终端窗口挂起..
java.lang.UNIXProcess$DeferredCloseInputStream@2747ee05
Password:
Sumit-Ghoshs-iMac-3:downloads sumitghosh3$ Password:
Password:
-bash: **********: command not found
Sumit-Ghoshs-iMac-3:downloads sumitghosh3$
答案 0 :(得分:2)
您可以为sudo提供密码:
echo "p@sw0rd" | sudo -S cal -y 2011
上面的命令使用root权限运行'cal -y 2011'。
答案 1 :(得分:1)
我实际上会尝试编辑/ etc / sudoers文件以不提示输入密码。如果您使用NOPASSWD标记,您应该能够这样做。一个示例条目是:
sumitghosh3 ALL=(ALL) NOPASSWD: ALL
答案 2 :(得分:0)
如果您想要一个提升权限的交互式解决方案,我使用openscript
提升了包装shell脚本的权限。它是这样的:
import java.io.File;
import java.text.MessageFormat;
/**
* OsxExecutor.java
*/
public class OsxExecutor {
private String error = null;
private String output = null;
/**
* Privileged script template format string.
* Format Arguments:
* <ul>
* <li> 0 = command
* <li> 1 = optional with clause
* </ul>
*/
private final static String APPLESCRIPT_TEMPLATE =
"osascript -e ''try''"
+ " -e ''do shell script \"{0}\" {1}''"
+ " -e ''return \"Success\"''"
+ " -e ''on error the error_message number the error_number'' "
+ " -e ''return \"Error: \" & error_message''"
+ " -e ''end try'';";
public void executeCommand(String command, boolean withPriviledge) {
String script = MessageFormat.format(APPLESCRIPT_TEMPLATE,
command,
withPriviledge
? "with administrator privileges"
: "");
File scriptFile = null;
try {
scriptFile = createTmpScript(script);
if (scriptFile == null) {
return;
}
// run script
Process p = Runtime.getRuntime().exec(scriptFile.getAbsolutePath());
StreamReader outputReader = new StreamReader(p.getInputStream());
outputReader.start();
StreamReader errorReader = new StreamReader(p.getErrorStream());
errorReader.start();
int result = p.waitFor();
this.output = outputReader.getString();
if (result != 0) {
this.error = "Unable to run script "
+ (withPriviledge ? "with administrator privileges" : "")
+ "\n" + script + "\n"
+ "Failed with exit code: " + result
+ "\nError output: " + errorReader.getString();
return;
}
} catch (Throwable e) {
this.error = "Unable to run script:\n" + script
+ "\nScript execution "
+ (withPriviledge ? " with administrator privileges" : "")
+ " failed: " + e.getMessage();
} finally {
if (scriptFile.exists()) {
scriptFile.delete();
}
}
}
}
如果withPriviledge
标志为true,则会引发密码对话框。未显示createTmpScript()
在/tmp
中创建可执行文件,StreamReader
扩展Thread
并用于捕获stdout
和stderr
流。