recherche
MaisonTutoriel systèmeLinuxComment restreindre les utilisateurs de Sudo à exécuter des commandes autorisées spécifiques dans Linux

The sudo command allows users to run commands with root privileges. This can be a powerful tool, but it can also be a security risk if not used carefully. One way to mitigate this risk is to allow sudo users to run particular authorized commands. In this guide, we will show you how to restrict sudo users to run specific commands with sudo privileges in Linux. We will also show you how to revert sudoers file back to the original configuration.

Table of Contents

Restrict Sudo Users to Run Authorized Commands

To restrict sudo users to ONLY run authorized commands, you can use the sudoers configuration file. On most Linux distributions, the sudoers file is located at /etc/sudoers file or /etc/sudoers.d/ directory.

Heads Up: Before making changes to the sudoers file, it's crucial to use caution, as incorrect configurations can lead to system issues. Always use the visudo command to edit the sudoers file, as it performs syntax checks before saving changes.

Here's how you can restrict sudo users to run specific commands:

1. It's highly recommended to backup the sudoers file before making any changes or edits to it. To backup sudoers file, run:

$ sudo cp /etc/sudoers /etc/sudoers.bak

By backing up the sudoers file, you can easily revert to a known-working configuration if errors occur during editing or in case of security incidents.

2. Open the sudoers file for editing using visudo command:

$ sudo visudo

3. Scroll down to the line where it says:

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

The above line means that members of the "sudo" group are allowed to execute any command with sudo privileges on any host and as any user or group. Essentially, it grants full sudo access to the users in the "sudo" group.

4. To allow the sudo users to execute only a specific command, for example apt, modify the line as shown below.

%sudo   ALL=(ALL:ALL) /bin/apt

Comment restreindre les utilisateurs de Sudo à exécuter des commandes autorisées spécifiques dans Linux

You can also specify multiple allowed commands for a user by separating them with commas:

%sudo   ALL=(ALL:ALL) /path/to/allowed/command1,/path/to/allowed/command2

5. If you want to allow the user to run the allowed commands without entering a password, you can append NOPASSWD: before the command path. However, be cautious when using this option, as it might reduce the security of your system.

%sudo  ALL=(ALL)  NOPASSWD: /path/to/allowed/command

6. Once you've made the necessary changes, save and close the sudoers file.

7. Verify the syntax of your sudoers file before exiting visudo. If there are any syntax errors, visudo will prompt you to correct them.

After following these steps, all the members of the sudo group will only be able to execute the allowed commands with sudo privileges. Running all other commands with sudo privilege will be denied, even if the user is a member of sudo group.

Let us verify it by running the cat command with sudo privilege.

$ sudo cat /etc/sudoers

Sample Output:

[sudo] password for ostechnix: 
Sorry, user ostechnix is not allowed to execute '/usr/bin/cat /etc/sudoers' as root on debian12.ostechnix.lan.

Comment restreindre les utilisateurs de Sudo à exécuter des commandes autorisées spécifiques dans Linux

Even though, the user 'ostechnix' is a member of sudo group, he can't run sudo cat /etc/sudoers command. Because, we restricted him to run only the apt command with sudo privilege.

Let us list all of the commands that the user ostechnix is allowed to run with sudo privileges.

$ sudo -lU ostechnix
[sudo] password for ostechnix: 
Matching Defaults entries for ostechnix on debian12:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin, use_pty

User ostechnix may run the following commands on debian12:
    <strong><mark>(ALL : ALL) /bin/apt</mark></strong>

Comment restreindre les utilisateurs de Sudo à exécuter des commandes autorisées spécifiques dans Linux

As you can see in the above output, the user ostechnix can run only apt command with sudo privilege.

Let us check if he can able to the apt command with sudo privilege.

$ sudo apt update

Comment restreindre les utilisateurs de Sudo à exécuter des commandes autorisées spécifiques dans Linux

Yes, he has no problem on running the allowed command, which is apt in this case, with sudo rights. The user can also run all the sub-commands of apt, for example apt upgrade, apt full-upgrade etc.

Please note that this is applicable only for the commands run with sudo privilege. Executing any other commands without sudo will normally work.

Restoring Original sudoers File Configuration

If you want to revert the sudoers file back to the original configuration, you need to change it to the correct syntax that was originally present in the file. To do that, follow these steps:

1. Login as root user or switch to another sudo user who has full sudo privilege.

2. If you already have the backup, restore the sudoers file from the backup using the following command (assuming the backup file is in /etc directory).

$ sudo cp /etc/sudoers.bak /etc/sudoers

If you don't have backup, follow the subsequent steps.

3. Open the sudoers file for editing using visudo command. Make sure you're logged in as root or other sudo user.

$ sudo visudo

4. Locate the line that you want to modify. In our case, it's the line that grants sudo privileges to the sudo group and allows them to run /bin/apt.

5. Replace the current line with the original configuration that you want to restore. For example, if the current line is:

%sudo   ALL=(ALL:ALL) /bin/apt

and you want to revert it back to the default configuration that grants full sudo privileges to the sudo group, it should be:

%sudo   ALL=(ALL:ALL) ALL

6. Save and close the sudoers file.

7. Verify the syntax of your sudoers file before exiting visudo. If there are no syntax errors, the changes will be applied.

After making these changes, the sudo configuration will be modified back to the original settings, and the users will have the sudo privileges as they had before the changes were made.

Remember to be careful when modifying the sudoers file, as incorrect configurations can lead to issues with sudo access on your system. Always use visudo to edit the file to avoid syntax errors.

Conclusion

Restricting sudo users to run specific commands is a good way to improve the security of your Linux system. By limiting the commands that sudo users can run, you can reduce the risk of unauthorized access and system damage.

Related Read:

  • How To Run Particular Commands Without Sudo Password In Linux
  • How To Allow Or Deny Sudo Access To A Group In Linux
  • How To Restrict Su Command To Authorized Users In Linux
  • Run Commands As Another User Via Sudo In Linux
  • How To Prevent Command Arguments With Sudo In Linux
  • How To Run All Programs In A Directory Via Sudo In Linux
  • How To Restore Sudo Privileges To A User

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Comment utiliser & # 039; suivant & # 039; Commande avec awk dans Linux - Partie 6Comment utiliser & # 039; suivant & # 039; Commande avec awk dans Linux - Partie 6May 15, 2025 am 10:43 AM

Dans ce sixième épisode de notre série AWK, nous explorerons la commande suivante, qui contribue à améliorer l'efficacité de vos exécutions de script en sautant les étapes de traitement redondantes. Quelle est la commande suivante? La commande suivante dans awk instruc

Comment transférer efficacement les fichiers dans LinuxComment transférer efficacement les fichiers dans LinuxMay 15, 2025 am 10:42 AM

Le transfert de fichiers dans les systèmes Linux est une tâche courante que chaque administrateur système doit maîtriser, en particulier en ce qui concerne la transmission réseau entre les systèmes locaux ou distants. Linux fournit deux outils couramment utilisés pour accomplir cette tâche: SCP (réplication sécurisée) et RSYNC. Les deux fournissent un moyen sûr et pratique de transférer des fichiers entre les machines locales ou distantes. Cet article expliquera en détail comment utiliser les commandes SCP et RSYNC pour transférer des fichiers, y compris les transferts de fichiers locaux et distants. Comprendre le SCP (Secure Copy Protocol) dans la commande Linux SCP est un programme de ligne de commande utilisé pour copier en toute sécurité les fichiers et les répertoires entre deux hôtes via SSH (Secure Shell), ce qui signifie que lorsque les fichiers sont transférés sur Internet, le nombre de

10 environnements de bureau Linux les plus populaires de tous les temps10 environnements de bureau Linux les plus populaires de tous les tempsMay 15, 2025 am 10:35 AM

Une caractéristique fascinante de Linux, contrairement à Windows et Mac OS X, est sa prise en charge d'une variété d'environnements de bureau. Cela permet aux utilisateurs de bureau de sélectionner l'environnement de bureau le plus approprié et le plus ajusté en fonction de leurs exigences informatiques.

Comment installer LibreOffice 24.8 dans Linux DesktopComment installer LibreOffice 24.8 dans Linux DesktopMay 15, 2025 am 10:15 AM

LibreOffice se démarque comme une suite de bureaux robuste et open source, adaptée aux plates-formes Linux, Windows et Mac. Il possède un éventail de fonctionnalités avancées pour gérer les documents de mots, les feuilles de calcul, les présentations, les dessins, les calculs et la mathématica

Comment travailler avec les fichiers PDF à l'aide de documents uniquement Office dans LinuxComment travailler avec les fichiers PDF à l'aide de documents uniquement Office dans LinuxMay 15, 2025 am 09:58 AM

Les utilisateurs de Linux qui gèrent les fichiers PDF ont un large éventail de programmes à leur disposition. Plus précisément, il existe de nombreux outils PDF spécialisés conçus pour diverses fonctions.

Comment filtrer la sortie de la commande à l'aide de awk et stdinComment filtrer la sortie de la commande à l'aide de awk et stdinMay 15, 2025 am 09:53 AM

Dans les segments précédents de la série de commandes AWK, notre objectif était principalement de lire les entrées des fichiers. Cependant, que se passe-t-il si vous avez besoin de lire l'entrée de Stdin? Dans la partie 7 de la série AWK, nous explorerons plusieurs exemples où vous pouvez utiliser la sortie de O

CLIFM - Gestionnaire de fichiers de terminal-rapide à Lightning pour LinuxCLIFM - Gestionnaire de fichiers de terminal-rapide à Lightning pour LinuxMay 15, 2025 am 09:45 AM

Clifm se distingue comme un gestionnaire de fichiers de ligne de commande distinctif et incroyablement rapide, conçu sur la base d'une interface de type coquille. Cela signifie que les utilisateurs peuvent s'engager avec leur système de fichiers en utilisant les commandes qu'ils connaissent déjà.

Comment passer de Linux Mint 21.3 à Linux Mint 22Comment passer de Linux Mint 21.3 à Linux Mint 22May 15, 2025 am 09:44 AM

Si vous préférez ne pas effectuer une nouvelle installation de Linux Mint 22 Wilma, vous avez la possibilité de passer à partir d'une version précédente.

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

<🎜>: Bubble Gum Simulator Infinity - Comment obtenir et utiliser les clés royales
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Système de fusion, expliqué
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers of the Witch Tree - Comment déverrouiller le grappin
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Listes Sec

Listes Sec

SecLists est le compagnon ultime du testeur de sécurité. Il s'agit d'une collection de différents types de listes fréquemment utilisées lors des évaluations de sécurité, le tout en un seul endroit. SecLists contribue à rendre les tests de sécurité plus efficaces et productifs en fournissant facilement toutes les listes dont un testeur de sécurité pourrait avoir besoin. Les types de listes incluent les noms d'utilisateur, les mots de passe, les URL, les charges utiles floues, les modèles de données sensibles, les shells Web, etc. Le testeur peut simplement extraire ce référentiel sur une nouvelle machine de test et il aura accès à tous les types de listes dont il a besoin.

SublimeText3 version anglaise

SublimeText3 version anglaise

Recommandé : version Win, prend en charge les invites de code !

SublimeText3 Linux nouvelle version

SublimeText3 Linux nouvelle version

Dernière version de SublimeText3 Linux

VSCode Windows 64 bits Télécharger

VSCode Windows 64 bits Télécharger

Un éditeur IDE gratuit et puissant lancé par Microsoft

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)