Skip to content

Instantly share code, notes, and snippets.

@Kif11
Last active June 14, 2017 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kif11/b0fa87902c4544dc3ddfc34314cf78a9 to your computer and use it in GitHub Desktop.
Save Kif11/b0fa87902c4544dc3ddfc34314cf78a9 to your computer and use it in GitHub Desktop.
Safe way to append a line to your sudoers file
# This is a safe way to append a line to your sudoers file
# The validation will be performed with "visudo -c"
# before replacing the sudoers file
if [[ -z $1 ]]; then echo "No line provided to append"; return 1; fi
# Include directive to be appended to sudoers file
include_line=$1
su_bac_file="/var/tmp/sudoers.bac"
if grep -Fxq "$include_line" /etc/sudoers
then
echo "Sudoers list already contains "$include_line""
return 0
else
# Make a backup of sudo file
cp /etc/sudoers ${su_bac_file}
if [[ $? -ne 0 ]]; then return $?; fi
echo "$include_line" >> "$su_bac_file"
# Now validate sudoers.bac file for any syntax errors
echo "Validating tmp sudoers file..."
# Validate our temp sudoers file
visudo -c -q -f $su_bac_file
# Check the result of vsudo validation
if [[ $? -eq 0 ]]; then
echo "$su_bac_file is valid"
# !!! Replace sudoers file !!!
cp $su_bac_file /etc/sudoers
if [[ $? -eq 0 ]]; then
echo "Sudoers file has been replaced successfully!"
return 0;
else
echo "Failed to replace sudoers file!"
return 1
fi
else
echo "$su_bac_file did not pass visudo validation"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment