ubuntu, updated

lsof, ss and ncdu

Which process holds a file open, which service listens on which port, and what fills the disk: three small tools for daily troubleshooting.

lsof: who has this open?

Remember everything is a file: open files, folders, sockets and devices. lsof (“list open files”) shows which process uses which of them. Run it with sudo to see all processes.

WhatCommand
Who uses this file?sudo lsof /var/log/syslog
Who uses something below this folder / mount? (“target is busy”)sudo lsof +D /data (or sudo lsof /data for the mount point)
What does this process have open?sudo lsof -p 1234
Everything a user has opensudo lsof -u anna
Everything a program has opensudo lsof -c nginx
Who uses port 443?sudo lsof -i :443
All network connectionssudo lsof -i -P -n
Deleted files still taking spacesudo lsof +L1

-P -n show port numbers and IPs instead of names (faster).

Disk full, but du finds nothing? A process still holds a deleted file open, so the space isn’t freed. sudo lsof +L1 shows it; restart that service (often a log file deleted by hand instead of rotated).

ss: ports and connections

ss replaces the old netstat (not installed by default).

WhatCommand
Listening ports with processsudo ss -tulpn
Only TCP / only UDP listenerssudo ss -tlpn / sudo ss -ulpn
Who listens on port 80?sudo ss -tlpn 'sport = :80'
All established TCP connectionsss -tn state established
Connections to a remote portss -tn 'dport = :5432'
Connections from one IPss -tn 'dst 10.0.0.21'
Count connections per statess -tan | awk 'NR>1 {print $1}' | sort | uniq -c
Summaryss -s

The letters: t TCP, u UDP, l listening, p process, n numeric.

Reading the address column:

Local addressReachable from
0.0.0.0:80 / [::]:80 / *:80everywhere (all interfaces)
127.0.0.1:5432only this server
10.0.0.11:8080only via that IP

ncdu: what fills the disk?

du gives numbers; ncdu gives an interactive, sorted browser of the biggest folders.

sudo apt install ncdu
sudo ncdu -x /          # -x: stay on this file system (skip /proc, other disks)
KeyDoes
↑ ↓ / Entermove / open folder
←back up
ddelete the selected file or folder (asks first)
gshow percentages / graph
iinfo about the item
qquit

Usual suspects: /var/log, /var/lib/docker, /var/cache/apt, /home, old kernels in /boot, core dumps in /var/crash. What to do about each: Disk full: find and free space.

Without ncdu:

sudo du -xh --max-depth=1 / | sort -h | tail
§ home
~/knubertus/home/
1,1 Top