LoginSignup
7

More than 3 years have passed since last update.

ncコマンド覚書

Posted at

ちょいちょい nc コマンドを見かけたり、使ったりするがそのたびに、どういう動作するんだっけ、と調べるので、メモしておく。

概要

簡易なクライアント、サーバのプロセスを起動するコマンド。

次のように実行して、クライアントとして疎通確認を行う。
nc 対象ホスト(IPアドレス等) ポート番号

ヘッダを相手先ポートに送って、処理を実施させることもできる。
echo -en "GET / HTTP/1.1\n\n" | nc 対象ホスト(IPアドレス等) 80

接続先が生きているかの確認

ncの返り値で接続先が起動しているか確認することができる。
Dockerで接続先コンテナが起動するのを待つときに使いたい。

wait_for_port() {
  local name="$1" host="$2" port="$3"
  local j=0
  while ! nc -z "$host" "$port" >/dev/null 2>&1 < /dev/null; do
    j=$((j+1))
    if [ $j -ge $TRY_LOOP ]; then
      echo >&2 "$(date) - $host:$port still not reachable, giving up"
      exit 1
    fi
    echo "$(date) - waiting for $name... $j/$TRY_LOOP"
    sleep 5
  done
}

リンク集

ついでに多段sshする記事も

-W host:port
    Requests that standard input and output on the client be forwarded to host
    on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and
    ClearAllForwardings, though these can be overridden in the configuration
    file or using -o command line options. 

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
7