Linux Bash:从 chroot 内执行命令并切换用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8157931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 22:47:04  来源:igfitidea点击:

Bash: executing commands from within a chroot and switch user

linuxbashunixchroot

提问by dgrandes

Im writing a script that should do this...

我正在写一个应该这样做的脚本......

chroot /chroot_dir/ su -
./startup.sh (This should run within the su environment)

I have tried this approach:

我试过这种方法:

chroot /chroot_dir /bin/bash -c " su -; ./startup.sh"

This tries to execute the user switching and the script as a string command to bash...however what it does, is it "stops" after "su -"and doesnt execute the script. However, once I leave the "su -" environment, it does try to run startup.sh but of course, it cant find it.

这会尝试将用户切换和脚本作为字符串命令执行到 bash ……但是它的作用是在“su -”之后停止 并且不执行脚本。但是,一旦我离开“su -”环境,它就会尝试运行 startup.sh 但当然找不到它。

Basically I need to nest the "startup.sh" to be run inside the "su -" environment...

基本上我需要嵌套“startup.sh”以在“su -”环境中运行......

采纳答案by Michael Krelin - hacker

try

尝试

chroot /chroot_dir /bin/bash -c "su - -c ./startup.sh"

回答by garuse

chroot /chroot_dir /bin/bash -x <<'EOF'
su -
./startup.sh
EOF

回答by Marek Lisiecki

basic option:

基本选项:

cat << EOF | chroot /chroot_dir 
touch aaaaa
touch bbbbb
EOF

option with different shell (eg. if using bash but in chrooted enviroment it doesn't exists)

具有不同 shell 的选项(例如,如果使用 bash 但在 chrooted 环境中它不存在)

cat << EOF | chroot /chroot_dir /bin/sh
touch aaaaa
touch bbbbb
EOF