Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chmod issue to change file permission using python

I am looking to change the file permission to all files to read write and execute for all the users in a directory using a python script. However, after running the script when I check the file permission doing the right click, it only shows the permissions for me and for the group everyone it only has read permission. Is there anything wrong I am doing in the following script:

import os
import pdb

for dirpath, dirnames, filenames in os.walk('M:\intra\EU'):
    for filename in filenames:
        path = os.path.join(dirpath, filename)
        os.chmod(path, 0o777) # for example
like image 235
Chaos Avatar asked Dec 16 '14 08:12

Chaos


People also ask

Why is chmod not changing permissions?

Your answer You got this error because your user is not the owner of /root folder. So you can't change the permission of your folder other than the root user. You need to switch to your root account and run the commands as shown below.

How do you change permissions on a file in Python?

We can change the permission of a file or a directory in Linux using subprocess. call() function. Python's subprocess contains a call() method that is utilised to start an application.

How do I run chmod in Python?

#!/usr/bin/python import os, sys, stat # Assuming /tmp/foo. txt exists, Set a file execute by the group. os. chmod("/tmp/foo.


1 Answers

I found a solution here :)

Setting folder permissions in Windows using Python

import win32security
import ntsecuritycon as con
import os
import pdb
userx, domain, type = win32security.LookupAccountName ("", "Everyone")
directory='M:\intra\EU'
for dirpath, dirnames, filenames in os.walk('M:\intra\EU'):
    for FILENAME in filenames:
        sd = win32security.GetFileSecurity(directory+'\\'+FILENAME, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()   # instead of dacl = win32security.ACL()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, userx)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(directory+'\\'+FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)
like image 149
Chaos Avatar answered Sep 29 '22 09:09

Chaos