Run a system command as sudo from R?

I can suggest two different solutions:

  1. Use gksudo, which will prompt the user for a password in a graphical interface. Here is how it works in practice:

    system('gksudo ls')

    • PRO:

      • It is secure, you don't have to handle the password yourself.
      • ....
    • CONS:

      • it won't work without a graphical interface.
      • gksudo was installed by default with linux brands I have tried, but YMMV: maybe some users won't have it.
      • ....
  2. Ask for the user password in R, and supply it with the proper sudo options: -k to always ask for the password, and -S to accept the password from the standard input. Here is how it works in practice:

    system('sudo -kS ls',input=readline("Enter your password: "))

    • PRO:

      • It does not rely on any other program.
      • ....
    • CONS:

      • I don't like the idea that a password gets manipulated by R: it looks like a bad idea.
      • ....

Other than that, I am not aware on any way to interactively communicate with a program started from R.


Since the gksudo utility mentioned in @jealie's answer is not maintained anymore (and thus missing from Ubuntu 18.04 onwards), one has to rely on pkexec instead as described here:

system("pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY ls")

The same command using R's newer system2() function:

system2(command = "pkexec",
        args = "env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY ls",
        stdout = TRUE,
        stderr = TRUE)

To run multiple commands in sequence with only a single password prompt, combine this with sudo and bash -c '...':

system2(command = "pkexec",
        args = paste0("env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY bash -c ",
                      "'sudo mkdir somedir; sudo ls -1l; sudo rm -R somedir'"),
        stdout = TRUE,
        stderr = TRUE)

Just to build up on @Jealie's response. I believe 1. Won't work in new versions of ubuntu.

But we can let Rstudio handle the password:

system("sudo -kS ls", input = rstudioapi::askForPassword("sudo password"))

Tags:

R