Используйте Visudo для этого с пользовательским редактором. Это решает все условия гонки и проблемы со взломом с помощью решения Брайана.
#!/bin/sh
if [ -z "$1" ]; then
echo "Starting up visudo with this script as first parameter"
export EDITOR=$0 && sudo -E visudo
else
echo "Changing sudoers"
echo "# Dummy change to sudoers" >> $1
fi
Этот скрипт добавит строку "# Dummy change to sudoers" в конец sudoers. Нет хаков и нет условий гонки.
Аннотированная версия, которая объясняет, как это на самом деле работает:
if [ -z "$1" ]; then
# When you run the script, you will run this block since $1 is empty.
echo "Starting up visudo with this script as first parameter"
# We first set this script as the EDITOR and then starts visudo.
# Visudo will now start and use THIS SCRIPT as its editor
export EDITOR=$0 && sudo -E visudo
else
# When visudo starts this script, it will provide the name of the sudoers
# file as the first parameter and $1 will be non-empty. Because of that,
# visudo will run this block.
echo "Changing sudoers"
# We change the sudoers file and then exit
echo "# Dummy change to sudoers" >> $1
fi