Remote server, iTerm2, and tmux integration

Yes it is possible, jut make sure:

  • To have latest version of tmux installed remotely
  • Have most recent version of iterm2 installed locally

Login via ssh login@hostname -t 'tmux -CC' and voilà - this should open iTerm2 window on your local box logged into remote box.


TLDR

ssh <hostname> -t 'tmux -CC new -A -s tmssh'

Explanation

Inside an existing ssh session (assuming you are using iTerm2), you can simply run tmux -CC and a native iTerm2 window will open with tmux integration. This means that you have native scrolling, split screen, and copy-paste available to you.

  • tmux -CC opens tmux in control mode.

You can combine this with the ssh command to immediately open the native tmux window:

ssh login@hostname -t 'tmux -CC'
  • -t forces pseudo-tty allocation (allows control characters inside SSH)

The downside of this approach is that you will get a new tmux session each time, so you will not be able to reconnect to view long-running processes (unless you remember to run tmux -CC attach).

We can expand the command a little to create a named tmux session, create the session if it does not exist, or reconnect if the session already exists:

ssh <hostname> -t 'tmux -CC new -A -s tmssh'
  • new creates a new session
  • -A makes new-session behave like attach-session if session name already exists
  • -s tmssh creates a session named tmssh

Now you have a native iTerm2 tmux window, which you can close at any time, and reconnect to when needed.

Helper Function

Finally, to make life easier we can put this all into a helper function that you can add to your bashrc or zshrc:

# tmux+ssh helper function with iterm integration
function tmssh () {
  if [[ -z "$1" ]]; then
    me="${FUNCNAME[0]}${funcstack[1]}"
    echo "usage: $me [ssh-args] hostname"
    return 1
  fi

  ssh "$@" -t 'tmux -CC new -A -s tmssh'
}