Linux Administration Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

When determining what's running on a server, you usually want to know if anything is listening on for connections and on what ports.

Out of the box, socket statistics (ss) is usually available. The older program, netstat, might be installed sometimes too, though it won't be covered here.

A good first step is to run ss -tua, which will list all TCP and UDP sockets:

$ ss -tua
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 127.0.0.1:323 *:*
udp UNCONN 0 0 *:bootpc *:*
udp UNCONN 0 0 *:bootpc *:*
udp UNCONN 0 0 *:sunrpc *:*
udp UNCONN 0 0 *:ntp *:*
udp UNCONN 0 0 *:728 *:*
udp UNCONN 0 0 ::1:323 :::*
udp UNCONN 0 0 :::sunrpc :::*
udp UNCONN 0 0 :::728 :::*
tcp LISTEN 0 5 *:irdmi *:*
tcp LISTEN 0 128 *:sunrpc *:*
tcp LISTEN 0 128 *:ssh *:*
tcp LISTEN 0 100 127.0.0.1:smtp *:*
tcp ESTAB 0 0 10.0.2.15:ssh 10.0.2.2:36116
tcp LISTEN 0 128 :::sunrpc :::*
tcp LISTEN 0 128 :::ssh :::*
tcp LISTEN 0 100 ::1:smtp :::*

If we want to list only to ESTAB (established) connections, we can filter down using the state directive:

$ ss -tua state established
Netid Recv-Q Send-Q Local Address:Port Peer Address:Port
tcp 0 0 10.0.2.15:ssh 10.0.2.2:36116

Here, we can see my SSH session from the host machine.

Say we now want to list all sockets that are listening for TCP connections:

$ ss -tl 
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 *:irdmi *:*
LISTEN 0 128 *:sunrpc *:*
LISTEN 0 128 *:ssh *:*
LISTEN 0 100 127.0.0.1:smtp *:*
LISTEN 0 128 :::sunrpc :::*
LISTEN 0 128 :::ssh :::*
LISTEN 0 100 ::1:smtp :::*

Alternatively, we can do this for the UDP:

$ ss -ul 
State Recv-Q Send-Q Local Address:Port Peer Address:Port
UNCONN 0 0 127.0.0.1:323 *:*
UNCONN 0 0 *:bootpc *:*
UNCONN 0 0 *:sunrpc *:*
UNCONN 0 0 *:ntp *:*
UNCONN 0 0 *:728 *:*
UNCONN 0 0 ::1:323 :::*
UNCONN 0 0 :::sunrpc :::*
UNCONN 0 0 :::728 :::*

This is enough to give us a good overview of the services running, but it doesn't let us know the ports.

ss will check against a known services list to determine the name to display. In this example, we deliberately chose to list the listening ports, filtering out everything but port 22, and we can see that ssh has been chosen:

$ ss -l sport = :22
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
tcp LISTEN 0 128 *:ssh *:*
tcp LISTEN 0 128 :::ssh :::*
:: is the IPv6 loopback denotion, which is why it shows up here next to one of the SSH entries.

We can check the system's services list to see what it thinks ssh should be using:

$ grep "^ssh " /etc/services
ssh 22/tcp # The Secure Shell (SSH) Protocol
ssh 22/udp # The Secure Shell (SSH) Protocol
ssh 22/sctp # SSH