Bash/WSL - 如何以root权限运行命令?

6
>ubuntu1804.exe -c "echo $USER"
mpen  

如何以root身份运行命令?

帮助页面甚至没有提到-c

>ubuntu1804.exe help
Launches or configures a Linux distribution.

Usage:
    <no args>
        Launches the user's default shell in the user's home directory.

    install [--root]
        Install the distribuiton and do not launch the shell when complete.
          --root
              Do not create a user account and leave the default user set to root.

    run <command line>
        Run the provided command line in the current working directory. If no
        command line is provided, the default shell is launched.

    config [setting [value]]
        Configure settings for this distribution.
        Settings:
          --default-user <username>
              Sets the default user to <username>. This must be an existing user.

    help
        Print usage information.
2个回答

12
原来还有一个名为wsl的命令,可以让您以任意用户身份运行任意命令。
>wsl -u root -d Ubuntu-18.04 -- echo "I am g$USER"
I am groot

注意,你需要使用单独的参数(而不是字符串)来完成这个任务。

-d 是可选的。你可以修改默认发行版,例如:

wslconfig.exe /l
wslconfig.exe /s Ubuntu-18.04
wslconfig.exe /l

wslconfig /l 似乎等同于 wsl --list


1
你在我看来赢得了互联网,因为你的回音示例。也许这已经是一个老笑话了,但我只是因为这个投票支持了你的解决方案。 - cycollins
1
就我而言,你的回声示例赢得了互联网。也许这已经是一个老笑话了,但我仅仅因为这个原因就给你的解决方案投了赞成票。 - undefined

0

如果您需要运行多个命令,只需以root身份登录:

wsl -u root

并且以交互方式运行所有命令


如果您能够交互式地运行命令,您可以像平常一样使用 sudosu。如果您需要从 Windows 非交互式地运行多个命令,则可以执行 wsl -u root -- sh -c 'echo foo && echo bar' - mpen
@mpen 我不得不交互地运行命令将我的用户添加到sudo组中 :-) - neves

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接