Bash空闲会话时间大于15分钟

时间:2018-10-04 02:28:47

标签: bash

我需要帮助才能完成此操作。尝试使闲置时间超过15分钟的用户会话闲置15分钟,而sshd_config并没有将这些会话杀死。这是我必须退出的会话,如何过滤15分钟以上。

#!/bin/bash

IFS=$'\n'

for output in $(w | tr -s " " | cut -d" " -f1,5 | tail -n+3 | awk '{print $2}')

do

echo "$output \> 15:00"

done

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情……

for i in $(w --no-header | awk '{print $4}')
do
echo $i | grep days > /dev/null 2>&1
if [ $? == 0 ]
then
   echo "greater that 15 mins"
fi
echo $i | grep min> /dev/null 2>&1
if [ $? == 0 ]
then
   mins=$(echo $i | sed -e's/mins//g')
   if [ $min -gt 15 ]
   then
       echo "Greater than 15 mins"
   fi
fi
done

棘手的部分将是找出要杀死的pid

答案 1 :(得分:0)

如果仍然使用Awk,则shell循环是笨拙的反模式。 Awk已经知道如何在行上循环;使用它。

一个严重的问题是,w的输出依赖于系统,并且通常为了便于阅读而重新格式化。

tripleee$ w | head -n 4
 8:16  up 37 days, 19:02, 17 users, load averages: 3.49 3.21 3.11
USER     TTY      FROM              LOGIN@  IDLE WHAT
tripleee console  -                27Aug18 38days -
tripleee s003     -                27Aug18    38 ssh -t there screen -D -r

如果您看起来很相似,则可能过滤掉IDLE字段中包含非数字信息的任何内容

w -h | awk '$5 ~ /[^0-9]/ || $5 > 15'

这将打印整个w输出行。您可能只想提取TTY字段(在我的系统上为{print $2}),然后从那里找出要杀死的会话。

在类似Linux的系统上更有效的方法可能是检查/proc文件系统。