繁体   English   中英

如何找到使用bash脚本在Linux中以root用户身份登录的用户?

[英]how to find the user is logged in as root in Linux using bash script?

这是一个简单的函数,脚本可以使用该函数来查找用户是否以root用户身份登录。

do_check_user(){
    id | grep root 1>/dev/null 2>&1
    if test "$?" != "0"
        then
            echo ""
            echo " Invalid login, Please logon as root and try again!"
            exit 0
    fi
}

我不完全了解此功能的工作原理。 我尝试了一些在线搜索,以查找实现方式的点点滴滴。 但我仍然不清楚。

特别是这些行:

id | grep root 1>/dev/null 2>&1
    if test "$?" != "0"

我试图一步一步地做。 但是我得到了错误

id | grep root 1
grep: 1: No such file or directory

如果您能向我解释这种语法及其作用,那将非常有帮助

谢谢

您只需使用whoami命令即可。

#!/bin/bashyou
if [[ $(whoami) == 'root' ]] ; then 
  echo "it's root"
fi

仅针对bash进行编辑 :您还可以使用$ EUID变量来引用用户标识符,因此在根情况下,它等于0

(($EUID == 0)) && echo 'root'
  1. id打印真实有效的用户和组ID

  2. grep在id的输出中搜索root

  3. 1>/dev/null 2>&1stdout/stderror发送到/dev/null ; 因此,您将不会看到输出1>/dev/null仅将stdout to /dev/null发送stdout to /dev/null

  4. if test "$?" != "0" if test "$?" != "0"检查最后执行的命令grep ,如果为0表示成功,如果不为0则将得到消息。

bash ,您可以仅测试$UID

if ((UID==0)); then
   # I'm root
fi

试试whoami

do_check_user() { test $(whoami) = root; }

我看到这里有很多人使用操作数==和!=比较真假位,我建议对于==不使用任何表示真实的值,而只使用! 为假。

例如

if ((UID)); then echo 'This means the test is Boolean TRUE and the user is not root'
if ((!UID)); then echo 'This means the test is Boolean FALSE and the user is root'

或者将数字变量与布尔值TRUE或FALSE进行比较

if [[$a]]; then echo "If the variable 'a' is a 1 then it's Boolean TRUE"
if [[!$a]]; then echo "If the variable 'a' is a 0 (zero) then it's Boolean FALSE"

当比较TRUE或FALSE时,不需要==和!=操作,这也节省了一些按键。

使用whoami

if [ `whoami` == "root" ] ; then
    echo "root"
fi

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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