How to Change the Owner of a Directory Using Python
We can change who owns a file or directory by using the pwd, grp, and os modules. The uid module is used to change the owner, get the group ID from the group name string, and get the user ID from the user name. In this article, we will see how to change the owner of a directory using Python.
Change the Owner of a Directory Using Python
Below are the ways by which we can change the owner of a directory using Python:
- Using os.chown() Method
- Using shutil.chown() Method
Using os.chown() Method
To change the owner and group ID of the given path to the specified numeric owner ID (UID) and group ID (GID), use Python’s os.chown() method.
Syntax of os.chown() Method
os.chown(filepath, uid, gid, *, dir_fd = None, follow_symlinks = True)
Parameters:
- path: A file descriptor representing the file whose uid and gid is to be set
- uid: An integer value representing the owner id to be set for the path.
- gid: An integer value representing the group id to be set for the path. To leave any one of the ids unchanged, set it to -1.
- dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
- follow_symlinks (optional): The default value of this parameter is True. If we do not want os.chown() method to follow symlink, we can set it to False. If it is False, method will operate on the symbolic link itself instead of the file the link points to.he procedure will work on the symbolic link rather than the file it links to.
Return Type: This method does not return any value.
Example 1: Changing Owner and Group ID
In this example, the function change
is defined to modify the owner and group IDs of a specified file path (path
). It prints the current owner and group IDs, changes them to the provided uid
and gid
, then displays the updated IDs.
import os
def change(path, uid, gid):
try:
# Displaying current owner and group IDs
print("File's owner id:", os.stat(path).st_uid)
print("File's group id:", os.stat(path).st_gid)
# Changing the owner id and group id of the file
os.chown(path, uid, gid)
print("\nOwner id and group id of the file have been changed successfully")
# Displaying updated owner and group IDs
print("\nFile's owner id now is:", os.stat(path).st_uid)
print("File's group id now is:", os.stat(path).st_gid)
except FileNotFoundError:
print("File not found:", path)
except Exception as e:
print("An error occurred:", e)
# Example usage
path = "C:\\Users\\Lenovo\\Downloads\\Work TP\\trial.py"
uid = 1500
gid = 1500
change(path, uid, gid)
Output:
└─$ sudo python3 kislay.py
file's owner id: 100
file's group id: 100
Owner id and group id of the file is changed successfully
file's owner id now is: 1500
file's group id now is: 1500
Example 2: Changing Owner ID Only
In this example, the function change_owner
is utilized to update the owner ID of a specified file (path
) while maintaining the existing group ID. It first prints the current owner and group IDs, then changes the owner ID to the provided uid
, and finally displays the updated owner and group IDs.
import os
def change_owner(path, uid):
try:
# Printing the current owner id and group id
print("File's owner id:", os.stat(path).st_uid)
print("File's group id:", os.stat(path).st_gid)
# Setting gid as -1 to leave the group id unchanged
gid = -1
os.chown(path, uid, gid)
print("\nOwner id of the file has been changed successfully, leaving the group id unchanged")
# Printing the owner id and group id of the file now
print("\nFile's owner id now is:", os.stat(path).st_uid)
print("File's group id now is:", os.stat(path).st_gid)
except FileNotFoundError:
print("File not found:", path)
except Exception as e:
print("An error occurred:", e)
# Example usage
path = "C:\\Users\\Lenovo\\Downloads\\Work TP\\trial.py"
uid = 200
change_owner(path, uid)
Output:
└─$ sudo python3 kislay.py
[sudo] password for kislay:
file's owner id: 1500
file's group id: 1000
Owner id of the file is changed successfully leaving the group id unchanged
file's owner id now is: 200
file's group id now is: 1000
Using shutil.chown() Method
In this example, the function change
is defined to modify both the owner and group of a specified file (path
). It first retrieves the current owner and group, then changes them to the provided uid
and gid
using shutil.chown()
.
import shutil
from pathlib import Path
def change(path, uid, gid):
try:
# Getting the owner and the group
info = Path(path)
user = info.owner()
group = info.group()
print("Present owner and group")
print("Present owner:", user)
print("Present group:", group)
# Changing the owner and the group
shutil.chown(path, uid, gid)
print("\nThe owner and the group have been changed successfully")
# Printing the owner user and group
info = Path(path)
user = info.owner()
group = info.group()
print("Present owner now:", user)
print("Present group now:", group)
except FileNotFoundError:
print("File not found:", path)
except Exception as e:
print("An error occurred:", e)
# Example usage
path = 'C:\\Users\\Lenovo\\Downloads\\Work TP\\trial.py'
uid = 10
gid = 10
change(path, uid, gid)
Output:
$ sudo python3 code2.py
[sudo] password for kislay:
Present owner and group
Present owner: kislay
Present group: kislay
The owner and the group is changed successfully
Present owner now: uucp
Present group now: uucp
Contact Us