Don't do this on the server-side!
(It is potentially dangerous because you can end up being locked-out of the remote machine). Instead, make use of ~/.ssh/config
like so:
tmux 3.1 or newer¹ on the remote machine
Into your local ~/.ssh/config
, put²:
Host myhost
Hostname host
User user
RequestTTY yes
RemoteCommand tmux new -A -s foobar
- As pointed out by @thiagowfx, this has the side effect of making it impossible to use, e.g.
ssh myhost ls /tmp
and should therefore not be used with Host *
... what I like to do is to have a Host myhost
section with RemoteCommand tmux ...
and then in addition to that I'll have a Host MYHOST
section without it.
- Instead of
RequestTTY yes
you could call ssh
with the -t
switch; thank you, @kyb.
- Off-topic, but if you're dealing with non-ASCII characters, I'd recommend to change that into
tmux -u …
for explicitly enabling Unicode support even on machines that don't have the proper environment variables set.
tmux 3.0a or older on the remote machine
Almost the same as above, but change the last line to³:
RemoteCommand tmux at -t foobar || tmux new -s foobar
¹ repology.org has a list of distros and their tmux versions
² new
is short for new-session
.
³ at
is short for attach-session
.
Only if, for some reason, you really, really can't do it client-side:
Using the remote's authorized_keys
file
If you would rather not have an ~/.ssh/config
file for whatever reason, or want the remote machine to force the connecting machine to connect to / open the session, add this to your remote ~/.ssh/authorized_keys
:
command="tmux at -t foobar || tmux new -s foobar" pubkey user@client
This will, of course, work from all clients having the corresponding private key installed, which some might consider an upside –– but: should anything go wrong, it might not be possible to connect anymore without (semi-)physical access to the machine!
~/.ssh/config
. The answer most people will probably need, is therefore stackoverflow.com/a/52838493/5354137.