Running .pkg on MAC OS from java code

后端 未结 3 1682
青春惊慌失措
青春惊慌失措 2021-01-14 23:41

Am trying to run a .mpkg application from my java code :

public void runNewPkg(){

try {

           String command = \"sudo installer -pkg Snip.mpkg -target /App         


        
3条回答
  •  独厮守ぢ
    2021-01-14 23:50

    If you want an interactive solution for elevating privilege, I have used openscript to elevate privilege of a wrapped shell script. It goes something like this:

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

    If withPriviledge flag is true, a password dialog will be raised. Not shown is createTmpScript() which creates an executable file in /tmp, and StreamReader which extends Thread and is used to capture both stdout and stderr streams.

提交回复
热议问题