gpt4 book ai didi

python - 如何授权/拒绝使用 Python 对 Windows 上的目录进行写访问?

转载 作者:可可西里 更新时间:2023-11-01 14:49:47 39 4
gpt4 key购买 nike

我希望能够授权或拒绝对 Windows XP 等系统上的特定目录的写入访问权限。

我尝试了以下方法,但它们都不起作用:

  • os.chmod(): 只能指定文件只读属性,见Python's doc
  • win32api.SetFileAttribute() FILE_ATTRIBUTE_READONLY:只读文件。 [...] 此属性在目录中不受支持,请参阅 MSDN's SetFileAttribute

看起来我唯一的选择是访问和更新目录的“Security info”,我已经尝试了几个小时来完成一些事情但没有成功(我真的不熟悉 Win32 API)。

关于如何做到这一点有什么想法吗?

最佳答案

这是一件很有挑战性的事情。我从 this really great answer 开始这可以帮助你做类似的事情。

您可以先列出目录的 ACL,这可以使用以下代码完成:

import win32security
import ntsecuritycon as con

FILENAME = r'D:\tmp\acc_test'

sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()

ace_count = dacl.GetAceCount()
print('Ace count:', ace_count)

for i in range(0, ace_count):
rev, access, usersid = dacl.GetAce(i)
user, group, type = win32security.LookupAccountSid('', usersid)
print('User: {}/{}'.format(group, user), rev, access)

你可以找到方法PyACL.GetAceCount()返回 ACE 的数量。

GetAce(i)函数返回 ACCESS_ALLOWED_ACE header作为一个元组:

现在您可以读取旧的 ACE 和 deleting old ones很简单:

for i in range(0, ace_count):
dacl.DeleteAce(0)

然后您可以通过调用 AddAccessAllowedAceEx() 添加权限。 [ MSDN ]:

userx, domain, type = win32security.LookupAccountName ("", "your.user")
usery, domain, type = win32security.LookupAccountName ("", "other.user")

dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 2032127, userx) # Full control
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 1179785, usery) # Read only

sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

我从脚本前半部分的列表中提取了数字 320321271179785(在运行脚本之前我在 Explorer->Right Click->Properties->Security->Advanced 中设置了权限:

Explorer->Right Click->Properties->Security->Advanced

只是从 http://technet.microsoft.com/ 借来的说明性图片

User: DOMAIN/user (0, 3) 2032127
User: DOMAIN/user2 (0, 3) 1179785

但是它对应于:

  • 3 -> OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE
  • 2032127 -> FILE_ALL_ACCESS(好吧,实际上是 con.FILE_ALL_ACCESS = 2032639,但是一旦你将它应用到文件中并读回它,你将得到 2032127;区别是 512 - 0x0200 - 我在 ntsecuritycon.py/file security permissions 中没有找到的常量)
  • 1179785 -> FILE_GENERIC_READ

您也可以删除访问权限、更改它或删除它,但这对您来说应该是一个非常可靠的开始。


TL;DR - 代码

import win32security
import ntsecuritycon as con

FILENAME = r'D:\tmp\acc_test'

userx, domain, type = win32security.LookupAccountName ("", "your.user")
usery, domain, type = win32security.LookupAccountName ("", "other.user")

sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()

ace_count = dacl.GetAceCount()
print('Ace count:', ace_count)

# Listing
for i in range(0, ace_count):
rev, access, usersid = dacl.GetAce(i)
user, group, type = win32security.LookupAccountSid('', usersid)

print('User: {}/{}'.format(group, user), rev, access)

# Removing the old ones
for i in range(0, ace_count):
dacl.DeleteAce(0)

# Add full control for user x
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,
con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE, con.FILE_ALL_ACCESS, userx)

# Add read only access for user y
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,
con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE, con.FILE_GENERIC_READ, usery)

sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

用于完整 ACE 列表的迷你实用程序

我刚刚编写了用于解析所有文件 ACE 的小脚本:

import win32security
import ntsecuritycon as con
import sys


# List of all file masks that are interesting
ACCESS_MASKS = ['FILE_READ_DATA', 'FILE_LIST_DIRECTORY', 'FILE_WRITE_DATA', 'FILE_ADD_FILE',
'FILE_APPEND_DATA', 'FILE_ADD_SUBDIRECTORY', 'FILE_CREATE_PIPE_INSTANCE', 'FILE_READ_EA',
'FILE_WRITE_EA', 'FILE_EXECUTE', 'FILE_TRAVERSE', 'FILE_DELETE_CHILD',
'FILE_READ_ATTRIBUTES', 'FILE_WRITE_ATTRIBUTES', 'FILE_ALL_ACCESS', 'FILE_GENERIC_READ',
'FILE_GENERIC_WRITE', 'FILE_GENERIC_EXECUTE']

# List of all inheritance flags
ACE_FLAGS = ['OBJECT_INHERIT_ACE', 'CONTAINER_INHERIT_ACE', 'NO_PROPAGATE_INHERIT_ACE', 'INHERIT_ONLY_ACE']

# List of all ACE types
ACE_TYPES = ['ACCESS_MIN_MS_ACE_TYPE', 'ACCESS_ALLOWED_ACE_TYPE', 'ACCESS_DENIED_ACE_TYPE', 'SYSTEM_AUDIT_ACE_TYPE',
'SYSTEM_ALARM_ACE_TYPE', 'ACCESS_MAX_MS_V2_ACE_TYPE', 'ACCESS_ALLOWED_COMPOUND_ACE_TYPE',
'ACCESS_MAX_MS_V3_ACE_TYPE', 'ACCESS_MIN_MS_OBJECT_ACE_TYPE', 'ACCESS_ALLOWED_OBJECT_ACE_TYPE',
'ACCESS_DENIED_OBJECT_ACE_TYPE', 'SYSTEM_AUDIT_OBJECT_ACE_TYPE', 'SYSTEM_ALARM_OBJECT_ACE_TYPE',
'ACCESS_MAX_MS_OBJECT_ACE_TYPE', 'ACCESS_MAX_MS_V4_ACE_TYPE', 'ACCESS_MAX_MS_ACE_TYPE',
'ACCESS_ALLOWED_CALLBACK_ACE_TYPE', 'ACCESS_DENIED_CALLBACK_ACE_TYPE', 'ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE',
'ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_AUDIT_CALLBACK_ACE_TYPE', 'SYSTEM_ALARM_CALLBACK_ACE_TYPE',
'SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE', 'SYSTEM_MANDATORY_LABEL_ACE_TYPE',
'ACCESS_MAX_MS_V5_ACE_TYPE']

################################################################################
def get_ace_types_str(ace_type):
''' Yields all matching ACE types as strings
'''
for t in ACE_TYPES:
if getattr(con, t) == ace_type:
yield t

################################################################################
def get_ace_flags_str(ace_flag):
''' Yields all matching ACE flags as strings
'''
for t in ACE_FLAGS:
attr = getattr(con, t)
if (attr & ace_flag) == attr:
yield t

################################################################################
def get_access_mask_str(access_mask):
''' Yields all matching ACE flags as strings
'''
for t in ACCESS_MASKS:
attr = getattr(con, t)
if (attr & access_mask) == attr:
yield t

################################################################################
def list_file_ace(filename):
''' Method for listing of file ACEs
'''

# Load data
sd = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()

# Print ACE count
ace_count = dacl.GetAceCount()
print('File', filename, 'has', ace_count, 'ACEs')

# Go trough individual ACEs
for i in range(0, ace_count):
(ace_type, ace_flag), access_mask, usersid = dacl.GetAce(i)
user, group, usertype = win32security.LookupAccountSid('', usersid)

print('\tUser: {}\\{}'.format(group, user))
print('\t\tACE Type ({}):'.format(ace_type), '; '.join(get_ace_types_str(ace_type)))
print('\t\tACE Flags ({}):'.format(ace_flag), ' | '.join(get_ace_flags_str(ace_flag)))
print('\t\tAccess Mask ({}):'.format(access_mask), ' | '.join(get_access_mask_str(access_mask)))
print()


################################################################################
# Execute with some defaults
if __name__ == '__main__':
for filename in sys.argv[1:]:
list_file_ace(filename)
print()

它打印出这样的字符串:

D:\tmp>acc_list.py D:\tmp D:\tmp\main.bat
File D:\tmp has 8 ACEs
User: BUILTIN\Administrators
ACE Type (0): ACCESS_MIN_MS_ACE_TYPE; ACCESS_ALLOWED_ACE_TYPE
ACE Flags (0):
Access Mask (2032127): FILE_READ_DATA | FILE_LIST_DIRECTORY | FILE_WRITE_DATA | FILE_ADD_FILE | FILE_APPEND_DATA | FILE_ADD_SUBDIRECTORY | FILE_CREATE_PIPE_INSTANCE | FILE_READ_EA | FILE_WRITE_EA | FILE_EXECUTE | FILE_TRAVERSE | FILE_DELETE_CHILD | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE

...

关于python - 如何授权/拒绝使用 Python 对 Windows 上的目录进行写访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465546/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com