Golang 递归更改权限的方法是使用 “os.Chmod” 和 “os.Chown”。

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

Golang Change permission "os.chmod" and "os.chowm" recursively

问题

你可以使用os.walk函数遍历目录中的所有文件和子目录,并对每个文件和目录应用os.chmodos.chown函数来递归地改变权限和所有权。

下面是一个示例代码:

import os

def change_permissions_and_ownership(path, mode, uid, gid):
    for root, dirs, files in os.walk(path):
        for dir in dirs:
            dir_path = os.path.join(root, dir)
            os.chmod(dir_path, mode)
            os.chown(dir_path, uid, gid)
        for file in files:
            file_path = os.path.join(root, file)
            os.chmod(file_path, mode)
            os.chown(file_path, uid, gid)

# 用法示例
path = '/path/to/directory'
mode = 0o755  # 设置权限,例如 755
uid = 1000   # 设置所有者的用户ID
gid = 1000   # 设置所有者的组ID

change_permissions_and_ownership(path, mode, uid, gid)

在上面的示例中,change_permissions_and_ownership函数接受一个路径参数,一个权限模式参数(如0o755),以及一个用户ID和组ID参数。它使用os.walk遍历目录中的所有文件和子目录,并对每个文件和目录应用os.chmodos.chown函数来递归地改变权限和所有权。

请注意,为了运行此代码,你需要具有足够的权限来更改文件和目录的所有权和权限。

英文:

I am trying to change ownership and permission of files and directory using os.Chmod and os.Chown. How can I do this recursively. For Illustration linux equivalent of this chmod -R and chown -R

答案1

得分: 2

func ChownRecursively(root string) {
err := filepath.Walk(root,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
err = os.Chown(path, os.Getuid(), os.Getgid())
if err != nil {
return err
} else {
fmt.Printf("文件 %s 的所有者已更改。\n", path)
}
return nil
})
if err != nil {
log.Println(err)
}
}

英文:
func ChownRecursively(root string) {
	err := filepath.Walk(root,
		func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			err = os.Chown(path, os.Getuid(), os.Getgid())
			if err != nil {
				return err
			} else {
				fmt.Printf("File ownership of %s changed.\n", path)
			}
			return nil
		})
	if err != nil {
		log.Println(err)
	}
}

huangapple
  • 本文由 发表于 2022年9月27日 16:16:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/73864379.html
匿名

发表评论

匿名网友

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

确定