0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

本記事は(SadServers)[https://sadservers.com/]というlinuxサーバに関するトラブルシューティングを無料で練習可能なサイトを実施した記録です。
正解だけでなく、自分の回答過程やチップスを記録するためのものです

TL;DR

#1 - "Saint John": what is writing to this log file?
学べること

  1. テキストファイルの抽出と加工
  2. 行の並び替え
  3. 行の重複排除

利用コマンド

  • awk:テキストを「フィールド単位」で処理して、抽出・加工
  • sort:テキスト行を並び替える
  • uniq:連続した重複行を1つにまとめる

取り組み

問題の理解

説明:ウェブサーバーのアクセスログファイルが にあります/home/admin/access.log。ファイルはHTTPリクエストごとに1行で構成され、各行の先頭にはリクエスト元のIPアドレスが記されています。
このファイルで最もリクエスト数が多いIPアドレスを調べてください(同点はありません。IPアドレスは一意です)。結果をファイルに書き込んでください/home/admin/highestip.txt。例えば、リクエストが「1.2.3.4」の場合、次のように記述します。echo "1.2.3.4" > /home/admin/highestip.txt

考え方

  1. 該当ファイルの中身を確認
  2. 各行から該当のフィールドを抽出
  3. IPアドレスを昇順で表示
  4. IPアドレスの重複排除と重複カウント
  5. 重複カウントの数が大きいものから順にIPアドレスを表示

該当ファイルの中身確認

(下記はイメージ)

admin@i-0b71e631086adadb0:~$ cat /home/admin/access.log
192.168.0.1 - - [13/Apr/2025] "GET /index.html"
10.0.0.2 - - [13/Apr/2025] "POST /login"
192.168.0.1 - - [13/Apr/2025] "GET /home"

(省略)

各行から該当のフィールドを抽出

各行の先頭にIPアドレスが記載されているので、一番目の要素を抽出

awk '{print $1}' /home/admin/access.log

IPアドレスを昇順で表示

awk '{print $1}' /home/admin/access.log | sort 

IPアドレスの重複排除と重複カウント

同一IPアドレスを重複排除。また、同一IPの個数を表示

awk '{print $1}' access.log | sort | uniq -c

重複カウントの数が大きいものから順にIPアドレスを表示

admin@i-0b71e631086adadb0:~$awk '{print $1}' access.log | sort | uniq -c | sort -nr
2 192.168.0.1 (出力例)
1 10.0.0.2  (出力例)

あとは出力結果の最初のIPアドレスを該当ファイルに記載するのみ
head -n 5等を使って上位5つの最頻IPが降順に並んでいることを確認してみたもよい

公式のヒントと解答

上記の考え方と同様のため、公式のヒントは省略
補足

  • cat, cutコマンドを用いたフィールド抽出

Tips

awk [パターン] {アクション} ファイル名

{print $1} → 1列目(フィールド)を表示(例: awk '{print $1}' access.log)
-F'区切り文字' → 区切り文字を指定(例: awk -F':' '{print $1}' /etc/passwd)
{if ($3 > 1000) print $1} → 条件を指定して出力

sort [オプション] ファイル名 または パイプ入力

-n → 数値順にソート(例: sort -n numbers.txt)
-r → 降順にソート(例: sort -r names.txt)
-nr → 数値+降順(例: sort -nr)
-k 番号 → 指定フィールドでソート(例: sort -k 2)

uniq [オプション] ファイル名 または パイプ入力

-c → 重複の回数を表示(例: uniq -c)
-d → 重複した行のみ表示(例: uniq -d)
-u → 一度だけ出現した行を表示(例: uniq -u)

cut [オプション] ファイル名

-d'区切り文字' → 区切り文字を指定(例: cut -d',' -f1)
-f 番号 → フィールド番号を指定(例: cut -d' ' -f1)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?