찾다
시스템 튜토리얼리눅스Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법

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

Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법

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.

Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법

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>

Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법

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

Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법

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

위 내용은 Linux에서 Sudo 사용자가 특정 공인 명령을 실행하도록 제한하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Linux의 오픈 소스 특성과 Windows와 어떻게 대조되는지 설명하십시오.Linux의 오픈 소스 특성과 Windows와 어떻게 대조되는지 설명하십시오.Apr 28, 2025 am 12:03 AM

Linux의 오픈 소스 특성은 커뮤니티 참여, 성능, 보안 등의 관점에서 Windows보다 우수하지만 Windows는 사용자 친화 성 및 소프트웨어 생태계에서 더 좋습니다. 1) Linux는 지역 사회의 기여를 장려하고 빠른 개발 속도를 가지고 있습니다. 2) 서버 및 임베디드 시스템의 성능 향상; 3) 오픈 소스 특성은 더 안전합니다. 4) Windows 사용자 인터페이스는 친숙하고 소프트웨어 생태계는 광범위합니다.

디스크 I/O 성능을 모니터링하기위한 상위 5 개의 Linux 도구디스크 I/O 성능을 모니터링하기위한 상위 5 개의 Linux 도구Apr 27, 2025 pm 04:45 PM

이 안내서는 디스크 I/O 성능 모니터링 및 문제 해결을위한 필수 Linux 도구, 서버 속도 및 애플리케이션 응답 성에 영향을 미치는 중요한 메트릭입니다. 디스크 I/O 성능은 데이터가 얼마나 빨리 읽고 쓰여지는지 직접 영향을 미칩니다.

Linux에서 플러그 된 USB 장치 이름을 찾는 4 가지 방법Linux에서 플러그 된 USB 장치 이름을 찾는 4 가지 방법Apr 27, 2025 pm 04:44 PM

새로운 Linux 사용자의 경우 연결된 장치를 식별하는 것이 중요합니다. 특히 USB 드라이브. 이 안내서는 형식과 같은 작업에 필수적인 USB 장치 이름을 결정하는 몇 가지 명령 줄 방법을 제공합니다. USB 드라이브는 종종 자동 장착 (예 : /

루트 (/) 파티션에서 '장치에 남은 공간 없음'을 고치는 방법루트 (/) 파티션에서 '장치에 남은 공간 없음'을 고치는 방법Apr 27, 2025 pm 04:43 PM

Linux 시스템, 특히 디스크 공간이 제한된 문제 중 하나는 루트 파티션 (/) 공간의 소진입니다. 이 문제가 발생하면 다음 오류가 발생할 수 있습니다. 장치에 남은 공간이 없습니다 당황하지 말 것! 이것은 루트 디렉토리 (/파티션)가 가득 차 있음을 의미합니다. 이는 특히 디스크 공간이 제한된 시스템이나 24/7 실행되는 시스템에서 일반적인 문제입니다. 이런 일이 발생하면 다음과 같은 문제가 발생할 수 있습니다. 패키지를 설치하거나 업그레이드 할 수 없습니다. 시스템 시작이 실패했습니다. 서비스를 시작할 수 없습니다. 로그 또는 임시 파일에 쓸 수 없습니다. 이 기사는 문제를 식별하고 공간을 안전하게 정리하고 다시 발생하지 않도록 실용적인 단계를 안내합니다. 이 지침은 초보자에게 적합합니다

2025 년 Linux의 상위 16 개 메모장 교체2025 년 Linux의 상위 16 개 메모장 교체Apr 27, 2025 pm 04:42 PM

이 기사는 Linux 사용자를위한 최고 수치 메모장 대안을 탐색합니다. 메모장은 Windows에서 우수하지만 Linux 버전이 부족합니다. 이 안내서는 다양한 요구와 선호도에 맞는 다양한 옵션을 제공합니다. 최고의 메모장 대안

SystemD에서 새 서비스 장치를 생성하고 실행하는 방법SystemD에서 새 서비스 장치를 생성하고 실행하는 방법Apr 27, 2025 pm 04:41 PM

며칠 전, 나는 32 비트 Centos 8 분포를 발견하고 이전 32 비트 시스템에서 테스트하기로 결정했습니다. 부팅 후 네트워크 연결 문제를 발견했습니다. 연결이 삭제되어 각 재부팅 후 수동 복원이 필요합니다. 이 PR

Linux의 하드 디스크에서 나쁜 부문을 확인하는 방법Linux의 하드 디스크에서 나쁜 부문을 확인하는 방법Apr 27, 2025 pm 04:40 PM

나쁜 섹터 또는 불량 블록을 구성하는 요소를 명확히하자. 일반적으로 디스크 표면에 대한 물리적 손상 또는 오작동하는 플래시 메모리 트랜지스터로 인해 읽을 수 없거나 브레이크가되지 않는 하드 드라이브 또는 플래시 메모리의 일부입니다. 축적

CP 명령을 강요하는 방법은 프롬프트없이 파일을 덮어 쓰도록합니다.CP 명령을 강요하는 방법은 프롬프트없이 파일을 덮어 쓰도록합니다.Apr 27, 2025 pm 04:39 PM

"Copy"의 짧은 CP 명령은 Linux의 기본 도구이며 파일 및 디렉토리를 복제하기위한 기타 UNIX와 같은 시스템입니다. 로컬 파일 전송에 효율적이지만 네트워크 기반 사본의 경우 SCP (Secure Copy)가 선호됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기