gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:26:54 24 4
gpt4 key购买 nike

我正在从 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用户的密码。

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

最佳答案

首先,不建议在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 看到,我们已经可以执行根需要的命令。

关于docker - 通过命令行向用户添加 sudo 权限(无密码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65427262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com