javasudoruntime.execumountgksudo

Sudo in Java's Runtime.exec & gksu for umount


I am writing a Java application in which (among other stuff) I'd mount a external device, do some copying, and then unmount it.

//I am mounting several devices in created dirs named sdb, sdc... according to the partitions
String[] command = {"gksu", "mount", "/dev/sd" + letter + "1", "mounter/sd" + letter};
Runtime.getRuntime().exec(command);

This works fine both in the terminal and in my program.

To unmount faster, I thought about using umount -a but gksu umount -a doesn't work in the terminal and consequently not in the Java program. sudo umount -a does work in the terminal, but not in the application. Meanwhile, I got it to work by unmounting the devices 1 by 1, but it would be cleaner if I could get umount -a to work someway.

If you understand why either gksu doesn't work with umount or sudo with Runtime.exec(), I'd take your explanation.

Thanks


Solution

  • I feel the problem is sudo not asking me for a password, as gksu does. But I don't know how to give it a password.

    This is very likely the case. There are a couple of different possible situations here, and each I think has it's own solution:

    1. The user running the program (in the case of a desktop app) already has privileges to run the commands you need. - Prompt the user to enter their password and pass it to sudo through stdin using the -s flag. Check out the sudo man page for more. This is simple and ensures that your application doesn't have greater access than the user running it.

    2. If your application needs to run with different privileges than the user has, or if this is running on a server, then the application should be run as it's own System User. You can then use visudo to give that system user the ability to run ONLY the commands you need without requiring a password. Just be very cautious about editing the sudoers file. I recommend adding it as a separate file and just linking to it in the actual sudoers so that it's easier to undo later.