如何找到使用bash脚本以root身份登录Linux的用户?
下面是一个简单的函数,我们的脚本使用它来查找用户是否以root用户身份登录如何找到使用bash脚本以root身份登录Linux的用户?,linux,bash,shell,sh,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
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命令即可
仅为bash编辑:
您还可以输入$EUID变量,该变量引用用户标识符,因此在root情况下,它等于0
试试whoami:
检查用户{test$whoami=root;}使用whoami:
id-打印真实有效的用户和组id
grep在id的输出中搜索root
1> /dev/null 2>&1将stdout/stderror发送到/dev/null;因此,您将不会看到输出1>/dev/null只向/dev/null发送标准输出
如果测试$?!=0检查最后执行的命令的状态,该命令为grep,如果为0表示成功,如果不是0,您将收到消息
在bash中,您可以只测试$UID:
我看到这里很多人都在使用操作数==和!=为了比较真位和假位,我建议不使用==来表示真位,而只使用!因为是假的 乙二醇 或者将数值变量与布尔值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时,操作==和!=不需要,这也会节省一些笔划。grep的第二个参数应该是一个文件。当前目录中不存在名为1的文件。带有grep的行包含输出重定向运算符1>/dev/null和2>&1,并且假定stderr标准错误输出通道2>和stdout标准输出通道1>,通常只>写入/dev/null aka,无处。顺便说一句,这是一种糟糕的测试方法。假设您有一个名为grooten的用户,或者甚至有一个名为arrowroot_饼干的组?whomai不应该在back tics中吗?@EJK,这个答案目前还没有编辑,您将它与一个类似的答案混淆,后者使用了$上的backticks的传统用法。。,有些人认为后者是目前较为理想的方法。上面的测试是什么?谢谢你的精心解答。在上面的第3点中,是来自grep的stdout或stderr发送到/dev/null。最后的2>&1是什么意思?1是标准输出。2是标准。2> &1将stderr重定向到stdout,通过发送1>\dev\null,它们都将被发送到\dev\null;
(($EUID == 0)) && echo 'root'
if [ `whoami` == "root" ] ; then
echo "root"
fi
if ((UID==0)); then
# I'm root
fi
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'
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"