LoginSignup
2
1

More than 1 year has passed since last update.

ポートを使用しているプロセス

Last updated at Posted at 2021-09-26

指定したポートを使用しているプロセスを探す

いつも、ちまちまとコマンドを打っていたけど、さすがに面倒くさくなったので、普段使っている「現在使用されているポート一覧」を表示する自作コマンドに、パラメータでポート番号を与えるとそのポートを使用しているプロセスを表示するようにアップデート。

うん、かなり楽になった。

#!/usr/bin/env bash

PATH=/bin:/usr/bin:/sbin:/usr/sbin

OPT=$1

NETSTAT=`which netstat`
if [ -z ${NETSTAT} ]; then
  echo "Can't execute netstat command."
  exit 1
fi

if [ "$OPT" = "" ]; then
  case "${OSTYPE}" in
  darwin*)
    PORTLIST=(`netstat -an | grep 'LISTEN ' | awk 'match($4, /[\:\.][0-9]*$/) {print substr($4, RSTART+1, RLENGTH)}' | sort -nu`)
    ;;
  linux*)
    PORTLIST=(`netstat -an | grep 'LISTEN ' | awk '{print $4}' | grep '^[0-9:]' | sed -e 's/.*://' | sort -n | uniq`)
    ;;
  esac
  for p in ${PORTLIST[@]}; do
    echo $p
  done
else
  ps ax | grep `lsof -ni :$OPT | grep LISTEN | awk '{print $2}'`
fi
2
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
2
1