如何在Windows中控制文件访问权限?

huangapple go评论93阅读模式
英文:

How to control file access in Windows?

问题

Go提供了os.Chmod()函数来设置文件和目录的权限。例如,如果我想确保一个文件只能被当前用户访问,可以使用以下代码:

os.Chmod("somefile.txt", 0600)

这在Linux上运行得很好,但在Windows上却没有任何效果。在查看Go源代码后,我发现了它的实现。看起来,S_IWRITE是唯一支持的属性。

我该如何使用Go在Windows上控制文件或目录的访问权限呢?

英文:

Go provides os.Chmod() for setting file and directory permissions. For example, if I want to ensure a file is accessible only to the current user, I can do the following:

os.Chmod("somefile.txt", 0600)

This works great on Linux but does absolutely nothing on Windows. After digging into the Go source code, I came across its implementation. It seems like S_IWRITE is the only attribute supported.

How do I control access to a file or directory on Windows using Go?

答案1

得分: 16

解释

Windows不使用传统的Unix权限。相反,Windows通过访问控制来控制对文件和目录的访问。每个对象都有一个ACL(访问控制列表) *,用于控制对该对象的访问。

每个ACL基本上是一个ACE(访问控制条目)列表,确定特定受托人(用户、组等)被授予的访问权限。例如,一个文件可能包含一个ACE,授予特定用户对文件的读取访问权限(GENERIC_READ)。

通过Windows API中的授权函数来操作ACL和ACE。

* 从技术上讲,每个对象有两个ACL - 一个DACL和一个SACL

解决方案

幸运的是,不需要学习所有这些函数。我已经编写了一个名为"go-acl"的小型Go包,它完成了所有繁重的工作,并公开了一个名为(当然)Chmod的函数。基本用法如下:

import "github.com/hectane/go-acl"

err := acl.Chmod("C:\\path\\to\\file.txt", 0755)
if err != nil {
    panic(err)
}

结果

Chmod()函数在文件的ACL中创建了三个ACE:

如何在Windows中控制文件访问权限?

  • 一个用于所有者(WinCreatorOwnerSid

  • 一个用于组(WinCreatorGroupSid

  • 一个用于其他所有人(WinWorldSid

英文:

Explanation

Windows does not use traditional Unix permissions. Instead, Windows controls access to files and directories through access control. Each object has an ACL (Access Control List)<sup>*</sup> which controls access to the object.

Each ACL is basically a list of ACEs (Access Control Entries) which determine what access a specific trustee (user, group, etc.) is granted. For example, a file may contain an ACE granting a specific user read access (GENERIC_READ) to the file.

Manipulating ACLs and ACEs is done through the authorization functions in the Windows API.

<sub><sup>* technically each object has two ACLs - a DACL and a SACL</sup></sub>

Solution

Thankfully, learning all of these functions isn't necessary. I've put together a small Go package named "go-acl" that does all of the heavy-lifting and exposes a function named (what else?) Chmod. Basic usage is as follows:

import &quot;github.com/hectane/go-acl&quot;

err := acl.Chmod(&quot;C:\\path\\to\\file.txt&quot;, 0755)
if err != nil {
    panic(err)
}

Results

The Chmod() function creates three ACEs in the file's ACL:

如何在Windows中控制文件访问权限?

  • one for the owner (WinCreatorOwnerSid)

  • one for the group (WinCreatorGroupSid)

  • one for everyone else (WinWorldSid)

huangapple
  • 本文由 发表于 2015年10月31日 06:21:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/33445727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定