例如,如果我运行sudo apt-get install vlc
,它会要求我输入sudo
密码。
如果我不输入密码,sudo
它会[sudo] password for avinash:
保留很长时间。
我如何设置这个 sudo 密码等待时间?如果这个等待时间到期,它会自动显示time expires
。这可能吗?
注意:我不是问能sudo
记住密码多长时间(RootSudoTimeout - 社区 Ubuntu 文档)。
要更改密码提示的超时,您可以编辑/etc/sudoers
(或/etc/sudoers.d/passwd_timeout
)并添加以下行
Defaults passwd_timeout=10
Run Code Online (Sandbox Code Playgroud)
或使用 以外的其他号码10
。
从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.
Run Code Online (Sandbox Code Playgroud)
这不能直接从 sudo 本身实现,但可以通过一些 hackish 技术实现。
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
Run Code Online (Sandbox Code Playgroud)
该timeout
变量保存在终止要求密码的 sudo 进程之前等待的超时时间(以秒为单位)。
用法:
./sudo_timeout.sh <command>
Run Code Online (Sandbox Code Playgroud)
例子:
./sudo_timeout.sh ls -al
Run Code Online (Sandbox Code Playgroud)
如果达到超时,您将得到:
alex@MaD-pc:~$ ./sudo_timeout.sh ls -al
[sudo] password for alex: Timeout reached.
./sudo_timeout.sh: line 34: 14583 Killed sudo $@
Run Code Online (Sandbox Code Playgroud)
如果您在超时之前输入密码,则该命令将正常执行。
免责声明:上面的内容是使用像ls
and这样的简单命令nano
(带参数和不带参数)进行测试的,但我不能保证它在每种情况下都有效,因为我还没有彻底测试它,这只是我想出的东西。