美文网首页开发辅助技术
iterm2实现复制当前ssh会话

iterm2实现复制当前ssh会话

作者: _肉 | 来源:发表于2019-03-03 22:29 被阅读0次

    以前在用secure crt的时候,有一个比较好用的功能,clone session,会将当前的ssh的会话复制一个,并自动完成登录。在用mac后,用上了iterm2这个神器,但是却没有找到任何类似的功能,google也没有结果,始终不得其解,郁郁寡欢。

    然而,在阳光不是很明媚的某天,突然茅塞顿开,找到了实现的方法,解决了困扰我几个月的问题,记录如下。

    实现步骤

    1. 前提:ssh配置了密钥登录,或者ssh config配置ControlMaster实现ssh相同主机只输入一次密码。

    2. 创建两个脚本(clone_horizontally.scpt和clone_vertically.scpt),填入以下内容,并拷贝到~/Library/Application Support/iTerm2/Scripts/

      #clone_horizontally.scpt对应水平分割并克隆
      vi clone_horizontally.scpt
      tell application "iTerm2"
        tell current session of current window
          set tty_now to tty
          set clone_host to (do shell script "ps -o tty,command|grep $(echo " & tty_now & "|awk -F'/' '{print $3}')|grep '  ssh'|awk -F'  ' '{print $2}'")
          split horizontally with default profile command clone_host
        end tell
      end tell
      
      #clone_vertically.scpt对应竖直分割并克隆
      vi clone_vertically.scpt
      tell application "iTerm2"
        tell current session of current window
          set tty_now to tty
          set clone_host to (do shell script "ps -o tty,command|grep $(echo " & tty_now & "|awk -F'/' '{print $3}')|grep '  ssh'|awk -F'  ' '{print $2}'")
          split vertically with default profile command clone_host
        end tell
      end tell
      
    3. ssh上一台机器,点击iterm2菜单栏--Scripts下的对应脚本确保能分割屏幕并克隆ssh。

    4. 打开iterm2--Preferences--Keys,设置两个快捷键分别执行这两个脚本,比如command+s执行竖直分割克隆会话(clone_vertically.scpt),^+command+s执行水平分割克隆会话(clone_horizontally.scpt)。

    5. 大功告成。

    脚本实现思路

    1. iterm2支持applescript实现自动化操作。https://www.iterm2.com/documentation-scripting.html

    2. 利用iterm2提供applescript下Sessions的tty方法,返回当前会话的tty。

      Sessions
      These functions and properties are provided by sessions.
      ...
      tty
      
      The name of the session's tty (e.g., /dev/ttys01). Returns a string.
      
    3. 在shell下过滤此tty的进程,并获取到ssh的主机名或者ip。

    4. 利用iterm2提供applescript下Sessions的split方法,水平或竖直分割窗口并执行ssh当前主机的命令。

      Sessions
      These functions and properties are provided by sessions.
      ...
      split horizontally with default profile
      split vertically with default profile
      split horizontally with default profile command "command"
      split vertically with default profile command "command"
      
      Splits the session either horizontally or vertically. If the optional command is provided then it is run in place of the profile's command. A horizontal split has a horizontal divider, while a vertical split has a vertical divider.
      
      Returns a reference to a session.
      

    相关文章

      网友评论

        本文标题:iterm2实现复制当前ssh会话

        本文链接:https://www.haomeiwen.com/subject/caamuqtx.html