在 Ubuntu 12.04 下,我编写了以下 C 程序来帮助我在运行自动备份时关闭服务器的 apache2 和 samba 服务。请注意,我在 Makefile 中设置了 SUID 位,以便程序在由低级用户运行时具有 root 权限tmv
。
服务.c:
#include <stdio.h>
#include <stdlib.h>
void usage(char * arg0) {
printf("Usage: %s start|stop\n", arg0);
exit(1);
}
int main(int argc, char ** argv) {
fprintf(stderr, "Running as: ");
system("whoami");
if (argc != 2) usage(argv[0]);
if (!strcmp(argv[1], "stop")) {
printf("Before running rsync, we need to shut down apache2 and smbd.\n");
system("service apache2 stop");
system("service smbd stop");
} else if (!strcmp(argv[1], "start")) {
printf("After running rsync, we need to start apache2 and smbd.\n");
system("service apache2 start");
system("service smbd start");
} else {
usage(argv[0]);
}
return 0;
}
生成文件:
all: services.c
gcc -o services services.c
chown root:tmv services
chmod u+s services # allow elevation to root
chmod o-rx services # only user tmv should execute
以下是我得到的结果:
tmv@patience:~$ ./services start
Running as: root
After running rsync, we need to start apache2 and smbd.
* Starting web server apache2 [ OK ]
start: Unable to connect to system bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory
以 root 身份运行正常:
# ./services start
Running as: root
After running rsync, we need to start apache2 and smbd.
* Starting web server apache2 [ OK ]
smbd start/running, process 8515
知道为什么./services
以用户身份运行时我的程序无法按预期工作吗tmv
?我是否也需要配置一些环境变量?
答案1
只需将其编写为 bash 脚本,然后授予您的 tmv 用户权限以使用 sudo 中的 NOPASSWD 标志执行该脚本:
sudoers 行可能类似于:
tmv ALL = (ALL) NOPASSWD: /path/to/script
此外,确保只有 root 可以修改该 bash 脚本。