How can you restrict the execution of a one-time command by a user with sudo privileges?
sobes.tech AI
Answer from AI
There are several ways to restrict a privileged user with sudo from executing a command only once:
-
Sudoers configuration: In the
/etc/sudoersfile, you can explicitly specify which commands are allowed for the user, and use theNOEXECoption to prevent the execution of child processes. -
Wrapper scripts: Instead of directly calling the command via sudo, create a script that checks whether the command has already been executed (for example, by creating a flag in the filesystem).
-
Limiting via PAM or external tools: You can set restrictions at the PAM level or use access control systems.
Example of sudoers configuration to allow only one command:
username ALL=(ALL) NOPASSWD: /usr/bin/command
To restrict execution to only once, the script can check for the presence of a flag file and refuse to run again.
Simple wrapper script example:
#!/bin/bash
FLAGFILE="/var/run/command_executed.flag"
if [ -f "$FLAGFILE" ]; then
echo "The command has already been executed."
exit 1
else
touch "$FLAGFILE"
/usr/bin/command "$@"
fi
This way, the user can execute the command only once until the flag file is removed.