我想制作一个 shell 脚本,使其运行“last -a”命令并以以下形式总结其数据:
userID : number of login sessions
Host or ip1 - number of connections
Host or ip2 - number of connections
我正在尝试使用“grep”和“awk”来执行此操作,但我仍然无法获得所需的输出:(
编辑:我的进度要计算用户实例及其会话:
lasta=$(last -a)
p1=$(echo "$lasta" | awk '{print $1}' | awk '{count[$1]++}END{for(j in count) print j,": "count[j]}')
echo "$p1"
这可能是不正确的(计算 ip 或主机 ID 实例)
uniqueusers=$(echo "$lasta"| awk '{print $1}'| sort | uniq)
p2=$(echo "$lasta" | grep "$uniqueusers" | awk '{print $10 } ' | awk '{count[$1]++}END{for(j in count) print j,": "count[j]}')
echo "$p2"
答案1
笔记:我必须将其放在 BSD 系统上,该系统的last
输出格式可能与您的不同。我的系统上的输出last
如下所示:
guido ttys000 Wed Apr 6 18:44 - 18:44 (00:00)
guido ttys000 Wed Apr 6 14:36 - 14:55 (00:18)
guido ttys000 Wed Apr 6 13:56 - 14:33 (00:37)
...
因此,您可能需要更改下面代码中的一些字段说明符以匹配您系统上awk
的输出。last -a
话虽如此,这是我awk
仅依赖于完成工作的方法:
#!/bin/bash
last | awk '
# Skip final 2 lines of output
# (empty line followed by "wtmp begins..."
/^$/ { exit }
# Increment connections per user
# Increment connections per user+ip combination
{
# Possibly need to change $1 and $2 to other field numbers
# depending on output of your "last"
user[$1] ++;
userip[$1,$2] ++;
}
# For each user, print total and scan user+ip array
# for user+ip totals accumulated for this user
END {
for (u in user) {
print u " : " user[u];
for (idx in userip) {
split(idx, arr, SUBSEP);
if (arr[1] == u) print "\t" arr[2] " - " userip[idx];
}
}
}
'
输出示例:
root : 7
console - 7
guido : 682
console - 69
ttys000 - 446
...