30 security command-line sudo execute-command
我最近禁用了sudo的身份验证缓存功能,因此它现在每次都提示我输入密码。
虽然这对安全性有好处,但它导致了一个我无法找到解决方案的小问题,我无法运行以下命令:
sudo <command> &
Run Code Online (Sandbox Code Playgroud)
在过去,我会在此sudo之前运行一个命令,它会缓存我的密码并允许我sudo在接下来的几分钟内不提示地运行命令,因此它允许我运行该命令。
但是当我现在运行它时,因为事先没有缓存并且它立即启动一个新线程并且sudo甚至不提示我输入密码,我无法以这种方式运行它。
因此,除非我sudo -i在它之前运行,否则我无法以这种格式运行命令,这变得相当烦人。
所以我想知道是否有任何方法可以解决这个问题并仍然以这种方式运行程序和命令?
我正在使用 GNOME 3.18 运行 Ubuntu GNOME 15.10,特别是我想以这种方式运行的程序etherape是否有任何不同,但我真的希望该解决方案适用于所有程序和命令。
mur*_*uru 58
不要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.
Run Code Online (Sandbox Code Playgroud)
例如:
sudo -b sleep 10
Run Code Online (Sandbox Code Playgroud)
另一种方法是仅使用 shell 来运行命令:
sudo sh -c 'sleep 10 &'
Run Code Online (Sandbox Code Playgroud)
另一种选择是指定一个图形程序来获取密码,然后发送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.
Run Code Online (Sandbox Code Playgroud)
Askpass 程序通常用于 SSH。ssh-askpass-gnome至少在 Ubuntu 15.10 上,默认情况下安装的包提供了这样的一个。
SUDO_ASKPASS=/usr/bin/ssh-askpass sudo -A sleep 10 &
Run Code Online (Sandbox Code Playgroud)
kos*_*kos 11
如果您愿意timestamp_timeout至少设置为0.02(1.2 秒,我会说与0) in一样安全/etc/sudoers(在您的情况下需要,但使用默认设置或timestamp_timeout设置为除0一个之外的任何内容都可以执行以下操作) ,你可以在 中设置一个像这样的别名~/.bashrc,它不需要你在运行命令之前记住做一些事情,这将允许你保持对进程的控制。:
alias sudo='sudo -v; [ $? ] && sudo'
Run Code Online (Sandbox Code Playgroud)
这里的技巧是分号,它将使 Bashsudo -v首先单独解析,对用户进行身份验证,并将潜在的后台部分限制为[ $? ] && sudo命令,它将检查是否sudo -v成功并sudo再次运行(可能对其进行后台运行)以防万一。
$ alias sudo='sudo -v; [ $? ] && sudo'
$ sudo -H gedit &
[sudo] password for user:
[1] 19966
$ jobs
[1]+ Running [ $? ] && sudo -H gedit &
Run Code Online (Sandbox Code Playgroud)
你不能。的&立即发送命令到背景中。也就是说,在后台创建了一个子shell,并在那里执行命令。当该命令发出提示时,就像 的情况一样sudo,提示会显示在后台并且您永远不会看到它。
解决这个问题的唯一方法是将命令带回前台,提供密码并将其发送回后台。例如:
$ sudo command &
$ fg
sudo command
[sudo] password for terdon:
Run Code Online (Sandbox Code Playgroud)
现在,输入您的密码,点击Enter然后点击CtrlZ将其发送回后台并bg告诉它继续运行。
一个简单的方法是永远不要使用&带有手动,取而代之的,将作业发送到后台CtrlZ,并bg发动他们之后。
最后,您可能需要考虑将 sudo 的密码超时设置为 1 或 2 秒。这仍然会为您提供足够的安全性(除非您试图防范 Flash)并允许您按预期运行类似的命令。