在sudo调用的Bash脚本中标识用户 [英] Identify user in a Bash script called by sudo

查看:70
本文介绍了在sudo调用的Bash脚本中标识用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建的脚本/root/bin/whoami.sh包含:

If I create the script /root/bin/whoami.sh containing:

#!/bin/bash
whoami

此脚本由具有正确配置的sudo的用户调用,它将指示

and this script is called by a user with a properly configured sudo, it will indicate

root

是否有一种快速的方法来获取脚本中的实际用户,还是我不得不求助于该用户名传递的参数?

Is there a fast way to obtain the actual user in a script, or will I have to resort to parameters passing along this username?

推荐答案

$ SUDO_USER在使用sudo su -时不起作用.
它还需要进行多次检查-如果$USER == 'root'然后得到$SUDO_USER.

$SUDO_USER doesn't work if you are using sudo su -.
It also requires multiple checks - if $USER == 'root' then get $SUDO_USER.

使用who am i代替命令whoami.这将运行针对当前会话过滤的who命令.它为您提供了比您所需更多的信息.因此,执行此操作仅获得用户:

Instead of the command whoami use who am i. This runs the who command filtered for the current session. It gives you more info than you need. So, do this to get just the user:

who am i | awk '{print $1}'

或者(更简单),您可以使用logname.它与上述声明具有相同的作用.

Alternatively (and simpler) you can use logname. It does the same thing as the above statement.

这为您提供了登录会话的用户名.

This gives you the username that logged in to the session.

这些工作与sudosudo su [whatever]无关.无论调用susudo多少次,它也都起作用.

These work regardless of sudo or sudo su [whatever]. It also works regardless of how many times su and sudo are called.

这篇关于在sudo调用的Bash脚本中标识用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆