Handle可以给文件或者目录的句柄,用CreateFile得到Sub SetAccess(ByVal Handle As Long, UserName As String, ByVal AccessMask As Long, ByVal AllowAccess As Boolean) If Handle = 0 Then Exit Sub Dim SecurityDescriptor As Long, Acl As Long, Status As Long, Sid As Long, SidLength As Long, DomainName As Long, DomainNameLength As Long, UserType As Integer DomainName = Allocate(512) DomainNameLength = 512 SidLength = 0 LookupAccountNameW 0, StrPtr(UserName), ByVal 0, SidLength, DomainName, DomainNameLength, UserType Sid = Allocate(SidLength) LookupAccountNameW 0, StrPtr(UserName), ByVal Sid, SidLength, DomainName, DomainNameLength, UserType Deallocate DomainName If RtlValidSid(ByVal Sid) Then SecurityDescriptor = Allocate(4096) If SecurityDescriptor Then Status = RtlCreateSecurityDescriptor(ByVal SecurityDescriptor, 1) If Status = 0 Then Acl = Allocate(4096) Status = RtlCreateAcl(ByVal Acl, 4096, 2) If Status = 0 Then If AllowAccess Then RtlAddAccessAllowedAce ByVal Acl, 2, AccessMask, ByVal Sid Else RtlAddAccessDeniedAce ByVal Acl, 2, AccessMask, ByVal Sid RtlSetDaclSecurityDescriptor ByVal SecurityDescriptor, True, ByVal Acl, True NtSetSecurityObject Handle, 4, ByVal SecurityDescriptor End If Deallocate Acl End If Deallocate SecurityDescriptor End If Deallocate Sid End Sub
而且cacls最终也是调用的api吧。所以我怎么喜欢调用cacls
If Handle = 0 Then Exit Sub
Dim SecurityDescriptor As Long, Acl As Long, Status As Long, Sid As Long, SidLength As Long, DomainName As Long, DomainNameLength As Long, UserType As Integer
DomainName = Allocate(512)
DomainNameLength = 512
SidLength = 0
LookupAccountNameW 0, StrPtr(UserName), ByVal 0, SidLength, DomainName, DomainNameLength, UserType
Sid = Allocate(SidLength)
LookupAccountNameW 0, StrPtr(UserName), ByVal Sid, SidLength, DomainName, DomainNameLength, UserType
Deallocate DomainName
If RtlValidSid(ByVal Sid) Then
SecurityDescriptor = Allocate(4096)
If SecurityDescriptor Then Status = RtlCreateSecurityDescriptor(ByVal SecurityDescriptor, 1)
If Status = 0 Then
Acl = Allocate(4096)
Status = RtlCreateAcl(ByVal Acl, 4096, 2)
If Status = 0 Then
If AllowAccess Then RtlAddAccessAllowedAce ByVal Acl, 2, AccessMask, ByVal Sid Else RtlAddAccessDeniedAce ByVal Acl, 2, AccessMask, ByVal Sid
RtlSetDaclSecurityDescriptor ByVal SecurityDescriptor, True, ByVal Acl, True
NtSetSecurityObject Handle, 4, ByVal SecurityDescriptor
End If
Deallocate Acl
End If
Deallocate SecurityDescriptor
End If
Deallocate Sid
End Sub