linux 系统下 chroot 命令介绍和案例使用
Linux 系统下 chroot 命令用于改变当前进程的根目录,以及其子进程的根目录。它可以创建一个受限的环境,让进程运行在一个隔离的根目录下
chroot 命令介绍chroot 命令可以改变当前进程及其子进程的根目录,让它们只能访问新的根目录及其子目录。改变根目录后,进程无法访问新根目录以外的文件和目录。这种隔离的环境被称为 "chroot jail"。只有 root 用户和一些特权进程才能使用 chroot 命令chroot 命令语法textchroot [选项] 新根目录 [命令 [参数]...]常用选项:
--userspec=用户:组: 指定运行命令的用户和组--groups=组列表: 指定补充组--help: 显示帮助信息命令:
root@meng:~# chroot
chroot: missing operand
Try 'chroot --help' for more information.
root@meng:~# chroot --help
Usage: chroot [OPTION] NEWROOT [COMMAND [ARG]...]
or: chroot OPTION
Run COMMAND with root directory set to NEWROOT.
--groups=G_LIST specify supplementary groups as g1,g2,..,gN
--userspec=USER:GROUP specify user and group (ID or name) to use
--skip-chdir do not change working directory to '/'
--help display this help and exit
--version output version information and exit
If no command is given, run '"$SHELL" -i' (default: '/bin/sh -i').
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report any translation bugs to <https://translationproject.org/team/>
Full documentation <https://www.gnu.org/software/coreutils/chroot>
or available locally via: info '(coreutils) chroot invocation'
案例测试:
root@meng:~/tmp# sudo mkdir -p /opt/chroot/tmp/{bin,lib,lib64}
root@meng:~/tmp# sudo cp /bin/bash /opt/chroot/tmp/bin/
root@meng:~/tmp# sudo cp /lib/x86_64-linux-gnu/lib{c.so.6,dl.so.2,rt.so.1} /opt/chroot/tmp/lib/
root@meng:~/tmp# sudo cp /lib64/ld-linux-x86-64.so.2 /opt/chroot/tmp/lib64/
root@meng:~/tmp# sudo chroot /opt/chroot/tmp /bin/bash
/bin/bash: error while loading shared libraries: libtinfo.so.6: cannot open shared object file: No such file or directory
root@meng:~/tmp# ls /opt/chroot/
tmp
root@meng:~/tmp# ls /opt/chroot/tmp/
bin lib lib64
root@meng:~/tmp# sudo cp /lib/x86_64-linux-gnu/libtinfo.so.6 /opt/chroot/tmp/lib/
root@meng:~/tmp# sudo chroot /opt/chroot/tmp /bin/bash
bash-5.1#