从java代码在MAC OS上运行.pkg
我试图从我的java代码运行.mpkg应用程序:
public void runNewPkg(){ 尝试{ String command =“sudo installer -pkg Snip.mpkg -target / Applications”; 进程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$
- 我想我还需要提供密码才能从命令行运行pkg你能告诉我怎么做吗?
我实际上会尝试编辑你的/ etc / sudoers文件以不提示输入密码。 如果您使用NOPASSWD标记,您应该能够这样做。 一个示例条目是:
sumitghosh3 ALL=(ALL) NOPASSWD: ALL
您可以为sudo提供密码:
echo "p@sw0rd" | sudo -S cal -y 2011
上面的命令使用root权限运行’cal -y 2011’。
如果您想要一个提升权限的交互式解决方案,我使用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: * * - 0 = command *
- 1 = optional with clause *
*/ 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
流。