简体   繁体   中英

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 ). 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. However, I don't think that the listings in the /etc/fstab matter at all when using the mount system call in a program.

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.

How can I successfully call the mount() system call without running the program with sudo ?

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() . 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 :

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM