Commands.page Logo

How to Set Time-Based Sudo Restrictions in Ubuntu

This guide explains how to configure time-based sudo restrictions in Ubuntu to enhance system security. You will learn how to modify the sudoers file to adjust the password timeout duration, ensuring that elevated privileges expire after a specific period of inactivity. By following these steps, administrators can reduce the risk of unauthorized access while maintaining workflow efficiency.

To implement these restrictions, you must edit the sudoers configuration file safely. Open your terminal and run the following command to launch the visual editor for sudo permissions:

sudo visudo

Using visudo is critical because it checks for syntax errors before saving, preventing you from locking yourself out of sudo access. Once the file opens, locate the line that reads Defaults env_reset. If you do not see a specific timeout setting, you can add a new line below the Defaults section.

To set the time limit, add the following configuration line:

Defaults timestamp_timeout=5

Replace 5 with the number of minutes you want sudo privileges to remain active after authentication. The default value is typically 15 minutes. Setting this to a lower number, such as 5 or 0, forces the system to request a password more frequently. A value of 0 requires a password for every single sudo command.

After adding the line, save and exit the editor. If you are using nano, press Ctrl + O to write out the file and Ctrl + X to exit. If you are using vim, type :wq and press Enter.

To verify the change, run a sudo command such as sudo ls. Enter your password when prompted. Wait for the specified number of minutes and run the command again. If the restriction is active, the terminal will request your password again instead of executing the command immediately. This confirms that the time-based restriction is successfully enforced on your Ubuntu system.