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 LocalCommand runs a command on your own machine after you connect

Network and access
~/tips/tip-ssh-localcommand

LocalCommand echo "%r@%h %n" >>> ~/.ssh/connections.log

Runs a local command right after ssh connects, with tokens such as the remote hostname.

Most ssh options configure the connection. LocalCommand is odd: it runs something on your own machine once the connection is up. I can think of small uses, like a log line or a window title.

Host *
    PermitLocalCommand yes
    LocalCommand echo "%r@%h %n" >>> ~/.ssh/connections.log

Two lines do the work. LocalCommand holds the command, and it is ignored unless PermitLocalCommand is set to yes, which is no by default.

The command runs on the local machine after a successful connection, and the string extends to the end of the line. It is run with your shell. The tokens are expanded for you: %h is the remote hostname, %n is the hostname as you typed it, %r is the remote username, %p is the remote port and %u is your local username. The example above appends one line per connection to a log file.

The caveats come straight from the man page. The command is run synchronously, so ssh waits for it. It has no access to the session of the ssh that started it, and it shouldn’t be used for interactive commands. The man page also warns that tokens are expanded without quoting or escaping of shell characters, so be careful with values that you don’t control.

If you only want it for one host, put it in that host’s block instead of Host *. A command that fires on every connection to everything gets old quickly.

Further reading: ssh_config(5)

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