快轉到主要內容

zsh+Tmux+Mosh 持續連線機制設定

·162 字·1 分鐘

基於 Zsh 上的 Tmux 和 Mosh 持續連線機制設定記錄

因為最近因為使用大量的 Server 所以想說是否有能持續連線或是連回去還能保持之前的狀態,於是我就找到了 Tmux 和 Mosh 兩個工具來實現這個目標。

我這個方法是因為我很常換 Server 進行連線,如果各位只有固定的連線 Server 可以直接看 Reference 網頁寫的方式設定可以更方便!!

因為我本身是使用 Mac 搭配 iTerm2 作為 Terminal,並且使用 oh my zsh 所以就以 oh my zsh 為基礎來設定,其他 Linux 系統也可以使用類似的方式來設定。

安裝 tmux 和 mosh:
#

brew install tmux mosh

設定 tmux 和 mosh:
#

nano ~/.zshrc

在最尾端加上

mssh() {
    local target="$1"
    local port=22

    if [[ -z "$target" ]]; then
        echo "用法:mssh user@host [-p SSH_PORT]" >&2
        return 1
    fi

    shift

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -p)
                if [[ -z "$2" || "$2" == -* ]]; then
                    echo "錯誤:-p 後面必須提供 SSH Port" >&2
                    return 1
                fi

                port="$2"
                shift 2
                ;;
            *)
                echo "未知參數:$1" >&2
                return 1
                ;;
        esac
    done

    command mosh \
        --ssh="ssh -p $port" \
        "$target" \
        -- tmux new-session -A -s main
}

之後你就能輕鬆的在 Terminal 上使用 mssh 來透過 mosh+tmux 方式連線到遠端伺服器了。

mssh user@host [-p SSH_PORT]
注意 不只 Client 端需要安裝 mosh+tmux,Server 端也需要安裝 mosh+tmux 才能正常使用 mosh+tmux 方式連線!

Reference
#

遠端 Shell 連線設定:iTerm2+tmux+mosh