如何使用 powershell 中的命令将 sudo 用户添加到 WSL?

How can I add a sudo user to WSL using commands in powershell?

我正在尝试使用 powershell 脚本自动执行 WSL 设置。 我在 windows 10 系统中为 WSL 安装了 Ubuntu 18.04 发行版。

我想 运行 在 powershell 中使用以下命令在 WSL 中设置一个 sudo 用户 tec,密码 1

Ubuntu1804 run useradd -m tec
Ubuntu1804 run usermod --password $(echo 1 | openssl passwd -1 -stdin) tec
Ubuntu1804 run usermod -aG sudo tec

问题是,第二个命令的密码设置不正确。试图成为 root 用户的结果是

 sudo: 3 incorrect password attempts

如果我在 windows 命令提示符下输入 bash 进入 WSL,然后执行以下命令:

usermod --password $(echo 1 | openssl passwd -1 -stdin) tec

密码设置正确。之后,我可以在出现提示时输入密码 1 成为 root 用户。

谁能帮我找出 powershell 脚本哪里出错了?

我得到了答案。 只需在第二个命令中用单引号将加密的密码包装起来就可以了。

Ubuntu1804 run usermod --password '$(echo 1 | openssl passwd -1 -stdin)' tec

现在,为 WSL 创建 sudo 用户 tec 密码 1 的 powershell 命令如下所示:

# Creates the user
Ubuntu1804 run useradd -m tec

# sets password for user
Ubuntu1804 run usermod --password '$(echo 1 | openssl passwd -1 -stdin)' tec

# adds user to the sudo group
Ubuntu1804 run usermod -aG sudo tec