LoginSignup
14
13

More than 5 years have passed since last update.

chroot 使い方

Last updated at Posted at 2018-07-20

基本的な使い方

$ sudo chroot NEW_ROOT_DIRECTORY_NAME [COMMAND]

ルートディレクトリ変更

'bin/bash' No such file or directory

$ mkdir /home/miyagawa/chroot_test
$ sudo chroot /home/miyagawa/chroot_test
chroot: failed to run command ‘/bin/bash’: No such file or directory

調査&解決

$ ls -la /bin/bash
-rwxr-xr-x 1 root root 1037528 May 16  2017 /bin/bash

存在する。

chrootの説明文を見てみる。

プログラムは一般に起動されたときに、一時ファイル、設定ファイル、スペシャルファイル、共有ライブラリなどが特定の位置(ディレクトリ)にあることを期待している。
chroot されたプログラムがうまく起動するには、chroot したディレクトリにそれらのファイルが正しく配置されていなければならない。
(引用) http://ja.wikipedia.org/wiki/Chroot

「chroot したディレクトリにそれらのファイルが正しく配置されていなければならない。」とあるので、chroot先にコピーする。

$ sudo rsync -a /bin /home/miyagawa/chroot_test

再挑戦

$ sudo chroot /home/miyagawa/chroot_test
chroot: failed to run command ‘/bin/bash’: No such file or directory

まだエラーが出る。
存在するのにNo such file or directoryが出るときは、実行不可能な状態であることが多いので、lddで使用しているライブラリを見てみる。

$ ldd /home/miyagawa/chroot_test/bin/bash
        linux-vdso.so.1 =>  (0x00007ffee5ab7000)
        libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f5ae4c91000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f5ae4a8d000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5ae46c3000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f5ae4eba000)

/libと/lib64以下がchroot先に存在しないので共有ライブラリをリンクできずにNo such file or directoryになっているのではないかと推測。
コピーする。

$ sudo rsync -a /{lib,lib64} /home/miyagawa/chroot_test/

再挑戦。

$ sudo chroot /home/miyagawa/chroot_test/
bash-4.3#

成功。

chroot内で遊んでみる

bash-4.3# pwd
/
bash-4.3# ls
bin  lib  lib64
bash-4.3# touch hoge
bash-4.3# ls
bin  hoge  lib  lib64
bash-4.3#

抜けるにはexitを使う。

bash-4.3# exit
exit
$

コマンド実行

$ sudo chroot /home/miyagawa/chroot_test/ echo hoge
hoge
$ sudo chroot /home/miyagawa/chroot_test/ touch /foo
$ ls /foo
ls: cannot access '/foo': No such file or directory
$ ls /home/miyagawa/chroot_test/foo
/home/miyagawa/chroot_test/foo

ユーザ変更

$ sudo chroot /home/miyagawa/chroot_test/ id
chroot: failed to run command ‘id’: No such file or directory

idが無いようなので入れる

$ sudo rsync -a $(which id) /home/miyagawa/chroot_test/bin/

再挑戦

$ sudo chroot /home/miyagawa/chroot_test/ id
uid=0 gid=0 groups=0

ユーザを変更して再挑戦

$ sudo chroot --userspec miyagawa:miyagawa /home/miyagawa/chroot_test/ id
uid=1002 gid=1002 groups=1002

ユーザが変わっていることがわかる

一応1002のユーザ名を確認

$ id
uid=1002(miyagawa) gid=1002(miyagawa) groups=1002(miyagawa)
14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13