Bash スクリプトの概要「last -a」

Bash スクリプトの概要「last -a」

「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システムに入れなければなりません。 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
...

おすすめ記事