![Linux 'w' 명령, 유휴 시간(초) 가져오기](https://linux55.com/image/5174/Linux%20'w'%20%EB%AA%85%EB%A0%B9%2C%20%EC%9C%A0%ED%9C%B4%20%EC%8B%9C%EA%B0%84(%EC%B4%88)%20%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0.png)
모든 사용자의 유휴 시간을 초 단위(분 또는 일 단위가 아님)로 가져와야 합니다. 어떻게 해야 합니까? 이 명령은 연결된 모든 사용자의 유휴 시간을 나열합니다.
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
' 연산자를 사용하십시오 -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