Python os.chroot() Method



The Python os.chroot() method changes the root directory of the current process to the given path. In Linux/Unix-like systems, every process or command has a current working directory called the root directory. Any process you run after a chroot operation can only access the newly defined root directory and its subdirectories.

A process or command running in such a modified environment can't access the files outside the root directory. This modified environment is called as “jailed directory” or “chroot jail”. The chroot command is accessible to some root user and privileged process.

Syntax

Following is the syntax of Python os.chroot() method −

os.chroot(path);

Parameters

  • path − This is the path which would be set as root for the current process.

Return Value

This method does not return any value.

Example

The following example shows the usage of Python os.chroot() method. Here the root directory of the current process is changed to the path "/tmp/usr".

import os, sys
# To set the current root path to /tmp/user
os.chroot("/tmp/usr")
print ("Changed root path successfully!!")

When we run above program, it produces following result −

Changed root path successfully!!

Example

If the specified file path or directory does not exists, then this method raises NotADirectoryError.

import os, sys
os.chroot("code.txt")
print ("Changed root path successfully!!")

While executing the above code we get the following output −

Traceback (most recent call last):
  File "/home/sarika/Desktop/chown.py", line 2, in <module>
    os.chroot("code.txt")
NotADirectoryError: [Errno 20] Not a directory: 'code.txt'

Example

If the path is not specified, then this method raises a FileNotFoundError,

import os, sys
os.chroot("")
print ("Changed root path successfully!!")

Following is an output of the above code −

Traceback (most recent call last):
  File "/home/sarika/Desktop/chown.py", line 2, in <module>
    os.chroot("")
FileNotFoundError: [Errno 2] No such file or directory: ''
os_file_methods.htm
Advertisements