【问题标题】:Add sudo permission (without password ) to user by command line通过命令行向用户添加 sudo 权限(无密码)
【发布时间】:2021-04-02 06:04:04
【问题描述】:

我正在从 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"]

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

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

【问题讨论】:

  • 你不应该在 Docker 中需要sudo:一个容器只运行一个进程,当你启动它时,你可以在docker run 命令行显式指定用户(或者,如果你需要一个调试外壳,docker exec -u 可以作为备用用户启动它)。您要打包的应用程序是什么,它如何需要sudoHow to use sudo inside a docker container? 有足够的信息给你吗?
  • 你说得对。但这不是我的决定。

标签: docker ubuntu dockerfile sudo sudoers


【解决方案1】:

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

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

RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

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

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"]

测试效果:

$ 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

你可以看到sudo,我们已经可以执行根需要的命令了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    相关资源
    最近更新 更多