Python os.access() – Test access permissions to path using real uid/gid

Python os.access()

The Python os.access() method uses the real uid/gid to test access permissions on a path. Most operations use the effective uid/gid, so this routine can be used in a suid/sgid environment to test whether the calling user has access to a specified path.

Syntax:

os.access(path, mode)

Parameters:

path: The path to test for access or existence mode.

mode: Should be F_OK to test for existence of the path, or an inclusive OR of one or more of R_OK, W_OK, and X_OK to test for permissions.

The following values can be passed as the mode argument to access() to test the following:

  • os.F_OK: Tests if the path exists.
  • os.R_OK: Tests if the path is readable.
  • os.W_OK: Tests if the path is writable.
  • os.X_OK: Checks if the path is executable.

Returns:

Returns True if access is allowed, False otherwise.

Example 1

Understanding the access() method

# Python program trying to access
# file with different mode parameters
 
# importing all necessary libraries
import os
importsys
 
# Different mode parameters will
# return True if access is allowed,
# else returns False.
 
# Assuming only read operation is allowed on file
# Checking access with os.F_OK
path1 = os.access("gfg.txt", os.F_OK)
print("Exists the path:", path1)
 
# Checking access with os.R_OK
path2 = os.access("gfg.txt", os.R_OK)
print("Access to read the file:", path2)
 
# Checking access with os.W_OK
path3 = os.access("gfg.txt", os.W_OK)
print("Access to write the file:", path3)
 
# Checking access with os.X_OK
path4 = os.access("gfg.txt", os.X_OK)
print("Check if path can be executed:", path4)

Output:

Exists the path: True
Access to read the file: True
Access to write the file: False
Check if path can be executed: False

Example 2

Code to open a file after validating access

# Python program to open a file
# after validating the access
 
# checking readability of the path
if os.access("gfg.txt", os.R_OK):
     
    # open txt file as file
    with open("gfg.txt") as file:
        return file.read()
         
# in case the file cannot be accessed       
return "Facing some issue"

Output:

Facing some issue

Leave a Reply

Your email address will not be published. Required fields are marked *