brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ssh -f -N -L runs a port forward in the background

Network and access
~/tips/tip-ssh-background-port-forward

ssh -f -N -o ExitOnForwardFailure=yes -M -S ~/.ssh/fwd.sock -L 8080:localhost:80 user@server

Opens a local port forward through SSH in the background, with a clean way to close it.

A port forward in the foreground takes over a terminal tab. With two more flags it runs quietly in the background.

ssh -f -N -o ExitOnForwardFailure=yes -M -S ~/.ssh/fwd.sock -L 8080:localhost:80 user@server
ssh -S ~/.ssh/fwd.sock -O check user@server
ssh -S ~/.ssh/fwd.sock -O exit user@server

The flags come straight from the ssh manual. -L 8080:localhost:80 forwards local port 8080 to port 80 as seen from the server. -N means do not execute a remote command, which the manual says is useful for just forwarding ports. -f asks ssh to go to the background just before command execution.

ExitOnForwardFailure=yes makes the client wait until the forward is established before it goes to the background, and exit with an error otherwise. Without it you can end up with a background process that has no forward at all.

The closing part is the reason for -M -S. They put the connection in master mode with a control socket. Then -O check checks that the master process is running, and -O exit asks it to exit. Without a socket, you have to find the process yourself with pgrep -af ssh and kill it.

After the forward is up, open http://localhost:8080 on your own machine.

The caveat is that a forgotten background tunnel keeps running, and the port stays reachable on your machine. By default it listens on the loopback address only, so keep it that way and do not add a wildcard bind address without a reason.

Further reading: OpenBSD manual: ssh

More Network and access tips scp -3 alice@server-a:/var/backups/db.sql.gz bob@server-b:/srv/restore/ tailscale exit-node suggest tailscale lock sign nodekey:1abddef1 tlpub:abcdef12 wg genpsk > peer1.psk Table = off All Network and access tips (163) All topics

Link