如何在后台运行需要密码输入的sudo命令?

我最近禁用了sudo的身份validation缓存function ,现在它每次都会提示我输入密码。

虽然这对安全性有好处,但它引起了一个我无法找到解决方案的小问题,我无法运行以下命令:

 sudo  & 

在过去我会先运行一个sudo命令,它会缓存我的密码并允许我在接下来的几分钟内运行sudo命令而不提示,因此它允许我运行命令。
但是当我现在运行它时,因为它之前没有缓存,因为它立即启动一个新线程,而sudo甚至没有提示我输入密码,我无法以这种方式运行它。

因此,除非我在它之前运行sudo -i ,否则我无法以这种格式运行命令,这种格式变得相当烦人。
所以我想知道是否有办法绕过这个并仍然以这种方式运行程序和命令?

我正在使用GNOME 3.18运行Ubuntu GNOME 15.10,特别是我希望以这种方式运行的程序是etherape如果这有任何区别,但我真的希望该解决方案适用于所有程序和命令。

不要在后台运行sudo ,而是告诉sudo在后台运行命令。 来自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. 

例如:

 sudo -b sleep 10 

另一种方法是使用shell来运行命令:

 sudo sh -c 'sleep 10 &' 

另一种选择是指定用于获取密码的图形程序,并将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-askpass If no askpass program is available, sudo will exit with an error. 

Askpass程序通常用于SSH。 其中一个是由ssh-askpass-gnome软件包提供的,默认情况下安装它,至少在Ubuntu 15.10上。

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

如果你愿意在/etc/sudoers中将timestamp_timeout设置为至少0.02 (1.2秒,我会说安全为0 )(在你的情况下需要,但是使用默认设置或timestamp_timeout设置为任何东西)但是0可能只是执行以下操作),你可以在~/.bashrc设置一个像这样的别名,这不需要你在运行命令之前记住做某事,这将允许你保持对处理。:

 alias sudo='sudo -v; [ $? ] && sudo' 

这里的诀窍是分号,它将首先分别对Bash解析sudo -v ,对用户进行身份validation,并将潜在的后台部分限制为[ $? ] && sudo [ $? ] && sudo命令,它将检查sudo -v是否成功并再次运行sudo (可能背景它)以防万一。

 $ alias sudo='sudo -v; [ $? ] && sudo' $ sudo -H gedit & [sudo] password for user: [1] 19966 $ jobs [1]+ Running [ $? ] && sudo -H gedit & 

你不能。 &立即将命令发送到后台。 也就是说,在后台创建一个子shell,并在那里执行命令。 当该命令发出提示时(如sudo的情况),提示将显示在后台,您永远不会看到它。

唯一的方法是将命令带回前台,提供密码并将其发送回后台。 例如:

 $ sudo command & $ fg sudo command [sudo] password for terdon: 

现在,输入您的密码, 按Enter键 ,然后按Ctrl Z将其发送回后台并按bg告诉它继续运行。

一种更简单的方法是永远不要使用& ,而是在启动它们之后使用Ctrl Zbg手动将作业发送到后台。

最后,您可能需要考虑将sudo的密码超时设置为1或2秒。 这仍然会给你足够的安全性(除非你试图防范Flash)并允许你按预期运行这样的命令。