在目录中运行 sudo 命令

And*_*huk 6 bash sudo cd-command

可能的解决方案可能是:

  1. 开始交互式会话。

    sudo -s <<< "cd dir ; command"
    
    Run Code Online (Sandbox Code Playgroud)

    或者

    sudo /bin/bash -c "cd dir ; command"
    
    Run Code Online (Sandbox Code Playgroud)

    但我没有 /bin/bash /bin/sh /bin/su 或其他 sudoer 权限

  2. 在 sudo 完成之前更改目录。

    cd dir ; sudo command
    
    Run Code Online (Sandbox Code Playgroud)

    但我无权进入目录。

  3. 我需要一个一般情况下的密码集(如 Popen cwd),所以下面不是我可以使用的答案:

    sudo command /path/to/file
    
    Run Code Online (Sandbox Code Playgroud)

我正在尝试编写的是带有 sudo=True/False 选项的 python Popen 包装器,目前我正试图以某种方式让 cwd 参数起作用。

ger*_*ijk 7

我不确定更大的图景是什么,但您的方法应该是在目录中的文件运行命令。例如,如果你想运行grep regex filewhere fileis in /root,那么你应该像这样处理它:

$ sudo grep regex /root/file
Run Code Online (Sandbox Code Playgroud)

不是

$ sudo 'cd /root; grep regex file'
sudo: cd /root; grep regex file: command not found
Run Code Online (Sandbox Code Playgroud)

为什么是这个输出?嗯,这是 shell 语法,sudo 不在另一个交互式 shell 中运行命令。

另一种方法是更改​​环境变量PWD,如下所示:

$ sudo -i PWD=/root grep regex file
Run Code Online (Sandbox Code Playgroud)