通过命令行为用户添加 sudo 权限(无密码)

ica*_*ete 4 ubuntu sudo sudoers docker dockerfile

我正在从 ubuntu:bionic 图像创建一个 docker 文件。

我想要一个具有 sudo 权限的 ubuntu 用户。

这是我的 Dockerfile

FROM ubuntu:bionic

ENV DEBIAN_FRONTEND noninteractive

# Get the basic stuff
RUN apt-get update && \
    apt-get -y upgrade && \
    apt-get install -y \
    sudo

# Create ubuntu user with sudo privileges
RUN useradd -ms /bin/bash ubuntu && \
    usermod -aG sudo ubuntu

# Set as default user
USER ubuntu
WORKDIR /home/ubuntu

ENV DEBIAN_FRONTEND teletype

CMD ["/bin/bash"]
Run Code Online (Sandbox Code Playgroud)

但用这种方法我需要写 ubuntu 用户的密码。

有没有办法通过命令行将 NOPASSWD 子句添加到 sudoers 文件中的 sudo 组?

atl*_*ine 13

首先,不建议sudo在docker中使用。USER您可以使用+很好地设计您的行为gosu

但是,如果您出于某种不受控制的原因坚持,只需在设置普通用户后添加下一行:

RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
Run Code Online (Sandbox Code Playgroud)

因此,对于您的场景,可行的方案是:

FROM ubuntu:bionic

ENV DEBIAN_FRONTEND noninteractive

# Get the basic stuff
RUN apt-get update && \
    apt-get -y upgrade && \
    apt-get install -y \
    sudo

# Create ubuntu user with sudo privileges
RUN useradd -ms /bin/bash ubuntu && \
    usermod -aG sudo ubuntu
# New added for disable sudo password
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Set as default user
USER ubuntu
WORKDIR /home/ubuntu

ENV DEBIAN_FRONTEND teletype

CMD ["/bin/bash"]
Run Code Online (Sandbox Code Playgroud)

测试效果:

$ docker build -t abc:1 .
Sending build context to Docker daemon  2.048kB
Step 1/9 : FROM ubuntu:bionic
......
Successfully built b3aa0793765f
Successfully tagged abc:1

$ docker run --rm abc:1 cat /etc/sudoers
cat: /etc/sudoers: Permission denied

$ docker run --rm abc:1 sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
......
#includedir /etc/sudoers.d
%sudo ALL=(ALL) NOPASSWD:ALL
Run Code Online (Sandbox Code Playgroud)

您可以看到sudo,使用 ,我们已经可以执行 root 需要的命令。