0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ワンライナーで疎通確認を一括実行 ~Linux~

Last updated at Posted at 2025-03-02

概要

複数の宛先に対して、疎通確認を一括実行するワンライナーです。
今回はping、Tracepath、netcatで作成しました。

課題として、逐次実行によるファイルの上書きがうまくいきませんでした。
ワンライナーといっても、pingコマンドの前後にファイル作成や削除のコマンドを実行する必要があります。

コマンド実行手順

① 読み込みファイルの作成

任意のworkディレクトリに移動し、ip_list.txtを作成。
ip_list.txtに疎通対象のIPアドレスを改行区切りで記載します。

ip_list.txt:記載例
google.com
8.8.8.7
8.8.8.8

② 疎通コマンドの実行

以下のコマンドのうち、確認したいものを実行します。
オプションは適宜修正してください。
前段のip_list.txtに記載したアドレス分、ip_result_${ip}.txtファイルが作成されます。

  • ping
while read -r ip; do echo "===== Pinging $ip =====" >> ip_result_${ip}.txt ; ping -c 4 "$ip" >> ip_result_${ip}.txt 2>&1 ; echo "" >> ip_result_${ip}.txt & done < ip_list.txt; wait
  • tracepath(通信経路の調査)
while read -r ip; do echo "===== Tracepath to $ip =====" >> ip_result_${ip}.txt ; tracepath -m 10 "$ip" >> ip_result_${ip}.txt 2>&1 ;echo "" >> ip_result_${ip}.txt & done < ip_list.txt; wait
  • netcat(Netcat:ポート接続確認)
    ※以下はPortを80で指定。時間制限は5秒
while read -r ip; do echo "===== netcat $ip =====" >> ip_result_${ip}.txt ;netcat -zv -w 5 "$ip" 80 >> ip_result_${ip}.txt 2>&1 ;echo "" >> ip_result_${ip}.txt & done < ip_list.txt; wait

③ 結果をまとめる

前段で作成したip_result_${ip}.txtファイルをip_result.txt にまとめます。
以下のコマンドを実行後、ip_resultを確認して、疎通結果を見ます。

while read -r ip; do cat "ip_result_${ip}.txt" >> ip_result.txt && rm -f ip_result_${ip}.txt 2>&1 & done < ip_list.txt; wait

結果だけ確認したい場合

疎通確認の結果だけを、OKかNGでCSVファイルに出力させるコマンドです。
同じようにip_list.txtを作成してから実行します。

  • ping疎通確認 CSV出力
while read -r ip; do ping -c 4 "$ip" > /dev/null 2>&1 && echo "${ip},OK" || echo "${ip},NG"; done < ip_list.txt >> ping_result.csv
# 実行後、ping_result.csvを確認
  • tracepath疎通確認 CSV出力
while read -r ip; do tracepath -m 15 "$ip" 2>/dev/null | grep -qi "reached" && echo "${ip},OK" || echo "${ip},NG"; done < ip_list.txt >> tracepath_result.csv
# 実行後、tracepath_result.csvを確認

おまけ

Linuxの接続文字について、なんとなく使っていたのですが、
これを機に整理できました。

Linux接続文字一覧

  • 並列処理 → &
  • 逐次実行(失敗時も) → ;
  • 成功時実行 → &&
  • 失敗時実行 → ||
  • パイプ処理(データの受け渡し) → |
  • リダイレクトで出力をファイルに保存 → > / >>
  • エラー出力を標準出力に統合 → 2>&1
  • 不要データを捨てる → >/dev/null
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?