我们可以通过Go在Linux中将文件挂载为只读吗?

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

How can we mount a file as read-only in Linux through Go?

问题

我想知道如何通过Golang在Linux CentOS 7服务器上将文件挂载为只读。我尝试了syscall,但没有成功,syscall会将文件挂载为读写。我尝试在数据中使用ro参数,但仍然以读写方式挂载。

以下是我的Go代码:

syscall.Mount(src, dst, "auto", syscall.MS_BIND, "ro")

你可以看到我在数据中给出了"ro"参数,我还尝试过只给出"r"、"readonly"和"read-only",但它们都不起作用。当我编译并执行这个Go文件后,当我检查/etc/mtab时,我得到以下输出:

cat /etc/mtab | grep "firewall"
/dev/vda1 /root/firewall.txt ext4 rw,relatime,data=ordered,jqfmt=vfsv1,usrjquota=quota.user 0 0

在这里你可以看到firewall.txt被挂载为"rw",意味着"读写"。

我想将其挂载为只读,请问有人可以帮我在Golang中实现吗?

英文:

I want to know how can we mount an file as read-only in Linux CentOS 7 Server through Golang. I have tried syscall but that doesn't work, syscall mounts the file but as read-write i have tried to give ro argument in the data but still it's mounting as read-write.
Here is my go code:

syscall.Mount(src, dst, "auto", syscall.MS_BIND, "ro")

You can see I have given ro argument in the data, i have also tried to give only r and readonly and also read-only but none of them works, when i compile the go file and execute it and then when i check /etc/mtab then i am getting this output :

cat /etc/mtab | grep "firewall"
/dev/vda1 /root/firewall.txt ext4 rw,relatime,data=ordered,jqfmt=vfsv1,usrjquota=quota.user 0 0

Here you can see that firewall.txt is mounted as rw means read-write

I want to mount it as read-only , can anyone help me how can i do that in Golang?

答案1

得分: 5

我遇到了类似的问题,通过将fstype设置为bind,将flags设置为MS_REMOUNTMS_RDONLYMS_BIND来解决了。你可以使用以下代码:

syscall.Mount(source, destination, "bind", syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_BIND, "")
英文:

I have faced similar issue, It was fixed by setting fstype as bind and flags as MS_REMOUNT MS_RDONLY and MS_BIND . You can use these codes:

syscall.Mount(source, destination, "bind", syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_BIND, "")

答案2

得分: 1

只读模式由系统调用标志MS_RDONLY定义,该标志也在syscall包中定义。因此,调用应该是:

syscall.Mount(src, dst, "auto", syscall.MS_BIND | syscall.MS_RDONLY, "")
英文:

Read-only mode is defined by the syscall flag MS_RDONLY, which is also defined in the syscall package. So the call should be:

syscall.Mount(src, dst, "auto", syscall.MS_BIND | syscall.MS_RDONLY, "")

huangapple
  • 本文由 发表于 2022年1月25日 22:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/70850199.html
匿名

发表评论

匿名网友

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

确定