什么是SUDO_ASKPASS
你是否遇到过这种场景,需要通过某个程序调用linux命令,如果命令中存在sudo,那么程序将无法执行,因为sudo命令需要等待输入密码才能继续执行。SUDO_ASKPASS就可以解决这个问题,设置了SUDO_ASKPASS后,不需要在输入密码,就可以执行sudo命令。
什么是SUDO_ASKPASS?
SUDO_ASKPASS可以理解为提供密码的可执行文件,关于SUDO_ASKPASS的解释,可以参考man sudo
-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-askpassIf no askpass program is available, sudo will exit with an error.
如何设置SUDO_ASKPASS
设置pwd.sh脚本
mkdir bin;vim ~/bin/pwd.sh
里面存储你的密码
#!/bin/bash
echo '密码'
将文件设置为可执行文件
chmod +x ~/bin/pwd.sh
在自己的执行环境中加载环境变量
vim ~/.bashrc
export SUDO_ASKPASS=~/bin/pwd.sh
执行sudo脚本
基本的配置已经完成了,现在要切换到root用户,可以执行如下命令
sudo -i -A
成功!