You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.4 KiB
54 lines
1.4 KiB
1 year ago
|
#!/bin/sh
|
||
|
|
||
|
# Warning if run with sudo
|
||
|
if [ "$EUID" -eq 0 ]; then
|
||
|
echo "Please do not run this script with sudo. Exiting."
|
||
|
exit 1
|
||
|
fi
|
||
|
|
||
|
# Command or file path provided as an argument
|
||
|
COMMAND_OR_FILE="$1"
|
||
|
|
||
|
# Get the specified username or default to the current user
|
||
|
USERNAME="${2:-$(whoami)}"
|
||
|
|
||
|
# Temporary file for sudoers
|
||
|
TMP_FILE="/tmp/sudoers.tmp"
|
||
|
|
||
|
# Determine if the input is a file or command name
|
||
|
if [ -f "$COMMAND_OR_FILE" ]; then
|
||
|
# Convert to absolute path if it's a file
|
||
|
PATH_TO_ALLOW="$(realpath "$COMMAND_OR_FILE")"
|
||
|
else
|
||
|
# Use 'which' to find the command path if it's a command name
|
||
|
PATH_TO_ALLOW="$(which "$COMMAND_OR_FILE")"
|
||
|
fi
|
||
|
|
||
|
# Check if the path was determined
|
||
|
if [ -z "$PATH_TO_ALLOW" ]; then
|
||
|
echo "File or command not found."
|
||
|
exit 1
|
||
|
fi
|
||
|
|
||
|
# Make a temporary copy of the sudoers file using sudo
|
||
|
sudo cp /etc/sudoers $TMP_FILE
|
||
|
|
||
|
# Check if the entry already exists
|
||
|
if ! sudo grep -q "$USERNAME ALL=(ALL) NOPASSWD: $PATH_TO_ALLOW" $TMP_FILE; then
|
||
|
# Add the new rule if it doesn't exist
|
||
|
echo "$USERNAME ALL=(ALL) NOPASSWD: $PATH_TO_ALLOW" | sudo tee -a $TMP_FILE > /dev/null
|
||
|
fi
|
||
|
|
||
|
# Validate the new sudoers file using sudo
|
||
|
sudo visudo -cf $TMP_FILE
|
||
|
|
||
|
# If validation succeeds, overwrite the sudoers file using sudo
|
||
|
if [ $? -eq 0 ]; then
|
||
|
sudo cp $TMP_FILE /etc/sudoers
|
||
|
echo "Sudoers file updated successfully."
|
||
|
else
|
||
|
echo "Error in sudoers file. Not updated."
|
||
|
fi
|
||
|
|
||
|
# Remove the temporary file using sudo
|
||
|
sudo rm -f $TMP_FILE
|