Edit visudo using vim called from a script

569 Views Asked by At

I created an automated install script and while executing from the chroot I would like to uncomment the wheel group line. I could do it using sed -i "s/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g" /etc/sudoers but I read that is not the best practice. So, how to do it with vim?

The command is :82 s/# // I tried to use pipe, redirect stdin or use vim +" command file" but the former ones do not work and the latter one works but indicates that it is a readonly file...

Thank you!

1

There are 1 best solutions below

0
On

One possibility would be to pipe the output of your sed command (without the -i flag) into this script to overwrite the sudoers file if it is safe to do so, without having to try to run the editor non-interactively.

#!/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