lsof, netstat コマンド

この記事は [Linux コマンド 全部オレ Advent Calendar 2017](https://adventar.org/calendars/2630) の2日目の記事です。

# lsof

```
NAME
       lsof - list open files

SYNOPSIS
       lsof  [  -?abChKlnNOPRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [ +|-D D ] [ +|-e s ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g [s] ] [ -i [i] ] [ -k k ] [ +|-L
       [l] ] [ +|-m m ] [ +|-M ] [ -o [o] ] [ -p s ] [ +|-r [t[m<fmt>]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [ +|-w ] [ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [
       -- ] [names]

DESCRIPTION
       Lsof revision 4.87 lists on its standard output file information about files opened by processes for the following UNIX dialects:

            Apple Darwin 9 and Mac OS X 10.[567]
            FreeBSD 4.9 and 6.4 for x86-based systems
            FreeBSD 8.2, 9.0 and 10.0 for AMD64-based systems
            Linux 2.1.72 and above for x86-based systems
            Solaris 9, 10 and 11

       (See the DISTRIBUTION section of this manual page for information on how to obtain the latest lsof revision.)

       An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.)  A specific file or all the files in a file system may be selected by path.

       Instead of a formatted display, lsof will produce output that can be parsed by other programs.  See the -F, option description, and the  OUTPUT  FOR  OTHER PROGRAMS section for more information.

       In  addition  to producing a single output list, lsof will run in repeat mode.  In repeat mode it will produce output, delay, then repeat the output operation until stopped with an interrupt or quit signal.  See the +|-r [t[m<fmt>]] option description for more information.
```
`list open files` の略。プロセスが開いているファイルディスクリプタを表示するコマンド。
ファイルディスクリプタなので、`a stream or a network file (Internet socket, NFS file or UNIX domain socket.)` の通り、ネットワークソケットの情報なども表示できる。

## よく使いそうな使い方

### ネットワークコネクションを表示する

```
[sinsnegumi ~]$ sudo /sbin/lsof -i -P
COMMAND      PID   USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
dhclient     810   root    6u  IPv4   14934      0t0  UDP *:68
dhclient     810   root   20u  IPv4   14903      0t0  UDP *:59116
dhclient     810   root   21u  IPv6   14904      0t0  UDP *:57007
snmpd        882   root    7u  IPv4   15827      0t0  UDP *:161
snmpd        882   root    8u  IPv4   15828      0t0  TCP localhost:199 (LISTEN)
xinetd       896   root    5u  IPv6   15598      0t0  TCP *:2105 (LISTEN)
xinetd       896   root    6u  IPv6   15599      0t0  TCP *:543 (LISTEN)
xinetd       896   root    8u  IPv6   15600      0t0  TCP *:544 (LISTEN)
chronyd     1151 chrony    1u  IPv4   17078      0t0  UDP localhost:323
sshd        1305   root    3u  IPv4   18128      0t0  TCP *:22 (LISTEN)
sshd        1305   root    4u  IPv6   18130      0t0  TCP *:22 (LISTEN)
rsyslogd    1997   root    6u  IPv4   21179      0t0  UDP *:56603
rsyslogd    1997   root    8u  IPv4   21343      0t0  UDP *:50551
rsyslogd    1997   root    9u  IPv4   21344      0t0  UDP *:56067
ds_agent    2027   root   10u  IPv6   21355      0t0  TCP *:4118 (LISTEN)
node_expo  85896   root    3u  IPv6 2211068      0t0  TCP *:9100 (LISTEN)
ruby      101960   root   12u  IPv4  827224      0t0  UDP *:33734
nginx     105456   root    6u  IPv4  971061      0t0  TCP *:80 (LISTEN)
nginx     105457  nginx    6u  IPv4  971061      0t0  TCP *:80 (LISTEN)
```
`-P` は、well-known を自動で置換（80 -> HTTP etc）するのを抑制する。

### プロセスが開いているファイルディスクリプタを表示する

```
[sinsengumi ~]$ sudo /sbin/lsof -p 105457 -P
COMMAND    PID  USER   FD      TYPE             DEVICE SIZE/OFF     NODE NAME
nginx   105457 nginx  cwd       DIR              253,2      281       64 /
nginx   105457 nginx  rtd       DIR              253,2      281       64 /
nginx   105457 nginx  txt       REG              253,2  1264584 25312354 /usr/sbin/nginx
nginx   105457 nginx  mem       REG              253,2   155744 25420012 /usr/lib64/libselinux.so.1
nginx   105457 nginx  mem       REG              253,2   111080 25401993 /usr/lib64/libresolv-2.17.so
nginx   105457 nginx  mem       REG              253,2    36392 17873397 /usr/nhnkrb5/lib/libkrb5support.so.0.1
nginx   105457 nginx  mem       REG              253,2   154696 17873385 /usr/nhnkrb5/lib/libk5crypto.so.3.1
nginx   105457 nginx  mem       REG              253,2    15848 25420024 /usr/lib64/libcom_err.so.2.1
nginx   105457 nginx  mem       REG              253,2   602952 17873395 /usr/nhnkrb5/lib/libkrb5.so.3.3
nginx   105457 nginx  mem       REG              253,2    11384 25377296 /usr/lib64/libfreebl3.so
nginx   105457 nginx  mem       REG              253,2  2127336 25377325 /usr/lib64/libc-2.17.so
nginx   105457 nginx  mem       REG              253,2    90664 25420015 /usr/lib64/libz.so.1.2.7
nginx   105457 nginx  mem       REG              253,2  2512448 25736459 /usr/lib64/libcrypto.so.1.0.2k
nginx   105457 nginx  mem       REG              253,2   470336 25736461 /usr/lib64/libssl.so.1.0.2k
nginx   105457 nginx  mem       REG              253,2   402384 25402043 /usr/lib64/libpcre.so.1.2.0
nginx   105457 nginx  mem       REG              253,2    41080 25377329 /usr/lib64/libcrypt-2.17.so
nginx   105457 nginx  mem       REG              253,2   144792 25401991 /usr/lib64/libpthread-2.17.so
nginx   105457 nginx  mem       REG              253,2    19776 25377331 /usr/lib64/libdl-2.17.so
nginx   105457 nginx  mem       REG              253,2   164264 25377318 /usr/lib64/ld-2.17.so
nginx   105457 nginx  mem       REG              253,2   217032 27823251 /var/db/nscd/group
nginx   105457 nginx  mem       REG              253,2   217032 27823250 /var/db/nscd/passwd
nginx   105457 nginx  mem       REG              253,2   189096 17873381 /usr/nhnkrb5/lib/libgssapi_krb5.so.2.2
nginx   105457 nginx  DEL       REG               0,10            971075 /[aio]
nginx   105457 nginx  DEL       REG                0,4            971062 /dev/zero
nginx   105457 nginx    0u      CHR                1,3      0t0     4856 /dev/null
nginx   105457 nginx    1u      CHR                1,3      0t0     4856 /dev/null
nginx   105457 nginx    2w      REG              253,2     1182 41943130 /var/log/nginx/error.log
nginx   105457 nginx    4w      REG              253,2     1182 41943130 /var/log/nginx/error.log
nginx   105457 nginx    5w      REG              253,2 44411701 41943129 /var/log/nginx/access.log
nginx   105457 nginx    6u     IPv4             971061      0t0      TCP *:80 (LISTEN)
nginx   105457 nginx    7u     unix 0xffff880028402800      0t0   971071 socket
nginx   105457 nginx    8u  a_inode                0,9        0     4852 [eventpoll]
nginx   105457 nginx    9u  a_inode                0,9        0     4852 [eventfd]
nginx   105457 nginx   10u  a_inode                0,9        0     4852 [eventfd]

[sinsengumi ~]$ sudo /sbin/lsof -p 105457 -a -i
COMMAND    PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   105457 nginx    6u  IPv4 971061      0t0  TCP *:http (LISTEN)
```
AND 条件にしたい場合は `-a` を付ける必要がある。


#### 特定のファイルを開いているプロセスを特定する

```
[sinsengumi ~]$ sudo /sbin/lsof /var/log/nginx/access.log
COMMAND    PID  USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
tail     57244  root    3r   REG  253,2 44411701 41943129 /var/log/nginx/access.log
ruby    101960  root   16r   REG  253,2 44411701 41943129 /var/log/nginx/access.log
nginx   105456  root    5w   REG  253,2 44411701 41943129 /var/log/nginx/access.log
nginx   105457 nginx    5w   REG  253,2 44411701 41943129 /var/log/nginx/access.log
```
nginx 以外に tail, ruby（fluentd）が開いていることがわかる。`3r` とか `16r` とかなので読み取り専用で開いている。

## 参考

- https://orebibou.com/2016/04/lsof%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%81%A7%E8%A6%9A%E3%81%88%E3%81%A6%E3%81%8A%E3%81%8D%E3%81%9F%E3%81%84%E4%BD%BF%E3%81%84%E6%96%B99%E5%80%8B/
- https://qiita.com/kooohei/items/9e3859e3d1d854c3d163
- https://qiita.com/yusabana/items/fd03ee4c90a0d1e0a8c6
- https://qiita.com/hypermkt/items/905139168b0bc5c28ef2


# netstat

```
NAME
       netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships

SYNOPSIS
       netstat  [address_family_options]  [--tcp|-t] [--udp|-u] [--udplite|-U] [--sctp|-S] [--raw|-w] [--listening|-l] [--all|-a] [--numeric|-n] [--numeric-hosts]
       [--numeric-ports] [--numeric-users] [--symbolic|-N] [--extend|-e[--extend|-e]] [--timers|-o] [--program|-p]  [--verbose|-v]  [--continuous|-c]  [--wide|-W]
       [delay]

       netstat    {--route|-r}    [address_family_options]    [--extend|-e[--extend|-e]]   [--verbose|-v]   [--numeric|-n]   [--numeric-hosts]   [--numeric-ports]
       [--numeric-users] [--continuous|-c] [delay]

       netstat {--interfaces|-I|-i} [--all|-a] [--extend|-e] [--verbose|-v] [--program|-p] [--numeric|-n]  [--numeric-hosts]  [--numeric-ports]  [--numeric-users]
       [--continuous|-c] [delay]

       netstat {--groups|-g} [--numeric|-n] [--numeric-hosts] [--numeric-ports] [--numeric-users] [--continuous|-c] [delay]

       netstat {--masquerade|-M} [--extend|-e] [--numeric|-n] [--numeric-hosts] [--numeric-ports] [--numeric-users] [--continuous|-c] [delay]

       netstat {--statistics|-s} [--tcp|-t] [--udp|-u] [--udplite|-U] [--sctp|-S] [--raw|-w] [delay]

       netstat {--version|-V}

       netstat {--help|-h}

       address_family_options:

       [-4|--inet]  [-6|--inet6]  [--protocol={inet,inet6,unix,ipx,ax25,netrom,ddp,  ...  }  ] [--unix|-x] [--inet|--ip|--tcpip] [--ax25] [--x25] [--rose] [--ash]
       [--ipx] [--netrom] [--ddp|--appletalk] [--econet|--ec]

NOTES
       This program is obsolete.  Replacement for netstat is ss.  Replacement for netstat -r is ip route.  Replacement for netstat -i is ip -s link.   Replacement
       for netstat -g is ip maddr.

DESCRIPTION
       Netstat prints information about the Linux networking subsystem.  The type of information printed is controlled by the first argument, as follows:

   (none)
       By default, netstat displays a list of open sockets.  If you don't specify any address families, then the active sockets of all configured address families will be printed.
```
ネットワークコネクションの情報を表示する。
ちなみに、このコマンドは `/proc/net/*` にある情報を整形して表示しているとのこと。

## よく使いそうな使い方

### すべてのネットワークコネクションを表示する。

```
[sinsengumi ~]$ sudo netstat -apn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      105456/nginx: maste
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1305/sshd
tcp        0      0 127.0.0.1:199           0.0.0.0:*               LISTEN      882/snmpd
tcp        0    312 10.127.122.252:2105     10.128.218.44:34469     ESTABLISHED 53367/klogind
tcp        0      0 10.127.122.252:60690    10.114.14.155:80        TIME_WAIT   -
tcp        1      0 10.127.122.252:60512    10.114.14.155:80        CLOSE_WAIT  2071/ds_agent
tcp        0      0 10.127.122.252:33998    10.118.203.103:80       TIME_WAIT   -
tcp        0      0 10.127.122.252:41386    10.32.128.149:9972      TIME_WAIT   -
tcp        0      0 10.127.122.252:35286    10.128.215.195:18000    ESTABLISHED 1653/./box
tcp        0      0 10.127.122.252:2105     10.128.218.44:45677     ESTABLISHED 57178/klogind
tcp        1      0 10.127.122.252:38400    203.104.134.7:80        CLOSE_WAIT  2071/ds_agent
tcp        0      0 10.127.122.252:44732    10.128.215.194:18000    ESTABLISHED 1653/./box
tcp        0      0 10.127.122.252:41666    10.22.31.21:9972        TIME_WAIT   -
tcp        0      0 10.127.122.252:60688    10.114.14.155:80        TIME_WAIT   -
tcp        0      0 10.127.122.252:40554    10.128.215.193:18000    ESTABLISHED 1653/./box
tcp6       0      0 :::9100                 :::*                    LISTEN      85896/node_exporter
tcp6       0      0 :::4118                 :::*                    LISTEN      2027/ds_agent
tcp6       0      0 :::22                   :::*                    LISTEN      1305/sshd
tcp6       0      0 :::2105                 :::*                    LISTEN      896/xinetd
tcp6       0      0 :::543                  :::*                    LISTEN      896/xinetd
tcp6       0      0 :::544                  :::*                    LISTEN      896/xinetd
tcp6       0      0 10.127.122.252:9100     10.127.118.220:40658    ESTABLISHED 85896/node_exporter
udp        0      0 0.0.0.0:59116           0.0.0.0:*                           810/dhclient
udp        0      0 0.0.0.0:56067           0.0.0.0:*                           1997/rsyslogd
udp        0      0 0.0.0.0:33734           0.0.0.0:*                           101960/ruby
udp        0      0 0.0.0.0:68              0.0.0.0:*                           810/dhclient
udp        0      0 0.0.0.0:161             0.0.0.0:*                           882/snmpd
udp        0      0 0.0.0.0:56603           0.0.0.0:*                           1997/rsyslogd
udp        0      0 127.0.0.1:323           0.0.0.0:*                           1151/chronyd
udp        0      0 0.0.0.0:50551           0.0.0.0:*                           1997/rsyslogd
udp6       0      0 :::57007                :::*                                810/dhclient
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name     Path
unix  2      [ ]         DGRAM                    6912     1/systemd            /run/systemd/notify
unix  2      [ ]         DGRAM                    6914     1/systemd            /run/systemd/cgroups-agent
unix  2      [ ACC ]     STREAM     LISTENING     6922     1/systemd            /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     11021    1/systemd            /run/systemd/private
```
- `-a`: すべて
- `-p`: プロセス ID とプラグラム名を表示
- `-n`: well-known を自動で置換（80 -> HTTP etc）するのを抑制

## This program is obsolete

ss コマンドを使えとのこと。

```
[sinsnegumi ~]$ sudo /sbin/ss -anpt
State       Recv-Q Send-Q                                      Local Address:Port                                                     Peer Address:Port
LISTEN      0      511                                                     *:80                                                                  *:*                   users:(("nginx",pid=105457,fd=6),("nginx",pid=105456,fd=6))
LISTEN      0      128                                                     *:22                                                                  *:*                   users:(("sshd",pid=1305,fd=3))
LISTEN      0      128                                             127.0.0.1:199                                                                 *:*                   users:(("snmpd",pid=882,fd=8))
ESTAB       0      248                                        10.127.122.252:2105                                                    10.128.218.44:37863               users:(("klogind",pid=63186,fd=2),("klogind",pid=63186,fd=1),("klogind",pid=63186,fd=0))
CLOSE-WAIT  1      0                                          10.127.122.252:39448                                                   203.104.134.7:80                  users:(("ds_am",pid=2071,fd=13))
ESTAB       0      0                                          10.127.122.252:35286                                                  10.128.215.195:18000               users:(("box",pid=1653,fd=7))
ESTAB       0      0                                          10.127.122.252:44732                                                  10.128.215.194:18000               users:(("box",pid=1653,fd=8))
CLOSE-WAIT  1      0                                          10.127.122.252:32768                                                   10.114.14.155:80                  users:(("ds_am",pid=2071,fd=15))
TIME-WAIT   0      0                                          10.127.122.252:34888                                                  10.118.203.103:80
ESTAB       0      0                                          10.127.122.252:40554                                                  10.128.215.193:18000               users:(("box",pid=1653,fd=9))
LISTEN      0      4096                                                   :::9100                                                               :::*                   users:(("node_exporter",pid=85896,fd=3))
LISTEN      0      5                                                      :::4118                                                               :::*                   users:(("ds_agent",pid=2027,fd=10))
LISTEN      0      128                                                    :::22                                                                 :::*                   users:(("sshd",pid=1305,fd=4))
LISTEN      0      64                                                     :::2105                                                               :::*                   users:(("xinetd",pid=896,fd=5))
LISTEN      0      64                                                     :::543                                                                :::*                   users:(("xinetd",pid=896,fd=6))
LISTEN      0      64                                                     :::544                                                                :::*                   users:(("xinetd",pid=896,fd=8))
ESTAB       0      0                                   ::ffff:10.127.122.252:9100                                            ::ffff:10.127.118.220:40658               users:(("node_exporter",pid=85896,fd=5))
```
## 参考

- https://qiita.com/toshihirock/items/c6a09575c2d88c210483
- https://qiita.com/thatsdone/items/f89a774c93bffdb5d46a