Uniquely Identifying the Local TTY of an SSH Connection
Ethan Pailes
ethan at pailes.org
Sat Mar 4 08:11:28 AEDT 2023
I've managed to figure out a scheme using SendEnv. The way it works is that I add the following to my local .bashrc
```
export LC__LOCAL_TTY_NAME="ssh-$(basename $(tty))"
```
then on the same local machine add an entry to my .ssh/config
```
Host = remote
Hostname = my.remote.host
SendEnv LC__LOCAL_TTY_NAME
ControlPath ~/.ssh/cm-%r@%h:%p
ControlMaster auto
ControlPersist 10m
```
and finally in my .bashrc on my remote host I have an entry
```
if [[ $- =~ i ]] && [[ -n "$LC__LOCAL_TTY_NAME" ]]; then
exec shpool attach "$LC__LOCAL_TTY_NAME"
fi
```
I did try packing the tty name in TERM, but using that with SendEnv would have required mutating my local TERM in a way that could have messed up programs running locally.
This approach works great, but I would also like to be able to set things up so that I can explicitly name the session I want to connect to and do `ssh main` or `ssh edit` to go directly to my remote host and attach to a session named `main` or `edit`. The SetEnv ssh config option seems to be just what the doctor ordered in order to do this, so I've added a few blocks to my local .ssh/config
```
Host = main
Hostname = my.remote.host
SetEnv LC__LOCAL_TTY_NAME=main
ControlPath ~/.ssh/cm-%r@%h:%p
ControlMaster auto
ControlPersist 10m
Host = edit
Hostname = my.remote.host
SetEnv LC__LOCAL_TTY_NAME=edit
ControlPath ~/.ssh/cm-%r@%h:%p
ControlMaster auto
ControlPersist 10m
```
this sorta works, but there seems to be a strange interaction between the Control{Path,Master,Persist} options and SetEnv. If I try to immediately ssh to my remote host from two different terminals using `ssh main` then `ssh edit`, LC__LOCAL_TTY_NAME will get set to `main` in both, presumably because of some sticky state on the shared connection. Oddly, if I first do `ssh remote` in a separate terminal to use the SendEnv mechanism, then do `ssh main` and `ssh edit` in terminals two and three, this approach works as I was hoping and terminal two has LC__LOCAL_TTY_NAME set to `main` while terminal three has it set to `edit`. This feels like a bug in ssh to me, but maybe it is actually working as intended and I'm just holding it wrong.
On the assumption that this is a bug, I've been trying to repro locally by cloning and building https://github.com/openssh/openssh-portable.git, then running the sshd it builds locally and logging in with the ssh binary it builds. Would those two components contain everything that could be in play here, or do I need to worry about using the ssh-agent from HEAD as well? (I know my setup is using my system ssh-agent because I configured an authorized_keys file with my id_rsa.pub in it, then was able to log in to the locally running sshd with no password after running ssh-add).
More information about the openssh-unix-dev
mailing list