1

My program processes a perticular file , if some condition is satisfied , then it has to block the access (READ n WRITE ) to that file , for all user even for the admin.

Later , when another function is called , it has to change the access control settings back to normal.

i have tried the following code

import os, sys
import win32api
import win32security
import ntsecuritycon as con

FILENAME = "temp.txt"
os.remove (FILENAME)

def show_cacls (filename):
print
print
for line in os.popen ("cacls %s" % filename).read ().splitlines ():
print line

#
# Find the SIDs for Everyone, the Admin group and the current user
#
everyone, domain, type = win32security.LookupAccountName ("", "Everyone")
admins, domain, type = win32security.LookupAccountName ("", "Administrators")
user, domain, type = win32security.LookupAccountName ("", win32api.GetUserName ())

#
# Touch the file and use CACLS to show its default permissions
# (which will probably be: Admins->Full; Owner->Full; Everyone->Read)
#    
open (FILENAME, "w").close ()
show_cacls (FILENAME)

#
# Find the DACL part of the Security Descriptor for the file
#
sd = win32security.GetFileSecurity (FILENAME, win32security.DACL_SECURITY_INFORMATION)

#
# Create a blank DACL and add the three ACEs we want
# We will completely replace the original DACL with
# this. Obviously you might want to alter the original
# instead.
#
dacl = win32security.ACL ()
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL, everyone)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL , user)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL, admins)

#
# Put our new DACL into the Security Descriptor,
# update the file with the updated SD, and use
# CACLS to show what's what.
#
sd.SetSecurityDescriptorDacl (1, dacl, 0)
win32security.SetFileSecurity (FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)
show_cacls (FILENAME)

IT Works fine to block write access. But I can't block read access . Also i don't know any method to restore the previous access settings , because if i block the read access for admin , it will not word.

please tell me how to implement the required functions.

2
  • Are you trying to block access through security? Wouldn't it be easier to have your process lock the file? docs.activestate.com/activepython/2.4/pywin32/… Commented Apr 26, 2013 at 19:35
  • Did you ever find a way to block access to a file? Commented Aug 19, 2014 at 10:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.