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.