Search code examples
python-3.xunix

How to check unix path permission and assign new permission recursively to it in Python


I want to check Unix file path permission and assign new permission after checking. My requirement is if the current permission is found to be 550, I will assign 750 to it.

I am using os.stat for checking the permission and os.chmod for assigning new permission recursively. What I found that with the intent of assigning 750, I end up getting 700.

Below is my code :

import os
import stat

path = "/home/user/mydir"
st = os.stat(path)
oct_perm = oct(st.st_mode)
perm     = oct_perm[-3 : (len(oct_perm))]

if perm == '550'
    os.chmod(path, stat.S_IRWXU)

# checking permission after changing 
st = os.stat(path)
oct_perm = oct(st.st_mode)
perm     = oct_perm[-3 : (len(oct_perm))]
print ("New perm = ", perm) # this gives 700 instead of 750

How can I assign the permission like I do with Unix command such as :
chmod -R 755 /home/user/mydir
chmod -R +w /home/user/mydir

Thanks


Solution

  • You explicitly set permissions for the user only and no permissions for group or others here:

        os.chmod(path, stat.S_IRWXU)
    

    Try

        os.chmod(path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP)
    

    or

        os.chmod(path, 0o750)
    

    According to https://stackoverflow.com/a/17776766/10622916, for Python versions older than 2.6, you would have to write the octal number as

        os.chmod(path, 0750)
    

    Alternative solution with UNIX commands:

    find /home/user/mydir -perm 550 -exec chmod 750 {} +