Am trying to run a .mpkg application from my java code :
public void runNewPkg(){ try { String command = \"sudo installer -pkg Snip.mpkg -target /App
You can provide the password to sudo:
echo "p@sw0rd" | sudo -S cal -y 2011
The command above runs 'cal -y 2011' with root permissions.
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:
* <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();
}
}
}
}
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.
I would actually try editing your /etc/sudoers file to not prompt for a password. If you use the NOPASSWD tag, you should be able to do that. An example entry would be:
sumitghosh3 ALL=(ALL) NOPASSWD: ALL