Ubuntu – How to run a sudo command needing password input in the background

command lineexecute-commandSecuritysudo

I have recently disabled sudo's authentication caching ability so that it now prompts me for a password every time.

And though this is good for security, it has caused one slight problem which I haven't been able to figure out a solution for, I am unable to run commands which go along the lines of:

sudo <command> &

In the past I would have run a sudo command before that, it would have cached my password and allowed me to run sudo commands without prompt for the next few minutes, and thus it would allow me to run the command.
But when I run it now as there is no caching before hand and as it starts a new thread immediately and sudo doesn't even prompt me for a password, I am unable to run it in this way.

So unless I run sudo -i before it I am unable to run a command in this format which is becoming rather annoying.
So I was wondering if there is any way to get around this and still run programs and commands in this way?

I am running Ubuntu GNOME 15.10 with GNOME 3.18, and specifically the program I want to run in this fashion is etherape if that makes any difference, but I would really like the solution to work for all programs and commands.

Best Answer

Instead of running sudo in the background, tell sudo to run the command in the background. From man sudo:

-b, --background
     Run the given command in the background.  Note that it is not
     possible to use shell job control to manipulate background
     processes started by sudo.  Most interactive commands will
     fail to work properly in background mode.

For example:

sudo -b sleep 10

Another way would be to just use a shell to run the command:

sudo sh -c 'sleep 10 &'

Another option would to specify a graphical program for obtaining the password, and send sudo to the background anyway:

-A, --askpass
     Normally, if sudo requires a password, it will read it from
     the user's terminal.  If the -A (askpass) option is
     specified, a (possibly graphical) helper program is executed
     to read the user's password and output the password to the
     standard output.  If the SUDO_ASKPASS environment variable is
     set, it specifies the path to the helper program.  Otherwise,
     if sudo.conf(5) contains a line specifying the askpass
     program, that value will be used.  For example:

         # Path to askpass helper program
         Path askpass /usr/X11R6/bin/ssh-askpass

     If no askpass program is available, sudo will exit with an
     error.

Askpass programs are typically used for SSH. One such is provided by the ssh-askpass-gnome package, which is installed by default, at least on Ubuntu 15.10.

SUDO_ASKPASS=/usr/bin/ssh-askpass sudo -A sleep 10 &