Show Service's Connections
Show active connections for a running SystemD service
Show connections for a service
Systemd tracks all processes per service by placing them in the same cgroup. Using “ps”, “awk” and “lsof”, we can print network connections for a single service, across multiple processes.
The oneliner
…ironically enough not on one line
ps -e -o pid,cgroup \
  | awk '$2 ~ /dovecot.service/ {print "-p", $1}' \
  | xargs -r lsof -n -i -aRun as root, sudo may not work.
What does it do?
The example lists all processes started by “dovecot.service”.
List all running processes, and print pid and cgroup on each line.
For each line, check if the “cgroup” matches our regular expression, and print the pid. Actually, print a “-p”, and the pid, since this is used by lsof.
Use “xargs” to take the “-p $pid” lines from STDIN, and add them to the “lsof” command line.
Example output
Here, we see that the “dovecot.service” unit has a number of listening ports, and one established session.
root@mail1:~# ps -e -o pid,cgroup \
>       | awk '$2 ~ /dovecot.service/ {print "-p", $1}' \
>       | xargs -r lsof -n -i -a
COMMAND   PID USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
dovecot 17335 root   31u  IPv4 11520166      0t0  TCP *:imap2 (LISTEN)
dovecot 17335 root   32u  IPv6 11520167      0t0  TCP *:imap2 (LISTEN)
dovecot 17335 root   33u  IPv4 11520168      0t0  TCP *:imaps (LISTEN)
dovecot 17335 root   34u  IPv6 11520169      0t0  TCP *:imaps (LISTEN)
imap-logi 17564 dovenull   18u  IPv6 25385800      0t0  TCP [2001:db8::de:caf:bad]:imaps->[2001:db8::c0:ff:ee]:55043 (ESTABLISHED)Last updated