How to set the timeout for sudo asking for password?
This is not directly possible from sudo itself, but it is possible with some hackish technique.
sudo_timeout.sh :
#!/bin/bash
timeout=10 #seconds
set -m
echoerr() { echo "$@" 1>&2; }
keep_eye_on() {
pid=$1
time_passed=0
while kill -0 $pid &> /dev/null; do
sleep 1
let time_passed=time_passed+1
if [ $time_passed -ge $timeout ]; then
echoerr "Timeout reached."
kill -9 $pid
exit 1
fi
done
}
if [ -z "$1" ]; then
echoerr "Please specify a process to run!"
exit 1
fi;
sudo $@ &
pid=$!
keep_eye_on $pid &
while true; do
if kill -0 $pid &> /dev/null; then
fg sudo > /dev/null; [ $? == 1 ] && break;
else
break
fi
done
The timeout
variable holds the timeout in seconds to wait prior killing the sudo process that is asking for password.
Usage:
./sudo_timeout.sh <command>
Example:
./sudo_timeout.sh ls -al
In case the timeout is reached you get:
alex@MaD-pc:~$ ./sudo_timeout.sh ls -al
[sudo] password for alex: Timeout reached.
./sudo_timeout.sh: line 34: 14583 Killed sudo $@
In case you type in your password prior the timeout, then the command executes normally.
Disclaimer: The above is tested with simple commands like ls
and nano
, both with and without arguments, but I cannot guarantee that it will work in every case because I haven't thoroughly tested it, it's just something I came up with.
Easy using sudo's SUDO_ASKPASS feature.
Create this script sudo-askpass-timeout.sh somewhere:
#! /bin/bash -eu
# dash doesn't support read -s, so we use bash instead
# "read" will not reset the terminal echo mode if it is canceled. Let's save/restore the tty status.
stty_orig=`stty -g`
trap 'stty "$stty_orig"' EXIT
## Default timeout is 60 seconds.
if read -s -t ${READ_TIMEOUT:-60} -p "$*"
then
echo "$REPLY"
else
echo "Timeout" >&2
exit 1
fi
Then, create a something like sudo-timeout.sh in the same directory:
#! /bin/bash -eux
## Syntax: sudo-timeout.sh [-t timeout_in_seconds] <sudo arguments>
## Example: sudo-timeout.sh -t 60 apt-get update
export SUDO_ASKPASS="$(dirname "$0")/sudo-askpass-timeout.sh"
export READ_TIMEOUT=60
if [ $# -ge 3 ] && [ "$1" = "-t" ]
then
shift
READ_TIMEOUT=$1
shift
fi
exec sudo -A "$@"
Example:
sudo-timeout.sh apt-get update ##Default: 60 second timeout
sudo-timeout.sh -t 30 apt-get update
To change the timeout for the password prompt, you can edit /etc/sudoers
(or /etc/sudoers.d/passwd_timeout
) and add the line
Defaults passwd_timeout=10
or use another number than 10
.
From man sudoers
:
passwd_timeout Number of minutes before the sudo password prompt times out, or 0 for
no timeout. The timeout may include a fractional component if minute
granularity is insufficient, for example 2.5. The default is 5.