创建一个脚本来识别过去 15 天内未登录的用户

eno*_*noy 4 linux scripting

我有疑问:

练习是:

编写一个脚本来检测过去 15 天内未登录且属于“校友”组的用户。该列表将添加到 /var/log/alumnos_sin_login。

我的做法:

    #2)
#!/bin/bash
#Scripts which detects users whose group is "alumnos" who have been not logged in,
#in the last 15 days. The users' list is added to /var/log/alumnos_sin_login
#RESULTADO holds those users who haven't entered in the last 15 days
#LISTA holds alumnos' users' list
#USUAEIO actual user being parsed
#RAIZ != "" if user has logged -15 days

#Read and check if group is not created
exec 0 </etc/gshadow
if [ $(grep "alumnos:") -e ]
then
    echo "Grupo alumnos no existe"
    exit 1
fi


RESULTADO="Los alumnos que llevan más de 15 días sin loguearse son: "
LISTA=$(grep "alumnos:" | cut -d ':' -f 4)
IFS=,
for USUARIO in $LISTA
do
    RAIZ=$(find /home/$USUARIO -atime +15 | grep "/home/$USUARIO")
    if [ $RAIZ != "" ]
    then
        RESULTADO="$RESULTADO $USUARIO"
    fi
done

echo $RESULTADO >> /var/log/alumnos_sin_login
exit 0
Run Code Online (Sandbox Code Playgroud)

疑惑:如何改进这句话?

if [ $(grep "alumnos:") -e ]
Run Code Online (Sandbox Code Playgroud)

检查组是否已经创建。如果它不存在,它工作正常,但如果它存在,它会报告:

bash: [: ==: unary operator was expected
Run Code Online (Sandbox Code Playgroud)

为什么?

其次,是否有更好的方法来了解用户是否在过去 15 天内未登录。因为在代码中我假设它的目录是 /home/name_of_user 并且它不是标准的。我的意思是,是否有一个命令可以获取最后一个用户的登录时间,或者至少是一种正确了解其目录的方法;因为我不知道。

感谢您的帮助。

Rui*_*iro 5

获取过去 15 天内未登录用户列表的最简单方法/home是使用lastlog命令

lastlog -b 15 
Run Code Online (Sandbox Code Playgroud)

查看一行输出:

alumno1 pts/14 172.17.1.114 周六 10 月 22 日 22:18:57 +0100 2016

如果您只想要名称(第一个字段):

lastlog -b 15 | sed "1d" | awk ' { print $1 } '
Run Code Online (Sandbox Code Playgroud)

sed "1d"如果用于删除lastlog标题)

来自man lastlog

选项 适用于 lastlog 命令的选项是:

   -b, --before DAYS
       Print only lastlog records older than DAYS.
Run Code Online (Sandbox Code Playgroud)

如果用户从未登录,将显示消息 ** 从未登录** 而不是端口和时间。

至于检查组的实际脚本:

#!/bin/bash 

getent group alumnos > /dev/null
if [ $? -ne 0 ]
then
    echo "group alumnos does not exist"
    exit 1
fi

for i in ` lastlog -b 15 | sed "1d" | awk ' { print $1 } '`
do
    if [ `id -ng $i` == "alumnos" ]
    then
        echo $i
    fi
done
exit 0
Run Code Online (Sandbox Code Playgroud)

其中:
该变量i将迭代所有用户lastlog
id -ng user的名称给出的用户组的名称,当前迭代“$i”指向的用户组的名称
getent group alumnos检查该组的存在

至于if你提到的错误;当grep没有找到任何东西时,它会错过一个操作数,然后变为空;因此错误。其中一个技巧是使用“x”进行字符串比较,如下所示:

if [ "x"$i == "xstring" ]
then
   ...
Run Code Online (Sandbox Code Playgroud)

检查团体校友存在的另一种方法:

if [ $(grep "^alumnos:" /etc/group) -e ]
then
    echo "No group alumnos"
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

检查具有多个组的用户的另一种选择:

groups user | grep alumnos
Run Code Online (Sandbox Code Playgroud)