首页 > 解决方案 > 需要帮助来调整 shell 脚本监控用户

问题描述

我需要添加可以传递参数以获取特定用户会话的位置。如果我不传递参数,它会在 24 小时内返回用户。认为:

./user-mon.sh oracle 18

它应该告诉我用户 Oracle 是否超过 18 小时。任何人都可以帮助实现这一目标。我可以在哪里做出改变和

这是脚本

#!/bin/bash
#monitor user session over 24 hrs

IFS='$NIFS' 

for who in $(who -u); do 
    IFS="$OIFS" 
    #skip any session that is not a try 
    line=$(awk '{print $1, $3, $4}' <<< "$who") 
    If grep  'old' <<< "$line";then
        Continue 
    fi
    echo "user logged in over 24 hours"
    IFS="$NIFS" 
done 

IFS="$OIFS" 

标签: shell

解决方案


以下代码段显示了如何计算用户“oracle”的登录时间:

#!/bin/bash

# how many senconds has a day?
seconds24hour=$(( 24 * 60 * 60 ))

# read content from who into array
read -r -a content <<< "$(who | grep '^oracle')"

# convert logintime into seconds
logintime=$(date -d "${content[2]} ${content[3]}" +"%s")

# convert now into seconds
now=$(date -d now +"%s")

# compute difference
difftime=$(( now - logintime ))

if [[ $difftime > $seconds24hour ]]; then
    echo "user logged in over 24 hours"
fi    

推荐阅读