如何查找用户使用bash脚本以root身份登录Linux?

时间:2015-02-06 19:59:12

标签: linux bash shell sh

这是一个简单的函数,我们的脚本用它来查找用户是否以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

如果你能解释一下这种语法及其做法,那将非常有用

由于

6 个答案:

答案 0 :(得分:2)

您只需使用whoami命令。

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

编辑仅限bash: 你还可以使用引用用户标识符的$ EUID变量,所以在root情况下它等于0

(($EUID == 0)) && echo 'root'

答案 1 :(得分:2)

  1. id - 打印真实有效的用户和组ID

  2. grep搜索id

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

  5. if test "$?" != "0"检查上次执行的命令grep的状态,如果0表示成功,如果不是0,您将得到消息。

答案 2 :(得分:2)

bash中,您只需测试$UID

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

答案 3 :(得分:1)

尝试whoami

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

答案 4 :(得分:1)

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

EG

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时,不需要==和!=操作,这也节省了一些按键。

答案 5 :(得分:0)

使用whoami

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