Memo

メモ > サーバ > 各論: ネットワーク > とあるポート番号を誰が使っているか調べる

■とあるポート番号を誰が使っているか調べる
# lsof -i :80 … 80番ポートを使っているプロセスIDを調べる COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 9126 nginx 6u IPv4 109070 0t0 TCP *:http (LISTEN) nginx 16210 root 6u IPv4 109070 0t0 TCP *:http (LISTEN) # lsof -i :10022 … 10022番ポートを使っているプロセスIDを調べる COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 6373 root 3u IPv4 6846541 0t0 TCP www2310uo.sakura.ne.jp:10022->st1992.nas811.p-osaka.nttpc.ne.jp:61731 (ESTABLISHED) sshd 6375 refirio 3u IPv4 6846541 0t0 TCP www2310uo.sakura.ne.jp:10022->st1992.nas811.p-osaka.nttpc.ne.jp:61731 (ESTABLISHED) sshd 10283 root 3u IPv4 50789 0t0 TCP *:10022 (LISTEN)
プロセスを停止させたい場合、「# kill 9126」のようにするが、サービスの場合は可能なら正式な手続きで終了させたい 上の内容や「# ps aux | grep 9126」からサービス名を推測することもできるが、以下の方法でプロセスIDからサービスを調べることができる プロセスIDからサービスを調べるには、以下のようにする(ただし子プロセスは考慮できておらず、親プロセスのIDを渡す必要があるので改良したい)
# service --status-all | grep 9126 … プロセスIDが9126のサービス名を求める場合
サービス名が判れば、以下のように終了できる
# service httpd stop
■CentOS7の場合
# systemctl list-units --type=service … サービスの一覧を取得する(CentOS7の場合) UNIT LOAD ACTIVE SUB DESCRIPTION abrt-ccpp.service loaded active exited Install ABRT coredump hook abrt-oops.service loaded active running ABRT kernel log watcher abrtd.service loaded active running ABRT Automated Bug Reporting Tool atd.service loaded active running Job spooling tools auditd.service loaded active running Security Auditing Service 〜略〜 # systemctl status nginx.service … それぞれのサービスに対して、サービスの状態を調べる(CentOS7の場合) ● nginx.service - nginx - high performance web server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since 土 2018-02-03 19:59:02 JST; 2 months 22 days ago Docs: http://nginx.org/en/docs/ Process: 9121 ExecReload=/bin/kill -s HUP $MAINPID (code=exited, status=0/SUCCESS) Main PID: 16210 (nginx) CGroup: /system.slice/nginx.service ├─ 9126 nginx: worker process … プロセスIDが記載されているので、対象のIDかどうかを比べる └─16210 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
という手順で調べられる。子プロセスも考慮できる サービスの目星がつかない場合、すべてのサービスに対して調べるのは現実的でないので、スクリプトを作成することを推奨
# vi find_service_by_pid.sh … プロセスIDからサービス名を求めるスクリプトを作成(CentOS7の場合)
#!/bin/bash pid=$1 systemctl list-units --type=service | cut -d ' ' -f 3 | while read name do if [[ $name =~ ".service" ]] then if systemctl status $name | grep -E $pid then echo "Service is $name" fi fi done
# chmod +x find_service_by_pid.sh … 実行権限を付与 # ./find_service_by_pid.sh 9126 … プロセスIDが9126のサービス名を求める場合
サービス名が判れば、以下のように終了できる
# systemctl stop nginx.service

Advertisement