- 10 Oct 2024
- 2 Minutes to read
- Print
- PDF
Temporary Sudo access for specific user
- Updated on 10 Oct 2024
- 2 Minutes to read
- Print
- PDF
Use this script to give temporary Sudo access to specific user on Linux machines.
Copy and save the contents below to a UTF-8 editor like notepad++ OR Sublime Text in Windows or gedit in Ubuntu.
If you are using notepad++ then use the bottom right panel to change the type to Unix (LF).
Or click here to download the file.
#!/bin/bash # Set the username USERNAME="ENTER_USER_NAME" # Check if the user exists if id "$USERNAME" &>/dev/null; then # Check if the user is in an active session if who | grep -wq "$USERNAME"; then # Note: Unsaved data may be lost or may result in data corruption # Log out the user if in an active session pkill -KILL -u "$USERNAME" echo "User $USERNAME logged out." fi # Add the user to the sudo group sudo usermod -aG sudo "$USERNAME" echo "User $USERNAME added to the sudo group." # Detect the user's timezone USER_TIMEZONE=$(sudo -u "$USERNAME" timedatectl | grep "Time zone" | awk '{print $3}') # Print the current timestamp based on the user's timezone echo "Current timestamp in $USER_TIMEZONE: $(sudo -u "$USERNAME" date)" # Schedule the removal of sudo access after X minutes using sleep (sleep ENTER_SECONDS && sudo gpasswd -d "$USERNAME" sudo && echo "Removed sudo access for $USERNAME." && pkill -KILL -u "$USERNAME") & echo "Scheduled removal of sudo access in X minutes, and user will be logged out." # Print the current timestamp based on the user's timezone echo "Current timestamp in $USER_TIMEZONE: $(sudo -u "$USERNAME" date)" else echo "User $USERNAME not found." fi exit 0
In the script, replace the following placeholder:
Provide the username in the line:
USERNAME="ENTER_USER_NAME"Provide the time in seconds in the line:
sleep ENTER_SECONDS &&On executing the script, the user will get logged out automatically from ongoing session and once they log in, they will become sudo.
After XX minutes (that is the time specified in the script) user will again get logged out automatically and again login back will make them Standard user.
The users will need to perform the logout-login action to ensure that the sudo group setting is updated.
The script also includes a command to auto detect the Time zone i.e. when the user was logged out - followed by at what time they became sudo user, followed by the time the user will be a sudo user.
The script will also revert back with a message if the mentioned user is not present.
Follow our guide to upload & publish the script using Scalefusion Dashboard.
Note:
Some of the scripts and their contents are sourced from internet and yes, our new friend ChatGPT.
Please validate the scripts on a test machine before deploying them on all your managed devices.
Scalefusion has tested these scripts, however Scalefusion will not be responsible for any loss of data or system malfunction that may arise due to the usage of these scripts.