4 Unix / Linux Chroot Command Examples

chroot command is used to change the root directory to a given directory. Once you change it to this directory, you can execute a command by using this directory as the root directory.

1. Basic Usage

For example, if you make /home/john as chroot directory, and if you try to execute /bin/mycommand command, it will really use the mycommand from /home/john/bin directory.

# chroot /home/john /bin/mycommand

Note: Make sure the /home/john/bin/mycommand is statically linked. If not, you should find all other dependencies, and put it in the appropriate location under /home/john for the above to work properly.

2. Chroot Exit Status

The following are various chroot exist status:

  • 125 chroot failed
  • 126 command found, but can’t execute it
  • 127 command not found
# chroot /home/john /bin/tar ; echo $?
chroot: failed to run command `/bin/tar': No such file or directory

# chroot /home/johna/bin/tar ; echo $?
chroot: cannot change root directory to /home/johna: No such file or directory

Note: If it works properly, it will return the exit status of the command itself.

3. Execute Command with Different User

By default, the following command will execute /bin/mycommand as the user/group who invokved the chroot.

# chroot /home/john /bin/mycommand

But, if you like it to execute as a different user/group, you should specify userspec as shown below.

# chroot --userspec=john:john /home/john /bin/mycommand

4. Specify Additional Groups to Execute Command

Apart from specifying the primary user and group using –userspec, you can also pass the secondary groups using –groups command as shown below.

# chroot --userspec=john:john --groups=dba,developer /home/john /bin/mycommand

Comments on this entry are closed.

  • Crivello4 September 14, 2013, 11:06 pm

    Just Thank you.
    Keep supplying the Hacks to help us all control our machines