首页 > 解决方案 > 使用从脚本调用的 vim 编辑 visudo

问题描述

我创建了一个自动安装脚本,在从 chroot 执行时,我想取消注释轮组行。我可以使用它来做到这一点,sed -i "s/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g" /etc/sudoers但我读到这不是最佳做法。那么,如何用 vim 做到这一点呢?

该命令是:82 s/# //我尝试使用管道,重定向标准输入或使用 vim +“命令文件”,但前者不起作用,后者起作用但表明它是只读文件...

谢谢!

标签: bashshellvimsudoersvisudo

解决方案


一种可能性是将您的 sed 命令(不带-i标志)的输出通过管道传输到此脚本中,以在安全的情况下覆盖 sudoers 文件,而不必尝试以非交互方式运行编辑器。

#!/bin/sh

#
# Replaces /etc/sudoers with a new version supplied
# on standard input, but first performs safety checks
# including with "visudo -c"
#

sudoers=/etc/sudoers
tmp_sudoers=$sudoers.tmp  # same tmp file as used by visudo

if [ -e $tmp_sudoers ]
then
    echo "someone is editing sudoers"
    exit 1
fi

# make new version from data on stdin, preserving permissions
# by creating a copy and then overwriting it
cp $sudoers $tmp_sudoers
cat > $tmp_sudoers

# install the new version if it passes checks
succeeded=0
if [ ! -s $tmp_sudoers ]
then
    echo "replacement file is empty"
elif diff -q $sudoers $tmp_sudoers > /dev/null
then
    echo "there were no changes"
elif ! visudo -q -c -f $tmp_sudoers
then
    echo "replacement file is invalid"
else    
    mv $tmp_sudoers $sudoers
    succeeded=1
fi

if [ $succeeded -eq 0 ]
then
    rm $tmp_sudoers
    exit 1
fi

推荐阅读