Linux 'w' 命令,获取 IDLE 时间(以秒为单位)

Linux 'w' 命令,获取 IDLE 时间(以秒为单位)

我需要以秒为单位(而不是分钟或天)获取所有用户的空闲时间,我该如何做?此命令列出所有连接用户的空闲时间:

w | awk '{if (NR!=1) {print $1,$5 }}'

输出:

USER IDLE
root 4:29m
root 105days
root 2days
root 10:49m
root 7.00s
root 4:27m

我如何将天和分钟转换为秒?

答案1

空闲时间并不比用户登录的 TTY 设备的最后访问时间更复杂。因此,一种简单的方法是获取人们登录的所有 TTY 名称,然后stat

who -s | awk '{ print $2 }' | (cd /dev && xargs stat -c '%n %U %X')

在某些系统上,这会为登录会话(例如不在真实 tty 上的 X11 会话)发出错误。

如果您想要年龄而不是绝对时间,请对其进行后处理以从当前时间中减去它:

who -s | awk '{ print $2 }' | (cd /dev && xargs stat -c '%n %U %X') |
    awk '{ print $1"\t"$2"\t"'"$(date +%s)"'-$3 }'

或者使用perl's-A运算符:

who -s | perl -lane 'print "$F[1]\t$F[0]\t" . 86400 * -A "/dev/$F[1]"'

答案2

这不是最优雅的代码,它可以缩短,但那是为了你的作业:-)

w |awk '{
if (NR!=1){ 
if($5 ~ /days/){ 
    split($5,d,"days");
    print $1,d[1]*86400" sec"
}
else if( $5 ~ /:|s/){
    if ($5 ~/s/) { sub(/s/,"",$5); split($5,s,"."); print $1,s[1]" sec" }
    else if ( $5 ~/m/) { split($5,m,":"); print $1,(m[1]*60+m[2])*60" sec" }
    else { split($5,m,":"); print $1,m[1]*60+m[2]" sec" }
}
else { print $1,$5}
}}'

答案3

这是一个 bash 解决方案:

WishSeconds () {

    # PARM 1: 'w -ish' command idle time 44.00s, 5:10, 1:28m, 3days, etc.
    #      2: Variable name (no $ is used) to receive idle time in seconds

    # NOTE: Idle time resets to zero when user types something in terminal.
    #       A looping job calling a command doesn't reset idle time.

    local Wish Unit1 Unit2
    Wish="$1"
    declare -n Seconds=$2

    # Leading 0 is considered octal value in bash. Change ':09' to ':9'
    Wish="${Wish/:0/:}"

    if [[ "$Wish" == *"days"* ]] ; then
        Unit1="${Wish%%days*}"
        Seconds=$(( Unit1 * 86400 ))
    elif [[ "$Wish" == *"m"* ]] ; then
        Unit1="${Wish%%m*}"
        Unit2="${Unit1##*:}"
        Unit1="${Unit1%%:*}"
        Seconds=$(( (Unit1 * 3600) + (Unit2 * 60) ))
    elif [[ "$Wish" == *"s"* ]] ; then
        Seconds="${Wish%%.*}"
    else
        Unit1="${Wish%%:*}"
        Unit2="${Wish##*:}"
        Seconds=$(( (Unit1 * 60) + Unit2 ))
    fi

} # WishSeconds

WishSeconds "20days" Days ; echo Passing 20days: $Days
WishSeconds "1:10m"  Hours ; echo Passing 1:10m: $Hours
WishSeconds "1:30"   Mins ; echo Passing 1:30: $Mins
WishSeconds "44.20s" Secs ; echo Passing 44.20s: $Secs

结果

Passing 20days: 1728000
Passing 1:10m: 4200
Passing 1:30: 90
Passing 44.20s: 44

相关内容