我正在运行的程序需要 root 权限,因此使用 运行sudo
,但它还需要知道运行它的用户是什么。getuid
并且geteuid
都返回root
。如何获取实际用户的用户名(或 uid)?
谢谢!
sudo
提供了一些环境变量来帮助您解决这种情况:
SUDO_UID Set to the user ID of the user who invoked
sudo
SUDO_USER Set to the login of the user who invoked sudo
steveayre 在评论中指出,用户可以在某些情况下设置这些环境变量;sudo(8)
手册页部分包括:
The sudoers policy subjects variables
passed on the command line to the same restrictions as normal
environment variables with one important exception. If the
setenv option is set in sudoers, the command to be run has the
SETENV tag set or the command matched is ALL, the user may set
variables that would otherwise be forbidden. See sudoers(5)
for more information.
ALL
因此,当您需要依赖此功能时,请确保不要向用户授予命令。
审计系统提供的特定于 Linux 的audit_getloginuid()
功能可能会有所帮助;因为pam_loginuid(8)
只会为“主要”守护进程(sshd
、login
、gdm
等)安装,所以审计 uid 在sudo(8)
执行时将保持不变。
这将需要一些配置;添加:
session required pam_loginuid.so
到/etc/pam.d/sshd
文件 - 以及您允许用户使用的任何其他服务。
确保pam_loginuid.so
未在/etc/pam.d/sudo
配置文件中加载。
你有两个不错的选择...
更新:
setuid 位是文件模式中的访问权限标志,它使程序以可执行文件所有者的能力运行。这就是 sudo(1) 能够以 root 身份运行的方式...... sudo 程序本身具有这种模式。
$ ls -l /usr/bin/sudo
-r-s--x--x 1 root wheel 272384 Jun 22 2009 /usr/bin/sudo*
要使程序 setuid root 可以:
$ chown root a.out
$ chmod +s a.out
不用说,setuid root 程序应该仔细编写。如果您只需要访问受保护的目录或文件,您可以将其设置为权限较低的用户。
更简单的方法是使用我是谁
who am i | awk '{print $1}'
或者
who am i | cut -f1 -d" "