본문 바로가기

리눅스

[draft] sudo 명령어

sudo 명령어

sudo란?

sudo는 리눅스·유닉스 계열 시스템에서 일반 사용자가 일시적으로 root(슈퍼유저) 권한으로 명령을 실행할 수 있도록 해주는 명령어입니다.

필요한 작업에만 권한을 상승시킬 수 있기 때문에 보안과 시스템 안정성 측면에서 su보다 안전한 방식으로 권장됩니다.

기본 사용법

기본 형식

sudo 명령어

시스템 파일 편집

sudo vim /etc/config.txt

사용 예시

패스워드 입력

  • sudo를 사용할 때는 일반적으로 현재 사용자의 패스워드를 입력해야 합니다.

특정 사용자로 실행

  • sudo를 사용하여 특정 사용자로 명령어를 실행할 수도 있습니다. -u 옵션을 사용합니다.
sudo -u <사용자명> <명령어>
sudo -u nginx ls /var/log/nginx

루트 셸 실행

  • root 환경 그대로 로그인한 것과 동일한 효과
sudo -i

특정 환경 변수 유지

  • PATH, ENV 등을 유지한 채 실행할 때 사용
sudo -E <명령어>

권한 있는 디렉토리에서 파일 생성

  • 슈퍼유저 권한이 필요한 디렉토리에 파일을 생성하려면 sudo를 사용하여 실행합니다.
sudo sh -c 'echo "내용" > /etc/myfile.txt'

위의 예시는 sudo 명령어의 사용법과 예시를 보여주는 것입니다. sudo는 시스템 관리 작업을 수행할 때 매우 유용한 도구이지만 주의해서 사용해야 하며 필요한 경우에만 사용하는 것이 좋습니다.

sudo: command not found 오류 해결

$ sudo
bash: sudo: command not found

sudo: command not found 오류는 sudo 명령어가 현재 사용자의 환경 변수에 포함되어 있지 않거나 시스템에서 설치되지 않은 경우 발생할 수 있습니다.

1. su 사용

sudo가 사용되지 않는 경우에는 su 명령어를 사용하여 root 사용자로 전환할 수 있습니다.

su -

이 명령은 root 사용자로 전환하며, 패스워드를 입력해야 합니다.

2. sudo 경로 확인

sudo 명령어가 설치되어 있는지 확인하고 경로를 확인합니다. 일반적으로 /usr/bin/sudo에 위치합니다.

which sudo

sudo 명령어가 설치되어 있지 않은 경우 시스템 패키지 관리자를 사용하여 설치할 수 있습니다.

3. sudo 설치

sudo 명령어가 시스템에 설치되어 있지 않은 경우, 시스템 패키지 관리자를 사용하여 설치할 수 있습니다. 패키지 관리자에 따라 설치 방법이 다를 수 있습니다.

  • CentOS/RHEL 계열
su -c "yum install -y sudo"
  • Ubuntu/Debian 계열
su -c "apt-get install -y sudo"

위의 방법 중 하나를 시도하여 sudo 명령어를 정상적으로 사용할 수 있도록 설정할 수 있습니다. 그러나 sudo 명령어가 시스템에서 필요한 중요한 보안 도구이므로 가능한 경우 설치하여 사용하는 것이 좋습니다.

sudo 설정 파일 (/etc/sudoers)

반드시 visudo로 편집해야 합니다. (문법 오류 시 자동 검사)
cat /etc/sudoers
# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.
#
# Host alias specification
# User alias specification
# Cmnd alias specification
# Defaults specification

# User privilege specification
root ALL=(ALL) ALL

# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL

# Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

# Samples
# %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users localhost=/sbin/shutdown -h now

특정 사용자에게 sudo 권한 부여

visudo
# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.
#

# Host alias specification
# User alias specification
# Cmnd alias specification
# Defaults specification

# User privilege specification
root ALL=(ALL) ALL

# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL

# Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

# Samples
# %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users localhost=/sbin/shutdown -h now

user1 ALL=(ALL) NOPASSWD: ALL
  • user1 계정에게 패스워드 없이 모든 명령 허용

설정 후 테스트

user1 계정으로 로그인 한다.

su - user1
sudo reboot

vagrant 사용자에게 sudo 권한 부여

echo 'vagrant ALL=NOPASSWD: ALL' >> /etc/sudoers