# Show Service's Connections

## 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 -a
```

{% hint style="warning" %}
Run as root, sudo may not work.
{% endhint %}

### 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)
```

{% hint style="info" %}
***Source:*** <https://www.redpill-linpro.com/sysadvent/2016/12/22/systemd-at-3am.html>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://strangebutohwell.gitbook.io/knowledge/linux/systemd/show-services-connections.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
