Run sudo commands in Haskell

I have ghc 6.12.3 and Ubuntu 11.04 installed on my laptop.

I would like to have a function that accepts some shell commands and executes them as superuser (e.g. sudo update-manager, sudo iwlist ....) in Haskell. I know that the System.Process module has some functions, such as createProcess, runInteractiveCommand. But there is for one raw command or one shell command, and not for compound commnads, such as "sudo update-manager". All my experiments on these functions to execute "sudo ..." have failed. The terminal that I used to run my haskell function did not respond.

I also looked at the HSH package. But it seems to me that the functions exported there are also not suitable for sudo commands.

I assume that it takes two processes to execute commands like "sudo update-manager". One for sudo and one for update-manager. Therefore, I need to call the "createProcess" functions twice and somehow bind them so that the second process for "update-manager" gets the superuser privilege from the first process for "sudo".

Thanks in advance for your help!

+8
shell haskell sudo
source share
3 answers

Try readProcess from System.Process

 readProcess :: FilePath -- command to run -> [String] -- any arguments -> String -- standard input -> IO String -- stdout 

readProcess opens an external process, reads its standard output strictly, blocking until the process is complete and returns a string.

Run it as follows:

 readProcess "/usr/bin/sudo" ("-S":someProgram) (passwort++"\n") 

Running sudo with the -S options and the program. -S need to read the password from stdin. The password must end with a newline, so the program adds it.

+12
source share

Responding to the last paragraph. sudo is a normal program, without magic. Other programs just start. So is your Haskell program. Your program starts sudo and sudo works update-manager No, you should not create two processes.

+8
source share

Have you tried System.Process.system?

 import System.Process main = system "sudo update-manager" 

This works for me (GHC 7.0.3). In addition, for scripts in Haskell in general (sudo included), you can watch the presentation Practical Haskell: scripting with types from Don Stewart.

+4
source share

All Articles