Skip to content

Instantly share code, notes, and snippets.

@samjonester
Last active May 23, 2022 11:36
Show Gist options
  • Save samjonester/1c316e785c7e85eb5d3305e380fe583c to your computer and use it in GitHub Desktop.
Save samjonester/1c316e785c7e85eb5d3305e380fe583c to your computer and use it in GitHub Desktop.
Tmate + Tmux pairing!

Tmate + Tmux pairing

Tmate is used as the "free reverse ssh tunnel". It is not super secure because a key is not required to connect, but it sure is conventient. Tmux is used inside the Tmate session to share multiple terminal windows


Here's the situation.

You've createe a new tmux session where you will do your work named foo.

tmux new-session -s foo

Then you've created a bunch of windows, splits, and running processes, and now you would like a pair. Uh-Oh! tmate won't work because you want to continue in this existing session.... or will it???


Turns out you can tmux inside tmate!

1a. Create the following file at ~/.tmate.conf.

## tmate

# Reassign prefix to not conflict with tmux
set -g prefix C-]
bind-key ] send-prefix

# turn off status bar so tmate is invisible
set -g status off

1b. Add the following functions to your ~/.bashrc.

# TMATE Functions

TMATE_PAIR_NAME="$(whoami)-pair"
TMATE_SOCKET_LOCATION="/tmp/tmate-pair.sock"

# Get current tmate connection url
tmate-url() {
  url="$(tmate -S $TMATE_SOCKET_LOCATION display -p '#{tmate_ssh}')"
  echo "$url" | tr -d '\n' | pbcopy
  echo "Copied tmate url for $TMATE_PAIR_NAME:"
  echo "$url"
}



# Start a new tmate pair session if one doesn't already exist
# If creating a new session, the first argument can be an existing TMUX session to connect to automatically
tmate-pair() {
  if [ ! -e "$TMATE_SOCKET_LOCATION" ]; then
    tmate -S "$TMATE_SOCKET_LOCATION" -f "$HOME/.tmate.conf" new-session -d -s "$TMATE_PAIR_NAME"
    sleep 0.3
    tmate-url
    sleep 1

    if [ -n "$1" ]; then
      tmate -S "$TMATE_SOCKET_LOCATION" send -t "$TMATE_PAIR_NAME" "TMUX='' tmux attach-session -t $1" ENTER
    fi
  fi
  tmate -S "$TMATE_SOCKET_LOCATION" attach-session -t "$TMATE_PAIR_NAME"
}



# Close the pair because security
tmate-unpair() {
  if [ -e "$TMATE_SOCKET_LOCATION" ]; then
    tmate -S "$TMATE_SOCKET_LOCATION" kill-session -t "$TMATE_PAIR_NAME"
    echo "Killed session $TMATE_PAIR_NAME"
  else
    echo "Session already killed"
  fi
}
  1. Open a pair session and attach to you existing tmux session.
tmate-pair foo
  1. After your done, close down tmate.
tmate-unpair
@megalithic
Copy link

@samjonester this still working for you on the latest tmux and tmate installed via homebrew?

this is what i end up getting with tmate-pair:

You must specify a socket name with -S. For example: 
  tmate -S /tmp/tmate.sock new-session -d
  tmate -S /tmp/tmate.sock wait tmate-ready

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment