[英]calling mount() system call as a non-root user
I am writing a C/C++ program that needs to be able to mount a disk as an ordinary user (can't run with sudo
). 我正在编写一个C / C ++程序,该程序需要能够以普通用户身份挂载磁盘(不能与sudo
运行)。 Typically, questions of this type pertain to using the mount
command in a shell, and the answer is to use the "user" option in the /etc/fstab
entry corresponding to the disk in question. 通常,此类问题与在shell中使用mount
命令有关,答案是在/etc/fstab
条目中使用与该磁盘相对应的“ user”选项。 However, I don't think that the listings in the /etc/fstab
matter at all when using the mount system call in a program. 但是,当在程序中使用mount系统调用时, /etc/fstab
中的列表根本不重要。
However, since it is clear that the mount
command is capable of allowing non-root users to mount disks (assuming the /etc/fstab
is setup right), and presumably the mount command calls the mount
system call, then I think it should be possible to achieve what I want. 但是,由于很明显mount
命令能够允许非root用户装载磁盘(假设/etc/fstab
设置正确),并且大概mount命令调用了mount
系统调用,那么我认为应该是可能实现我想要的。
How can I successfully call the mount()
system call without running the program with sudo
? 如何在不使用sudo
运行程序的情况下成功调用mount()
系统调用?
A valid solution to this dilemma is to pack the mount
/ umount
calls into a shell script, provide sudo
permissions for that to the application user, and call it from the application eg using system()
. 解决此难题的有效方法是将mount
/ umount
调用打包到shell脚本中,向应用程序用户提供sudo
权限,然后从应用程序中调用它,例如,使用system()
。 Make sure that the script does adequate error handling and perhaps logging, returning the appropriate exit code on error or success you can handle in the calling application. 确保该脚本进行了足够的错误处理,并且可能记录了日志,并在您可以在调用应用程序中处理的错误或成功情况下返回了适当的退出代码。
/etc/sudoers.d/myApplication
: /etc/sudoers.d/myApplication
:
<appUser> <host> = (root) NOPASSWD: /usr/local/bin/myMountScript.sh
In your application: 在您的应用程序中:
const int result = system("sudo /usr/local/bin/myMountScript.sh <options>");
//Error handling on result follows below
Another possibility is to use capabilities, as mentioned in a comment above, and set them on the binary, but that's bit more complex, so I don't get into details here. 另一种可能性是使用功能,如上面的注释中所述,然后将其设置为二进制文件,但这有点复杂,因此在此不做详细介绍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.